Puppeteer Scraping: See XHR response data before request completes for real time data

I am using puppeteer to scrape a website for real time data in nodejs. Instead of scraping the page, I am watching the backend requests and capturing the JSON/TEXT responses so I have more structured data. (and seeing more data than what’s being displayed in the browser) Everything is working except some of the data is updated with a Firestore request. I can capture the response to that request, but only get the data when the request is complete.

If I monitor the request/response in the browser, I can see that there are several numbered “messages” in the response packet:

16
[[732,[“noop”]]]
16
[[733,[“noop”]]]
123
[[734,[{
“targetChange”: {
“resumeToken”: “CgkIgqb+n7TFiwM=”,
“readTime”: “2025-02-15T09:53:39.558146Z”
}
}
]]]
16
[[735,[“noop”]]]

with each message coming in over several seconds. At some point the request completes and a new firebase request is issued. The problem is I only see all these messages in my app once the response is complete and not in real time as each message comes in. (which my app requires in order to display changes in real time)

Is there a way to see the response data as it is received and not just when the request is completed?

    page.on('response', async (response) => {    
        if (response.request().resourceType() === 'xhr') {
            console.log('Firestore Response URL:', response.url());
            const theResponse = await response.text();
            console.log('response.text: ', theResponse);
        }
    }

Issues with Date Function on IOS

So I’m currently building a Website for my retro moped club and I’ve encountered an issue I am unable to solve. I am writing everything in plain JS (don’t hate me, I just like writing everything myself), HTML and CSS. For the members page, I use a JSON file which has all the members Data saved, including their birthdate. I’m using this JS code to calculate their age

// Fake data for Test
const member = {
  "Name": "John Doe",
  "Birthdate": "1990-07-15T00:00:00Z",
};

// Function to calculate age
const ageP = document.createElement("p");
const now = new Date();
const birthdate = new Date(member.Birthdate);

let age = now.getFullYear() - birthdate.getFullYear();

if (
  now.getMonth() < birthdate.getMonth() ||
  (now.getMonth() === birthdate.getMonth() && now.getDate() < birthdate.getDate())
) {
  age--;
}

console.log(`Birthdate: ${member.Birthdate}`);
console.log(`Age: ${age}`);

But for some reason, the calculation does not work on IOS Devices, no matter which browser I use.

Next.js UI Not Updating After Login Until Manual Refresh

I’m working on a Next.js 14 app with a login system that uses server actions and cookies for authentication. However, when I log in:

The UI does not update immediately after login.
Elements appear stuck together and unstyled until I manually refresh the page.
Once I refresh, everything looks normal.

Before Refreshing

After Refreshing

Here’s the code:

// API CODE 

import { executeQuery } from "@/app/lib/db";
import { NextRequest, NextResponse } from "next/server";
import bcrypt from "bcryptjs";
import * as jose from "jose";

export async function POST(request: NextRequest) {
  try {
    const { Email, Password } = await request.json();

    const user = await executeQuery("SELECT * FROM user WHERE Email = ?", [Email]);

    if (!user || user.length === 0) {
      return NextResponse.json({ error: "Wrong email" }, { status: 400 });
    }

    const isCorrectPassword = await bcrypt.compare(Password, user[0].Password);

    if (!isCorrectPassword) {
      return NextResponse.json({ error: "Wrong password!" }, { status: 400 });
    }

    const secret = new TextEncoder().encode(process.env.JWT_SECRET);
    const alg = "HS256";

    const jwt = await new jose.SignJWT({ UserID: user[0].UserID, Email: user[0].Email })
      .setProtectedHeader({ alg })
      .setExpirationTime("2h")
      .setSubject(user[0].UserID.toString())
      .sign(secret);

    return NextResponse.json({ token: jwt });
  } catch (error) {
    return NextResponse.json({ message: error || "Server error" }, { status: 500 });
  }
}
// Log-in Action

"use server";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";

export default async function logInAction(
  currentState: any,
  formData: FormData
): Promise<string> {
  const email = formData.get("email");
  const password = formData.get("password");

  const response = await fetch(new URL("/api/login", "http://localhost:3000"), {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ Email: email, Password: password }),
  });

  const json = await response.json();

  cookies().set("Authorization", json.token, {
    secure: true,
    httpOnly: true,
    expires: Date.now() + 24 * 60 * 60 * 1000 * 3, // 3 days
    path: "/",
    sameSite: "strict",
  });

  if (response.ok) {
    redirect("/homepage");
  } else {
    return json.error;
  }
}
// Login Page

"use client";
import React from "react";
import "@/app/styles/login-style.css";
import Image from "next/image";
import loginLogo from "@/public/haytek-login-logo.png";
import { Button, Form } from "react-bootstrap";
import "bootstrap/dist/css/bootstrap.min.css";
import { useFormState } from "react-dom";
import logInAction from "./loginAction";
import Link from "next/link";

const LogInPage = () => {
  const [error, formAction] = useFormState(logInAction, undefined);
  return (
    <main>
      <Image src={loginLogo} alt="Logo" style={{ pointerEvents: "none" }} />
      <div className="log-in-container">
        <Form className="login-form" action={formAction}>
          <Form.Group className="form-group">
            <Form.Label>Email:</Form.Label>
            <Form.Control
              name="email"
              type="email"
              placeholder="Enter your email"
              required
            />
          </Form.Group>
          <Form.Group className="form-group">
            <Form.Label>Password:</Form.Label>
            <Form.Control
              name="password"
              type="password"
              placeholder="Enter your password"
              required
            />
          </Form.Group>
          <Button variant="primary" type="submit" className="submit-button">
            Log In
          </Button>
          {error && <p className="error-message">{error}</p>}
          <Link href={"/signup"} className="form-link">
            Don't have an account? Sign up
          </Link>
        </Form>
      </div>
    </main>
  );
};

export default LogInPage;

Created npm Package but not able to load :: Module not found:

I have created the react component and trying to create the package of it and publish it.
I was testing it with npm link as well as npm install but after compiling it always gives an error :: Module not found. Even though it is present in the node modules.

package.json

{
  "name": "field-input",
  "version": "0.0.1",
  "description": "Input Field Component",
  "main": "dist/index.js",
  "module": "dist/index.mjs",
  "types": "dist/index.d.ts",
  "scripts": {
    "build": "tsup",
    "lint": "tsc"
  },
  "keywords": [
    "react",
    "component",
    "input",
    "field"
  ],
  "author": "fastkit",
  "license": "ISC",
  "peerDependencies": {
    "react": "^18.2.0",
    "react-dom": "^18.2.0"
  },
  "dependencies": {
    "lodash": "^4.17.21",
    "lucide-react": "^0.475.0"
  },
  "devDependencies": {
    "@tailwindcss/postcss": "^4.0.6",
    "@tsconfig/recommended": "^1.0.8",
    "@types/lodash.debounce": "^4.0.9",
    "@types/react": "^18.3.18",
    "@types/react-dom": "^18.3.5",
    "autoprefixer": "^10.4.20",
    "esbuild": "^0.25.0",
    "esbuild-css-modules-plugin": "^3.1.4",
    "postcss": "^8.5.2",
    "tailwindcss": "^4.0.6",
    "tsup": "^8.3.6",
    "typescript": "^5.7.3"
  }
}

tsconfig.ts

{
  "compilerOptions": {
    "strict": true,
    "noImplicitAny": true,
    "esModuleInterop": true,
    "strictNullChecks": true,
    "target": "ESNext",
    "moduleResolution": "node",
    "module": "ESNext",
    "declaration": true,
    "jsx": "react-jsx",
    "outDir": "dist"
  },
  "include": ["src"],
  "exclude": ["node_modules"]
}

tsup.config.ts

import { defineConfig } from "tsup";
export default defineConfig({
  entry: ["src/index.ts"],
  format: ["esm", "cjs"],
  minify: true,
  dts: true,
  outDir: "dist",
  sourcemap: true,
  clean: true,
});

/src/index.ts

import "./index.css";
import FieldInput from "./FieldInput";
export default FieldInput;

/src/Index.tsx

React Component

USAGE

"use client"
import FieldInput from "field-input";
export default function Home() {
  return (
    <div className="">
      <FieldInput label="test"/>
    </div>
  );
}

How to make the field-sizing property regain control after a resize

Width the new field-sizing CSS property, you can allow certain form related elements to grow/shrink in size as content is inputted. (Only supported on Chrome as of writing this: caniuse)

If you input some text into the textarea in the snippet below, you can see the feature working. However, if you use the resize feature of the textarea at all, you will notice the field-sizing feature completely stops working. It is as if the browser just removes the property from the element after it has been resized.

My question is: how can we allow the field-sizing property to continue to work after a resize has occurred?

I have tried programatically setting resize: none; and field-sizing: content; after the resizing but nothing seems to allow the field-sizing property to regain control.

textarea {
  field-sizing: content;
  min-width: 6rem;
  max-width: 16rem;
}
<textarea></textarea>

How do you get the datetimeoffset in c# that comes back from sqlserver as dattimeoffset and return this value in javascript date to get local datetime

I have this object:

        public partial class TblThread
        {
            public int Id { get; set; }

            public string? Guid { get; set; }

            public int? FrameworkId { get; set; }

            public string? Title { get; set; }

            public string? Question { get; set; }

            public string? Tags { get; set; }

            public DateTimeOffset? DateCreated { get; set; }

            public int? UserId { get; set; }

            public virtual TblUser? User { get; set; }
        }

The DateCreated field in the database has the datatype as DateTimeOffset(7) and default value is (getutcdate())

But when i do this and look at the value:

@thread.DateCreated 

this value returns this:

"15/02/2025 07:07:37 &#x2B;00:00"

But the value in the database is:

2025-02-15 07:07:37.2366667 +00:00

So how do i return the datetimeoffset from c# and get the localtime from the utc timestamp in new Date() in javascript?

Mobile Video Play/Pause Toggle Not Working Reliably (SwiperJS Slider)

I’m using Swiper JS to create a slider of TikTok videos on my website. I’ve implemented a feature where users can click on the video itself to toggle between play and pause. This works perfectly on desktop browsers. However, on mobile devices, the play/pause toggle is unreliable. It doesn’t work. It seems like the video element’s play() and pause() methods are not being triggered on mobile.

document.addEventListener('DOMContentLoaded', function() {
    const swiper_video = new Swiper('.tiktok-carousel', {
        loop: true, // Enable infinite loop
                slidesPerView: "auto", // or number for fixed slides
                spaceBetween: 10, // Space between slides
                centeredSlides: true, // Center the active slide
                pagination: {
                    el: ".swiper-pagination",
                    clickable: true,
                },
                navigation: {
                    enabled: false,
                    nextEl: ".swiper-button-next",
                    prevEl: ".swiper-button-prev",
                },
                breakpoints: {
                    769: {
            navigation: {
              enabled: true
            },
                        slidesPerView: 2,
                    },
           1100: {
            navigation: {
              enabled: true
            },
                        slidesPerView: 2,
                        centeredSlides: true,
                   },
    });

    swiper_video.on('init', () => {
        const videos = document.querySelectorAll('.tiktok-embed');
        videos.forEach(video => {
            let isManuallyPaused = false;
            let touchTimeout;

            video.addEventListener('touchstart', function(event) {
                event.preventDefault();
                clearTimeout(touchTimeout);

                touchTimeout = setTimeout(() => {
                    togglePlayPause(video);
                }, 200);

            });

            video.addEventListener('click', function(event) {
                event.stopPropagation();
                togglePlayPause(video);
            });

            video.addEventListener('play', function() {
                isManuallyPaused = false;
            });

            video.addEventListener('pause', function() {
                if (!isManuallyPaused) {
                    video.play();
                }
            });

            function togglePlayPause(video) {
                if (video.paused) {
                    video.play();
                    isManuallyPaused = false;
                } else {
                    video.pause();
                    isManuallyPaused = true;
                }
            }
        });
    });

    swiper_video.on('transitionEnd', () => {
        const videos = document.querySelectorAll('.tiktok-embed');
        videos.forEach(video => {
            video.pause();
        });
    });
});

What I’ve tried:

  • Using event.stopPropagation() in the click handler.
  • Using both touchstart and click event listeners.
  • Implementing the isManuallyPaused flag.
  • Using setTimeout to introduce a delay.
  • Ensuring event listeners are attached after Swiper initialization.

This issue only persists on mobile phone browsers. I suspect it might be related to how mobile browsers handle touch events and video playback. I need a solution that works consistently on both desktop and mobile.

Extracting YouTube Data

I found this snippet of console JavaScript on a YouTube video. The purpose of it is to extract information about YouTube video(s) including: title(s), date(s), URL(s), and view count(s). A majority of the code works returning everything correctly except for the view count.

window.clearInterval(scroll); console.clear(); urls = $$('a'); urls.forEach(function(v,i,a){if (v.id=="video-title-link" && v.href){console.log('t'+new Date().toLocaleDateString()+'t'+v.title+'t'+v.href+'t'+v.__shady_native_innerHTML.match(/aria-label="(.+?)"/g)?.[0].match(/[d,]+ views/g)[0]+'t')}});

In the console its just returing as undefined. Could someone please modify the code so that it properly returns the view count? Thank you!

Nodejs Webscoket discord bot authorization

I tried logging in using my credentials, and I expected the WebSocket connection to recognize my session and allow me to stay connected. However, even after successful authentication, the server still says I am not logged in and disconnects me with the error “Connection rejected – Missing token!”. I also checked that my access token is being generated, but it seems like the server isn’t recognizing it properly in the WebSocket connection.

It looks like my WebSocket connection is being rejected due to a missing token, even though I successfully log in. After logging in, the server still says I’m not authenticated and disconnects me. The error message states: “Connection rejected – Missing token!” even though my login details and access token are valid. The issue might be related to token validation, session handling, or the way the token is being passed in the WebSocket connection.

I tried logging in using my credentials, and I expected the WebSocket connection to recognize my session and allow me to stay connected. However, even after successful authentication, the server still says I am not logged in and disconnects me with the error “Connection rejected – Missing token!”. I also checked that my access token is being generated, but it seems like the server isn’t recognizing it properly in the WebSocket connection.

error log
Custom Command (Use arrow keys)
❯ Change Mode
Change Password
Change Prefix
Kick Player
Ban IPAdress
Unban IPAdress
Restart Server ❌ Odrzucono połączenie WebSocket – użytkownik niezalogowany!
❌ Odrzucono połączenie WebSocket – użytkownik niezalogowany!
Otrzymany query: [Object: null prototype] { code: ‘8w2GBb2puGgcoJ07ex4dwuV3GmN9zs’ }
Token data: {
token_type: ‘Bearer’,
access_token: ‘UazoCEWwk7JZBebza6PDshV3mMnIn2’,
expires_in: 604800,
refresh_token: ‘y6kpQZi2QBoqL8BZQhDITN9lxLTYcT’,
scope: ‘identify’
}
User data: {
id: ‘1186727516774334516’,
username: ‘xx_ksgaming_xx’,
avatar: ‘6d761d8ef76fdd9e799634f49d3034cd’,
discriminator: ‘0’,
public_flags: 128,
flags: 128,
banner: null,
accent_color: null,
global_name: ‘!KoKsus’,
avatar_decoration_data: null,
banner_color: null,
clan: null,
primary_guild: null,
mfa_enabled: false,
locale: ‘en-GB’,
premium_type: 0
}
❌ Odrzucono połączenie WebSocket – użytkownik niezalogowany!

here is code

require("dotenv").config()
const WebSocket = require("ws")
const msgpack = require("msgpack-lite")
const http = require("http")
const url = require("url")
const inquirer = require("inquirer")
const fetch = require("node-fetch")
const package = require("./package.json")
const { exec } = require('child_process');
var fs = require('fs');
var path = require('path');
const express = require("express")
const session = require("express-session");
const marked = require('marked');
const sessions = {}; // Przechowywanie sesji w zależności od adresu IP
const { URLSearchParams } = require('url')
const app = express()
const SESSIONS = {}; // Przechowywanie sesji użytkowników

const CLIENT_ID = process.env.DISCORD_CLIENT_ID;
const CLIENT_SECRET = process.env.DISCORD_CLIENT_SECRET;
const REDIRECT_URI = process.env.DISCORD_REDIRECT_URI;


function getDiscordAuthURL() {
    return `https://discord.com/api/oauth2/authorize?client_id=${CLIENT_ID}&redirect_uri=${encodeURIComponent(REDIRECT_URI)}&response_type=code&scope=identify`;
}

const httpServer = http.createServer((req, res) => {
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("Access-Control-Allow-Methods", "OPTIONS, GET");
    res.setHeader("Access-Control-Allow-Headers", "*");
    
    const parsed = url.parse(req.url, true);
    
    if (req.url.startsWith("/auth/login")) {
        res.writeHead(302, { Location: getDiscordAuthURL() });
        return res.end();
    }

    if (req.url.startsWith("/auth/callback")) {
        handleAuthCallback(req, res);
        return;
    }
    
    let filePath = parsed.pathname === "/" ? "./static/index.html" : path.join("static", path.normalize(parsed.pathname));
    
    fs.readFile(filePath, (err, content) => {
        if (err) {
            res.writeHead(404, { "Content-Type": "text/plain" });
            return res.end("Not Found");
        }
        res.writeHead(200, { "Content-Type": getContentType(filePath) });
        res.end(content);
    });
});

async function handleAuthCallback(req, res) {
    const query = url.parse(req.url, true).query;
    console.log("Otrzymany query:", query);  // Logowanie przekierowania z Discorda
    if (!query.code) {
        res.writeHead(400, { "Content-Type": "text/plain" });
        return res.end("Brak kodu autoryzacji.");
    }
    try {
        const tokenResponse = await fetch("https://discord.com/api/oauth2/token", {
            method: "POST",
            headers: { "Content-Type": "application/x-www-form-urlencoded" },
            body: new URLSearchParams({
                client_id: CLIENT_ID,
                client_secret: CLIENT_SECRET,
                grant_type: "authorization_code",
                code: query.code,
                redirect_uri: REDIRECT_URI
            })
        });
        const tokenData = await tokenResponse.json();
        console.log("Token data:", tokenData);  // Logowanie odpowiedzi z Discorda
        if (!tokenData.access_token) throw new Error("Nie udało się pobrać tokena!");

        const userResponse = await fetch("https://discord.com/api/users/@me", {
            headers: { Authorization: `Bearer ${tokenData.access_token}` }
        });
        const userData = await userResponse.json();
        console.log("User data:", userData);  // Logowanie danych użytkownika
        
        const sessionId = Math.random().toString(36).substr(2, 9);
        SESSIONS[sessionId] = userData.id;
        
        res.writeHead(302, {
            "Set-Cookie": `session=${sessionId}; Path=/; HttpOnly`,
            "Location": "/"
        });
        res.end();
    } catch (err) {
        console.error("Błąd autoryzacji:", err);
        res.writeHead(500, { "Content-Type": "text/plain" });
        res.end("Błąd autoryzacji.");
    }
}


function getContentType(filePath) {
    const ext = path.extname(filePath);
    const types = {
        ".js": "text/javascript",
        ".css": "text/css",
        ".json": "application/json",
        ".png": "image/png",
        ".jpg": "image/jpeg",
        ".mp3": "audio/mpeg",
        ".txt": "text/plain",
        ".wav": "audio/wav"
    };
    return types[ext] || "text/html";
}

httpServer.on("upgrade", (request, socket, head) => {
    const pathname = url.parse(request.url).pathname?.replace(//$/, "")
    
    // Sprawdzenie, czy ścieżka to /server
    if (pathname === "/server") {
        const userId = getSession(request);  // Pobierz dane sesji

        // Jeśli sesja nie istnieje, połączenie jest odrzucane
        if (!userId) {
            console.log("❌ Odrzucono połączenie WebSocket - użytkownik niezalogowany!");
            return socket.destroy();  // Zniszcz socket, jeśli nie ma sesji
        }

        console.log(`✅ Połączony użytkownik Discord ID: ${userId}`);

        // Obsługuje upgrade WebSocket
        server.handleUpgrade(request, socket, head, (ws) => {
            server.emit("connection", ws, request);
        });
    } else {
        // Jeśli ścieżka nie jest poprawna, połączenie jest odrzucane
        socket.destroy();
    }
});

// Funkcja do pobierania sesji z ciasteczka
function getSession(request) {
    const cookieHeader = request.headers.cookie;
    if (!cookieHeader) return null;

    // Parse cookies
    const cookies = Object.fromEntries(cookieHeader.split("; ").map(c => c.split("=")));
    return SESSIONS[cookies.session] || null;  // Zwraca sesję, jeśli istnieje
}


    
    httpServer.listen(PORT, () => {
        setupServer()
        commandStart()
    })
    

    const banIps = './data/BannedIps.json';
    
    async function commandStart() {
        console.clear();
        console.log(`Listening at http://localhost:${PORT}n`);
        const command = await inquirer.prompt({
            name: "command",
            type: "list",
            message: "Custom Command",
            choices: ["Change Mode", "Change Password", "Change Prefix", "Kick Player", "Ban IPAdress", "Unban IPAdress", "Restart Server"]
        });
    
        if (command.command === "Change Mode") {
            const mode = await inquirer.prompt({
                name: "mode",
                type: "list",
                message: "Select mode",
                choices: ["NORMAL", "SANDBOX", "ARENA", "HOCKEY"]
            });
            const modeType = [["HOCKEY"], ["SANDBOX", "NORMAL"], ["ARENA"]];
            function areInSameGroup(arg1, arg2, arg3) {
                for (const group of modeType) {
                    if (group.includes(arg1) && group.includes(arg2) && group.includes(arg3)) {
                        return true;
                    }
                }
                return false;
            }
    
            if (areInSameGroup(MODE, mode.mode)) {
                MODE = mode.mode;
            } else {
                const restart = await inquirer.prompt({
                    name: "restart",
                    type: "confirm",
                    message: "Are you sure you want to restart server?"
                });
                if (restart.restart) {
                    MODE = mode.mode;
                    setupServer();
                }
            }
        } else if (command.command === "Change Password") {
            const password = await inquirer.prompt({
                name: "password",
                type: "input",
                message: "Input password:"
            });
            PASSWORD = password.password;
        } else if (command.command === "Change Prefix") {
            const prefix = await inquirer.prompt({
                name: "prefix",
                type: "list",
                message: "Select prefix",
                choices: ["!", "?", "/", "\", "`", "'", '"', ":", "|", ";", "<", ">", ",", ".", "~"]
            });
            PREFIX = prefix.prefix;
        } else if (command.command === "Kick Player") {
            const sid = await inquirer.prompt({
                name: "sid",
                type: "input",
                message: "Input player sid:"
            });
            const sidNumber = Number(sid.sid);
            if (!isNaN(sidNumber)) {
                for (let i = 0; i < players.length; i++) {
                    let tmpPlayer = players[i];
                    if (tmpPlayer.sid === sidNumber) {
                        connection[tmpPlayer.id].close();
                        break;
                    }
                }
            }
        } else if (command.command === "Restart Server") {
            const restart = await inquirer.prompt({
                name: "restart",
                type: "confirm",
                message: "Are you sure you want to restart server?"
            });
            if (restart.restart) {
                setupServer();
            }
        } else if (command.command === "Ban IP") {
            const ipInput = await inquirer.prompt({
                name: "ip",
                type: "input",
                message: "Enter IP address to ban:"
            });
            const bannedIp = ipInput.ip;
    
            if (!bannedIp) {
                console.log("Invalid IP address.");
            } else {
                let bannedIps = [];
                if (fs.existsSync(banIps)) {
                    const fileData = fs.readFileSync(banIps, 'utf8');
                    try {
                        bannedIps = JSON.parse(fileData);
                    } catch (error) {
                        console.log("Error parsing BannedIps.json, resetting file.");
                    }
                }
    
                if (!bannedIps.includes(bannedIp)) {
                    bannedIps.push(bannedIp);
                    fs.writeFileSync(banIps, JSON.stringify(bannedIps, null, 2));
                    console.log(`IP ${bannedIp} has been banned.`);
                } else {
                    console.log("This IP is already banned.");
                }
            
        }
    } else if (command.command === "Unban IPAdress") {
        const ipInput = await inquirer.prompt({
            name: "ip",
            type: "input",
            message: "Enter IP address to unban:"
        });
        const unbanIp = ipInput.ip;

        if (!unbanIp) {
            console.log("Invalid IP address.");
        } else {
            let bannedIps = [];
            if (fs.existsSync(banIps)) {
                bannedIps = JSON.parse(fs.readFileSync(banIps, 'utf8'));
            }

            if (bannedIps.includes(unbanIp)) {
                bannedIps = bannedIps.filter(ip => ip !== unbanIp);
                fs.writeFileSync(banIps, JSON.stringify(bannedIps, null, 2));
                console.log(`IP ${unbanIp} has been unbanned.`);
            } else {
                console.log("This IP is not in the banned list.");
            }
        }
    }
        commandStart();
    }

Devtools console: Function was resolved from bound function

Browsers have a window.stop() function which I have overwritten for my own purposes:

window.stop = (s,t,o,p=window) => ...

I’m trying to troubleshoot why calling my stop() function does not work in some contexts, such as inside a function called from an anonymous function that is itself called via setTimeout(). In one part of my project where the code malfunctions I have inserted the following:

console.log('calling console.log(stop) on the next line');
console.log(stop);

Then, I opened the browser console and typed console.log(stop) which yielded the expected output.

This is all exhibited in the following screenshot:

screenshot of browser console output indicating the stop() function is native code

Note the little blue ‘i’ icon, which I hovered the mouse over.

What does ‘Function was resolved from bound function‘ mean and how can I prevent that, such that my stop() function is called instead of the native one?

VSCode’s “TypeScript and JavaScript Language Features” duplicates warnings when ESLint is enabled, but shows no warnings otherwise

Trying to get basic ESLint working in a non-TypeScript repository, but VSCode won’t stop showing me warnings from “ts” despite not having TypeScript anywhere in my project. After some experimenting I realized that these warnings come from the built-in “TypeScript and JavaScript Language Features” extension, and disabling that extension gets rid of them. However, these warnings only pop up when I have the ESLint extension enabled. If I disable the ESLint extension, the warnings go away.

This creates a situation where I either have to see duplicated warnings (one from eslint and another from ts) or no warnings at all.

For example, declaring a variable and then never using it generates these two warnings:

'myVariable' is declared but its value is never read. ts(6133)
'myVariable' is defined but never used. eslint(no-unused-vars)

How can I stop VSCode from automatically giving me these warnings? If I was using TypeScript in my project I could turn these off in tsconfig.json, but I’m not even using TypeScript so I’m unsure of how to approach this. I’d like to use ESLint instead of VSCode’s default, non-configurable IntelliSense. I found two other threads asking about this on StackOverflow but none of the answers worked for me.

Also curious: Why does VSCode only show the warnings from “ts” when I have the ESLint extension enabled? I don’t see why those two things would be related.

Why was there no need (or was there) for a TypeScript for Python? [closed]

If I understand correctly, TypeScript was invented to catch type errors at compile time that would otherwise only be exposed at runtime in JavaScript, as JavaScript by definition is dynamically-typed.

I can see how being able to reassign any value to a variable or to create properties on the fly is not practically useful. And when you do, it is probably unintentional and can easily break things in large projects.

But these problems are not unique to JavaScript. But there are languages X where X have the same shortcomings but never had a widely adopted TypeScript equivalent of X. For concreteness let’s say X = Python.

Am I missing anything or making false assumptions? Did I misunderstand the nature of the problem TypeScript was invented to solve? People do write large projects in Python, and Python does have the shortcomings of JavaScript for large projects, right?

JSXGraph: Can’t zoom out all the way when maxBoundingBox is set

This is for JSXGraph 1.10.1.

I’m trying to set up a graph with both pan and zoom enabled. I also set a maxBoundingBox because I don’t want my users to stay within a certain area of the graph.

Here’s a JSFiddle to illustrate this. The initial bounds of the graph is set to be equal to the maxBoundingBox. When I zoom in, then try zooming back out all the way, the zoom-out stops before hitting the maxBoundingBox. I would expect the zoom to stop at the maxBoundingBox, not before.

I’ve tried setting zoom: { min: someParticularNumber } in place of maxBoundingBox to control & limit the zoom-out. I’d find the value of someParticularNumber so that the minimum zoom matches the bounds I want to enforce. This almost works, except it doesn’t limit panning maxBoundingBox does; the user will be able to pan outside my desired bounded area.

I tried setting both zoom: { min: someParticularNumber } and maxBoundingBox. But the zoom-out still stops before hitting the maxBoundingBox.

Is there a way set panning and zoom that meets these requirements?

  • Panning is limited to some maxBoundingBox.
  • A user can zoom in, then zoom out until the bounds of the graph exactly matches the maxBoundingBox and not before.

How do I fix my decryption code for caesar cypher in Javascript

I am fairly new to coding and learning Javascript as my first language. I was tasked with creating a caeser cypher that shifts and unshifts by 42 characters while also inserting a random character ever two characters.

I was given a encrypted message to solve, which is the console.log() at the bottom, and the code solved that correctly and gave me the answer, but when I try to make my own encryption and then reverse it, it returns something different. which leads me to believe that their may be a problem with the encryption half of the code.

I’m also unsure what the best way to pass through all non-alphabet characters such as spaces, exclamation marks, etc…, would be.

const alphabet = "abcdefghijklmnopqrstuvwxyz";

// encryption code
function encrypt(message, shiftValue) {
  let encryptedMessage = ""; // a place for the encrypted value to be stored
  for (let i = 0; i < message.length; i++) {
    let char = message[i].toLowerCase(); //converts everything to lowercase
    if (alphabet.includes(char)) {
      const index = alphabet.indexOf(char); // if alphabet inclues character find its index
      const newIndex = (index + shiftValue) % alphabet.length; //adds shift value while looping around to the beginning of the alphabet
      encryptedMessage += alphabet[newIndex]; //adds and stores the new shifted version as the encrypted message
    }
    if ((i + 1) % 2 === 0) {
      //adds random letter every 2 character
      const randomIndex = Math.floor(Math.random() * 26);
      encryptedMessage += alphabet[randomIndex];
    } else {
      encryptedMessage += char; // if character is not part of alphabet passes it through to encrypted message
    }
  }

  return encryptedMessage;
}

//decryption code
function decrypt(encryptedMessage, shiftValue) {
  let decryptedMessage = "";

  for (i = 0; i < encryptedMessage.length; i++) {
    if ((i + 1) % 3 !== 0) {
      // this ignores random letters that were added every 2 characters
      const char = encryptedMessage[i].toLowerCase();
      const index = alphabet.indexOf(char);
      if (index >= 0) {
        let newIndex = index - shiftValue;
        while (newIndex < 0) newIndex += alphabet.length; //avoids negative index so decrypt doesnt return undefined
        decryptedMessage += alphabet[newIndex % alphabet.length];
      } else {
        decryptedMessage += char; // if character is not part of alphabet passes it through to encrypted message
      }
    }
  }

  return decryptedMessage;
}

console.log(
  decrypt(
    "Iueuan jrxuq cjythdykwxaj mixkqtaeml ebv wHenckvbkei rqdmt fHukckvi.r Jbxuihus, tmxayiwfuxh sjxau amenhtv 'zQkhhuubyjkit' yjew jhxux mxydatij. zJxmu hvymhihj ajel kldlsuyjb dyju yid uekdh qIbkqsxa xsxqqdvduzb wuqzhdoi qjxwu waueo xjem jfxuy dpuntj dgkvuiwj.",
    42
  )
);

node/no-extraneous-require “resolvePaths” option doesn’t seem to work with relative paths in VSCode

I’m currently running eslint ^8.13.0 and eslint-plugin-node ^11.1.0. My repository has a package.json file in the root directory as well as an additional package.json file in a child directory.

I’m currently seeing a node/no-extraneous-require error on several packages. These packages are listed dependencies in the root package.json however the file that’s importing them is in the directory that contains the second package.json file.

This issue seems like it would be easily fixed by adding the following to .eslintrc.json (which is also located in the root directory).

    "rules": {
        "node/no-extraneous-require": ["error", {
            "resolvePaths": ["./node_modules"],
        }]
    }

The above, however, does not resolve the issue. I’m using VSCode and wondering if anyone has experiences a similar issue using with relative paths in an eslintrc.json file and/or if the path itself seems to be incorrect in some way.

Paths I’ve tried:
“.”
“./”
“./node_modules”
“./node_modules/”