Why does this pattern cause problems for Regexr? [closed]

I’ve been working on a YouTube ID parsing regex (because none of the available ones are complete) on RegExr.com and I found a pattern that works great. However, when the page first loads, it ALWAYS throws an error.

Exec Error: The expression took longer than 250ms to execute.

The pattern doesn’t take longer than 250ms though. If I make ANY edit to the pattern (e.g. add a space and then remove it), it runs quickly, and perfectly does what I need it to.

A couple of other weird things occur in the execution reporting though.

  1. The UI says “41 matches (0.0ms)”. O.0ms?!
  2. When I hover that same element, there is a message: “No matches found in 1609 characters”.

So, the pattern is effective, but something about it is really throwing the Regexr execution reporting. Any ideas? Is there something wrong with the pattern itself?

Here is the pattern:

/(?:https?://|//)?(?:www.|m.|music.)?(?:youtube.com|youtu.be){1}(/live/|/v/|/embed/|/watch?v=|/w+?v=|/)([w-]+)??.*/gi

Please see the linked page for the demo to see the functionality I described.

reCaptcha Enterprises “Permission denied for: recaptchaenterprise.assessments.create”

I’m setting up a reCaptcha for a client with an Enterprise Google Cloud account.
I used an API Key, which is the easiest based on my client files configuration.
Everything works well until I call the https://recaptchaenterprise.googleapis.com/v1/projects/ url.

I get this error as my curl response :

{
  "error": {
    "code": 403,
    "message": "Permission denied for: recaptchaenterprise.assessments.create. Please ensure you have sufficient permissions: https://cloud.google.com/iam/docs/granting-changing-revoking-access",
    "status": "PERMISSION_DENIED"
  }
}

Here’s my code :


$verify_url = "https://recaptchaenterprise.googleapis.com/v1/projects/PROJECT_ID/assessments?key=API_KEY";
$data = [
    "event" => [
        'expectedAction' => 'CONTACT_FORM',
        "token" => $recaptcha_token,
        'siteKey' => $google_site_key
    ]
];

$ch = curl_init($verify_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

$response = curl_exec($ch);
curl_close($ch);

$response_data = json_decode($response);

I tried setting up a Service Account with “reCAPTCHA Enterprise Agent”
access rights but nothing works (and I don’t understand how the API Key is supposed to be linked to the Service Account).
I removed all restrictions from the API Key to test but it does not work.

Piece of advice with the structure of a project in the front

Hello there I am a junior developer finishing my professional training. I am encountering some problems when I try to advance with my final project a small CRM. I do not know what approach should I use when I receive the data from the back end(PHP) and I have to send it to the front (user inteface), I have tested it with postman and i get to see the data, but when it comes to the front, i do not know if there is a schema or architecture to use ( I am using JavaScript by the way). I am trying to use a single page pattern but it is getting messy and i am afraid that i wont be able to organize it as it should. Can someone with more experience give me some piece of advice? or a source with good information to see how to can i connect the front-end and the back-end using a single page patter?

I have tried to use a script.js that deal with the information. Currently I have a dashboard that i generate once that i have a valid login. But the file is getting messy, and i dont know if I should have several files instead of one big script.

How to simulate a cloth falling over a cube (table) using Three.js and a physics engine?

I’m trying to create a realistic animation in Three.js where a tablecloth (plane mesh) falls naturally onto a table (cube mesh), with the edges hanging and folding due to gravity.

I want the cloth to:

React to physics and gravity

Collide with the cube (table) as it falls

Be textured with a tileable tablecloth pattern

I’ve read that I might need a physics engine like Ammo.js or Cannon.js, but I’m not sure how to simulate the cloth realistically or map the texture correctly on a dynamic mesh.

AWS IoT Core WebSocket MQTT via React

I’m trying to connect a web client to AWS IoT Core using JavaScript over WebSocket, authenticated via Amazon Cognito Identity Pool.

The connection works (confirmed via logs), and the subscription to the topic is successful, but I do not receive any messages, even though messages are actively published (verified using AWS Test Client).

I have granted permissions to the unauthenticated role used by Cognito and also attached the policy to the certificate used by the device.

IAM Policy used:

{
“Version”: “2012-10-17”,
“Statement”: [
{
“Effect”: “Allow”,
“Action”: [
“iot:Connect”,
“iot:Subscribe”,
“iot:Receive”,
“iot:Publish”
],
“Resource”: “*”
}
]
}

JavaScript code:

// --- Configuration ---
const AWS_REGION = '';
const COGNITO_IDENTITY_POOL_ID = '';
const IOT_CORE_ENDPOINT = '';
const MQTT_TOPIC = ''; 

// --- DOM Elements ---
const connectionStatusElement = document.getElementById('connection-status');
const iotDataElement = document.getElementById('iot-data');
const reconnectButton = document.getElementById('reconnect-button');

let connection; // Declare connection globally to manage its state

// --- Function to get AWS Credentials from Cognito ---
async function getAWSCredentials() {
    AWS.config.region = AWS_REGION;
    AWS.config.credentials = new AWS.CognitoIdentityCredentials({
        IdentityPoolId: COGNITO_IDENTITY_POOL_ID
    });

    try {
        await AWS.config.credentials.getPromise();
        console.log('Successfully got AWS credentials from Cognito.');
        return {
            accessKeyId: AWS.config.credentials.accessKeyId,
            secretAccessKey: AWS.config.credentials.secretAccessKey,
            sessionToken: AWS.config.credentials.sessionToken
        };
    } catch (error) {
        console.error('Error getting AWS credentials:', error);
        throw error; // Propagate the error
    }
}

// --- Function to Connect to AWS IoT Core and Subscribe ---
async function connectAndSubscribe() {
    connectionStatusElement.textContent = 'Connecting...';
    reconnectButton.style.display = 'none';

    try {
        const credentials = await getAWSCredentials();

        const clientID = `web_client_${Math.random().toString(16).substr(2, 8)}`; // Unique client ID

        // Initialize the AWS IoT MQTT Connection
        connection = new iot.AwsIotMqttConnection({
            endpoint: IOT_CORE_ENDPOINT,
            protocol: iot.AwsIotMqttConnectionConfig.ConnectThroughWebSocket,
            credentialsProvider: {
                get: {
                    credentials: () => ({
                        aws_access_key_id: credentials.accessKeyId,
                        aws_secret_access_key: credentials.secretAccessKey,
                        aws_session_token: credentials.sessionToken,
                    }),
                }
            },
            cleanSession: true,
            clientId: clientID,
            keepAlive: 30
        });

        // --- Event Listeners ---
        connection.on('connect', () => {
            console.log('Connected to AWS IoT Core!');
            connectionStatusElement.textContent = 'Connected';
            connectionStatusElement.style.color = 'green';

            // Subscribe to the topic
            connection.subscribe(MQTT_TOPIC, iot.QoS.AtLeastOnce)
                .then(() => {
                    console.log(`Subscribed to topic: ${MQTT_TOPIC}`);
                })
                .catch(error => {
                    console.error('Subscription error:', error);
                    connectionStatusElement.textContent = `Connected (Subscription Failed)`;
                    connectionStatusElement.style.color = 'orange';
                });
        });

        connection.on('message', (topic, payload) => {
            console.log(`Message received on topic ${topic}: ${payload.toString()}`);
            try {
                const data = JSON.parse(payload.toString());
                iotDataElement.textContent = JSON.stringify(data, null, 2);
            } catch (e) {
                iotDataElement.textContent = `Raw: ${payload.toString()}`;
                console.warn('Received non-JSON message:', payload.toString());
            }
        });

        connection.on('error', (error) => {
            console.error('MQTT Connection Error:', error);
            connectionStatusElement.textContent = `Error: ${error.message}`;
            connectionStatusElement.style.color = 'red';
            reconnectButton.style.display = 'block';
        });

        connection.on('close', () => {
            console.log('MQTT Connection Closed');
            connectionStatusElement.textContent = 'Disconnected';
            connectionStatusElement.style.color = 'gray';
            reconnectButton.style.display = 'block';
        });

        // --- Connect to IoT Core ---
        await connection.connect();

    } catch (error) {
        console.error('Failed to connect to AWS IoT Core:', error);
        connectionStatusElement.textContent = `Failed to Connect: ${error.message || error}`;
        connectionStatusElement.style.color = 'red';
        reconnectButton.style.display = 'block';
    }
}

// --- Reconnect Button Handler ---
reconnectButton.addEventListener('click', () => {
    if (connection && connection.isConnected) {
        console.log('Already connected, no need to reconnect.');
        return;
    }
    connectAndSubscribe();
});

// --- Initial Connection on Page Load ---
document.addEventListener('DOMContentLoaded', connectAndSubscribe);

Aligning reflected, rotated image to the bottom right (or top right, etc.) of a shape outline with transforms/dealing with rotated bounds

I take arbitary (any angle) lines and create shapes around them, some of which are reflected across those lines. The shapes can be triangular or quadrilateral, including non-parallelograms. My code to calculate the reflected points works, and I draw these points onto a canvas, clip, and stroke. Then I need to render the texture flipped and rotated to correspond to these points. I create a transform with DOMMatrix, using rotate and scale to create a reflection (flip) about the line and translating so the image aligns with the outline, which doesn’t work.

Because the drawing orientation of the canvas sometimes (but not always) switches, I tried translating to the maxX/Y, but this runs into problems with non-axis-aligned shapes. The maxX, maxY float outside the shape. Using minX/Y for the top left also fails, which you can see looking at the second of my test cases in the example. This could mean the original bounding box isn’t correct either.

I also tried using closest points on the new shape, with better results. But this still failed noticeably on shapes where the slope of the bottom edge was positive, since the bottom right point would have a smaller minY than the bottom left (so then the image wouldn’t be drawn low enough).

I don’t think I can just perform math on the height/width of the image, because the shapes are recursively folded, so they might only represent fractions of the canvas. I need the images to sit within the exact bounds dictated by calculating the reflected points (which are hardcoded in my example, sorry).

I made a more minimal version of my code to show here. It just has a few predefined test lines/shapes and it doesn’t cover all scenarios unfortunately. The original code is way too big to post. The part of the canvas that reads ‘1’ should draw from the origin.

<head>
<style>
canvas {
    border: 1px solid grey;
    margin: 2px;
}
</style>
</head>
<body>
<p><canvas id="image" width="680" height="50"></canvas></p>
<p id="canvases"></p>
<script>
"use strict";
const canvasWidth = 600;
const canvasHeight = 830;
const pieces = [
    [{points:[new DOMPoint(140, 50),new DOMPoint(140.00000000000003, -90),new DOMPoint(90.00000000000001, -90),new DOMPoint(90, 0),], line:{ start: new DOMPoint(283.6663192636163, 193.66631926361632), end: new DOMPoint(-52.666319263616316, -142.66631926361632) }, original:[new DOMPoint(140, 50),new DOMPoint(0, 50),new DOMPoint(0, 0),new DOMPoint(90, 0),], intersects:[new DOMPoint(90, 0),new DOMPoint(140, 50),], origTopLeft:new DOMPoint(0, 0),width:50.00000000000003, height:50.00000000000003}, {points:[new DOMPoint(158.36517719568567, 44.67326250912334),new DOMPoint(163.97896049896048, -53.783451143451146),new DOMPoint(213.82095634095634, -49.58802494802492),new DOMPoint(211.1386748844376, -2.5451301597599514),], line:{ start: new DOMPoint(252.24682141160773, -39.3261033682806), end: new DOMPoint(101.75317858839227, 95.3261033682806) }, original:[new DOMPoint(158.36517719568567, 44.67326250912335),new DOMPoint(256.8378378378378, 50),new DOMPoint(258.18918918918916, -1.6317320576126618e-15),new DOMPoint(211.1386748844376, -2.5451301597599563),], intersects:[new DOMPoint(211.1386748844376, -2.5451301597599514),new DOMPoint(158.36517719568567, 44.67326250912334),], origTopLeft:new DOMPoint(158.36517719568567, -2.5451301597599563),width:55.45577914527067, height:55.45577914527067},{points:[new DOMPoint(198.38255973344914, 8.868236027966603),new DOMPoint(-153.64897521683866, 5.578032470538176),new DOMPoint(-154.11627140114496, 55.57584876561373),new DOMPoint(143.07549812764987, 58.3535016752606),], line:{ start: new DOMPoint(436.3443301443184, -204.04492697123226), end: new DOMPoint(-82.3443301443184, 260.04492697123226) }, original:[new DOMPoint(198.3825597334491, 8.868236027966553),new DOMPoint(162.65825355141538, 359.09787638799855),new DOMPoint(112.9163540869709, 354.0240772523315),new DOMPoint(143.0754981276499, 58.353501675260645),], intersects:[new DOMPoint(143.07549812764987, 58.3535016752606),new DOMPoint(198.38255973344914, 8.868236027966603),], origTopLeft:new DOMPoint(112.9163540869709, 8.868236027966553),width:352.49883113459407, height:352.49883113459407}, ],
    [{points:[new DOMPoint(183, 0),new DOMPoint(-115.80000000000018, -398.4000000000001),new DOMPoint(-155.80000000000018, -368.4000000000001),new DOMPoint(158, 50),], line:{ start: new DOMPoint(466.81944546997806, -567.6388909399561), end: new DOMPoint(-126.81944546997806, 619.6388909399561) }, original:[new DOMPoint(183.00000000000003, 0),new DOMPoint(681, 0),new DOMPoint(681, 50),new DOMPoint(158, 50),], intersects:[new DOMPoint(158, 50),new DOMPoint(183, 0),], originalTopLeft:new DOMPoint(158, 0),width:338.8000000000002, height:338.8000000000002}, ],
    [{points:[new DOMPoint(157.50666666666666, 24.98461538461538),new DOMPoint(232.01174895512395, 458.84515237596656),new DOMPoint(182.7330781575854, 467.307575458501),new DOMPoint(121.1733333333333, 108.830769230769),], line:{ start: new DOMPoint(358.8607804360353, -439.6787240831585), end: new DOMPoint(-43.86078043603533, 489.6787240831585) }, original:[new DOMPoint(157.50666666666666, 24.9846153846154),new DOMPoint(-210.00917431192647, 267.30275229357795),new DOMPoint(-182.48623853211006, 309.045871559633),new DOMPoint(121.17333333333352, 108.83076923076914),], intersects:[new DOMPoint(121.1733333333333, 108.830769230769),new DOMPoint(157.50666666666666, 24.98461538461538),], originalTopLeft:new DOMPoint(-210.00917431192647, 24.9846153846154),width:110.83841562179065, height:110.83841562179065}, {points:[new DOMPoint(118.49999999999997, 49.99999999999999),new DOMPoint(207.78082191780817, 127.91780821917807),new DOMPoint(240.6575342465753, 90.24657534246575),new DOMPoint(137.25, -4.9897642155143516e-15),], line:{ start: new DOMPoint(199.2848941516392, -165.42638440437122), end: new DOMPoint(55.71510584836079, 217.42638440437122) }, original:[new DOMPoint(118.5, 50),new DOMPoint(0, 50),new DOMPoint(0, 0),new DOMPoint(137.25, 0),], intersects:[new DOMPoint(137.25, -4.9897642155143516e-15),new DOMPoint(118.49999999999997, 49.99999999999999),], originalTopLeft:new DOMPoint(0, 0),width:122.15753424657532, height:122.15753424657532}]
];

// reflect, rotate by angle of the longest edge of the pre-reflected shape so that the image renders at the right angle on the page

function getReflectionMatrix(piece, ctx) {
    const { line, original, points, intersects } = piece;
    const anchor = intersects[0]; // point where the line and the other edges meet, used as an origin for reflection

    const display = new DOMMatrix();
    reflectMatrix(display, line, anchor);
    rotateMatrix(display, original, anchor); // i do this so the image shows up at the right angle on the canvas
    translateMatrix(display, original, points, ctx);
    return display;
}

function reflectMatrix(matrix, line, anchor) {
    const radians = getAngleFromOrigin(line);
    const angle = getDegreesFromRadians(radians);

    matrix.translateSelf(anchor.x, anchor.y);
    matrix.rotateSelf(angle);
    matrix.scaleSelf(1, -1);
    matrix.rotateSelf(-angle);
}

function rotateMatrix(matrix, originalPoints, anchor) {
    const longestEdgeAngle = getLongestEdgeAngle(originalPoints);
    const degrees = getDegreesFromRadians(longestEdgeAngle);

    matrix.rotateSelf(degrees);
    matrix.translateSelf(-anchor.x, -anchor.y);
}

function translateMatrix(matrix, originalPoints, newPoints, ctx) {
    const { width, height } = getDimensions(newPoints);
    const { pointsUp, pointsLeft } = getMatrixDirection(matrix);

    let { x, y } = getTopLeft(newPoints);
    if (pointsUp) y += height;
    if (pointsLeft) x += width;
    //const target = findClosestPoint(newPoints, x, y); // if you look at the top left test, the bottom of the image is too high on the yellow shape
    const target = new DOMPoint(x, y); // make a new dompoint for it just for ease of switching between variables in testing

    const pt0T = new DOMPoint(0, 0).matrixTransform(matrix);
    const dx = target.x - pt0T.x;
    const dy = target.y - pt0T.y;
    const translated = new DOMMatrix().translateSelf(dx, dy);
    matrix.preMultiplySelf(translated);

    drawDebugMarker(target.x, target.y, "blue", ctx);
}

// helpers for getting shape dimensions etc.

function getAngleFromOrigin(line) {
    const { start, end } = line;
    const dx = end.x - start.x;
    const dy = end.y - start.y;
    return Math.atan2(dy, dx);
}

function getLongestEdgeAngle(points) {
    let maxLength = 0;
    let bestAngle = 0;
    for (let i = 0; i < points.length; i++) {
        const a = points[i];
        const b = points[(i + 1) % points.length];
        const dx = b.x - a.x;
        const dy = b.y - a.y;
        const length = Math.hypot(dx, dy);
        if (length > maxLength) {
            maxLength = length;
            bestAngle = Math.atan2(dy, dx);
        }
    }
    return bestAngle;
}

function getDegreesFromRadians(angle) {
    const degrees = angle * 180 / Math.PI;
    return ((degrees % 360) + 360) % 360;
}

function getTopLeft(points) {
    const { minX, maxX, minY, maxY } = getBoundingBox(points);
    return new DOMPoint(minX, minY);
}

function getBoundingBox(points) {
    const coordsX = points.map(point => point.x);
    const minX = Math.min(...coordsX);
    const maxX = Math.max(...coordsX);
    const coordsY = points.map(point => point.y);
    const minY = Math.min(...coordsY);
    const maxY = Math.max(...coordsY);
    return { minX, maxX, minY, maxY };
}

function getDimensions(points) {
    const { minX, maxX, minY, maxY } = getBoundingBox(points);
    const width = maxX - minX;
    const height = maxY - minY;
    return { width, height };
}

function getMatrixDirection(matrix) {
    const rightX = matrix.a;
    const rightY = matrix.b;
    const downX = matrix.c;
    const downY = matrix.d;

    const pointsLeft = Math.abs(rightX) >= Math.abs(rightY) ? rightX < 0 : rightY < 0;
    const pointsUp = Math.abs(downY) >= Math.abs(downX) ? downY < 0 : downX < 0;
    return { pointsLeft, pointsUp };
}

function findClosestPoint(points, x, y) {
    let minDist = Infinity;
    let closest = points[0];
    for (const point of points) {
        const dist = Math.hypot(point.x - x, point.y - y);
        if (dist < minDist) {
            minDist = dist;
            closest = point;
        }
    }
    return closest;
}

// drawing

function loopThroughPieces(test, ctx) {
    for (let i = 0; i < test.length; i++) {
        ctx.setTransform(canvasTransform);
        const piece = test[i];
        const colour = getColour(i);
        const display = getReflectionMatrix(piece, ctx);
        drawPiece(piece, colour, display, ctx);
    }
}

function getColour(i) {
    // red comes first
    const hue = (i * 45) % 360;
    const lightness = 100 - (40 + 10);
    const alpha = 0.5;
    return `hsla(${hue}, 90%, ${lightness}%, ${alpha})`;
}

function drawPiece(piece, colour, display, ctx) {
    ctx.save();
    tracePiecePath(piece.points, ctx);
    ctx.globalAlpha = 0.65;
    //ctx.clip(); // it's supposed to be clipped, but i unclipped for visualisation, since sometimes the image floats outside of the outline

    ctx.setTransform(canvasTransform.multiply(display));
    ctx.drawImage(image, 0, 0, image.width, image.height);

    ctx.strokeStyle = colour;
    ctx.lineWidth = 3;
    ctx.globalAlpha = 1;
    ctx.stroke();
    
    ctx.restore();
    ctx.save();
}

function tracePiecePath(points, ctx) {
    ctx.beginPath();
    const firstPoint = points[0];
    ctx.moveTo(firstPoint.x, firstPoint.y);
    points.slice(1).forEach(point => {
        ctx.lineTo(point.x, point.y);
    });
    ctx.closePath();
}

function drawDebugMarker(x, y, colour, ctx) {
    ctx.beginPath();
    ctx.arc(x, y, 5, 0, 2 * Math.PI);
    ctx.fillStyle = colour;
    ctx.fill();
}

// everything below is just assembling test cases etc. and rendering them

function makeCanvasTransform() {
    canvasTransform.scaleSelf(0.6, 0.6);
    canvasTransform.translateSelf(canvasWidth/2, canvasHeight/2);
}

function drawDebugImage() {
    const imgCtx = image.getContext("2d");
    imgCtx.fillStyle = "white";
    imgCtx.fillRect(0, 0, image.width, image.height);
    imgCtx.font = "20px arial";
    imgCtx.textAlign = "center";
    imgCtx.fillStyle = "black";
    const segmentWidth = image.width/12;
    let offsetX = 0;
    for (let i = 0; i < Math.ceil(image.width/segmentWidth); i++) {
        imgCtx.strokeRect(offsetX, 0, segmentWidth, image.height);
        imgCtx.fillText(i + 1, offsetX + segmentWidth/2, image.height/2);
        offsetX += segmentWidth;
    }
}

function gatherCtxs() {
    const ctxs = [];
    for (let i = 0; i < pieces.length; i++) {
        const canvas = document.createElement("canvas");
        canvas.width = canvasWidth;
        canvas.height = canvasHeight;
        canvases.appendChild(canvas);
        if (i % 2 == 1) {
            const br = document.createElement("br");
            canvases.appendChild(br);
        }
        ctxs.push(canvas.getContext("2d"));
    }
    return ctxs;
}

const image = document.getElementById("image");
const canvases = document.getElementById("canvases");
const canvasTransform = new DOMMatrix();

drawDebugImage();
makeCanvasTransform();
const ctxs = gatherCtxs();
for (let i = 0; i < pieces.length; i++) {
    loopThroughPieces(pieces[i], ctxs[i]);
}
</script>
</body>

Thank you for reading! 🙂

How to detect the date format (DD/MM/YYYY or MM/DD/YYYY) in JavaScript? [closed]

In my application, I’m currently using:
var dt = (new Date()).toLocaleString();

This formats the date based on the user’s locale. However, some users have requested a more standardized and explicit format like DD-MM-YYYY for better clarity.

I understand that toLocaleDateString() produces different outputs based on the locale. For example:

(new Date()).toLocaleDateString('en-IN'); // "11/6/2025" (DD/MM/YYYY)
(new Date()).toLocaleDateString('en-US'); // "6/11/2025" (MM/DD/YYYY)

Given that JavaScript runs on the client side and has access to the user’s locale and timezone settings, is there a way to detect or infer the actual date format (i.e., the order of day, month, year) being used on the browser?

My goal is to display the format itself (not just the formatted date), so that I can inform users or standardize input fields accordingly.

learning api rate limiting using token bucket

I was using token bucket algorithm to implement api rate limiting. it does seem to work, but can you help me improve it ? i do plan on using redis later on instead of in memory data storing.

Thank you.

import { Request, Response } from "express";

interface Iuser {
  userName: string;
  expireDate: number;
  count: number;
}

type Iusers = Record<string, Iuser>;

const users: Iusers = {};

export class TokenBucket {
  count = 0;
  time = Date.now();
  maxLimit: number = 3;
  constructor() {
    setInterval(() => {
      this.expireRequest(users);
    }, 5000);
  }

  addrequest(req: Request, res: Response, successFn: Function) {
    let user = req.headers.authorization as string;

    if (!users[user]) {
      users[user] = {
        count: 1,
        expireDate: Date.now() + 5000,
        userName: user,
      };
      this.count = users[user].count;
    } else {
      this.count = ++users[user].count;
    }

    if (this.count > this.maxLimit) {
      console.log("rate limit excetion for ", users[user].userName);
      return res.status(429).json({
        message: "rate limit exceeded. please try again",
      });
    }
    return successFn();
  }

  expireRequest(users: Iusers) {
    for (let key in users) {
      console.log("inside loop");
      const user = users[key];
      if (Date.now() > user.expireDate && user.count !== 0) {
        console.log("inisdide reset for ", user.userName);
        user.expireDate = Date.now() + 5000;
        user.count = 0;
      }
    }
  }
}


explanation:
whenever a request comes in , if its exists in the users obj. it increments a its number by 1 and if doesnt exist, it adds the userName as a property and initializes with 1 as value .
there is also a setInterval that runs a function expireRequest, that resets the counter for user if the current time is greater than expireDate of that user.
if the user hit their max limit before their request expires , theyll be locked out for making the request untill thier expiryDate is lesser than current Date .

Error in my website coding won’t open links in the calendar section

I cannot figure out what is wrong with my calendar section of the site. I’ve been able to fix most bugs and issues independently. When you got to the calendar on the site it opens fine but you you try to click and event you get the following error message:

An error occurred on the server when processing the URL. Please contact the system administrator.

The link is below

http://www.flamaranth.org/Calendar/Home.asp

The code for Home.asp is below

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<%
    DIM IP_Address, Server_Name, WebUserPW, AdminPW

    IP_Address = "47.206.174.213"
    Server_Name = "WIN-0EGS42TD4A3"
    WebUserPW = "WeBu$3rpW0rd"
    AdminPW = "^DMinl$tr4t0rpW*rd"
%>
<%
    Business_Name = "Grand Court of Florida Order of the Amaranth"
    Bus_Nm = "Amaranth"
    Database_Name = "Amaranth"
    Site_Name = "Amaranth"
    Page_Title = Business_Name
    Web_Address = "http://www.flamaranth.org/"
    App_Location = Web_Address & "Application/"
    Img_Location = Web_Address & "Images/"
    Icon_Location = Web_Address & "Icons/"
    FontColor = "#000000"
    LineColor = "#FFFFFF"
    AltLineColor = "#EFF3FE"
    BackColor = "#FFFFFF"
    Dtl_Background = "#C8DEFE"
    Dtl_Background = "#FFFFFF"
    Dtl_Background = "#CCCCCC"
    eMail_CC = "[email protected]"
    Frame_Page = "Yes"
    IF Logged_In_Text <> "logout" THEN Logged_In_Text = "login" END IF
%>
<%
    Folder_Name = ""
    Page_Title = "Calendar - Planning"
    ID_Field_Name = "Primary_ID"
    Page_Security = "NotSecured"
    Window_Page = "No"
    Frame_Page = "No"

    DIM Login_ID, Login_Name, Login_First_Name, Login_Last_Name, Login_Type
    Login_ID = Session("Login_ID")
    Login_Name = Session("Login_Name")
    Login_First_Name = Session("Login_First_Name")
    Login_Last_Name = Session("Login_Last_Name")
    ''Login_Type = Session("Login_Type")

    DIM PopWinWidth, PopWinHeight, PopFrameHeight
    PopWinWidth = "460"
    PopWinHeight = "320"
    PopFrameHeight = PopWinHeight - 23

    DIM Activity_Date, MyOrder, VerifyPrefix, VerifyNumber
    Activity_Date = Request.item("Activity_Date")
    IF Activity_Date = "" OR IsNull(Activity_Date) THEN Activity_Date = Date() END IF
    Activity_Date = CDate(Activity_Date)
    MyOrder = Request.item("MyOrder")
    VerifyPrefix = "WMP"
    VerifyNumber = DateDiff("d",CDate("11/11/2011"),Now())

    DIM i, BodyScroll, BodyOnLoad, BodyOnUnload, Body_Style, Body_Class, Previous_Page, Page_Security, Window_Page, Data_Page_Type
    DIM Data_Mode, Toggle_Mode, Primary_ID, Verify
    Verify = Session("Verify")
%>
<%
    Page_Name = "Home"
    IF Verify = VerifyPrefix & VerifyNumber THEN
        Login_Type = "Admin"
    ELSE
        Login_Type = "User"
    END IF
%>
<!--#include file="Header.inc"-->
<script type="text/javascript" src="<%=Web_Address%>Movable_Div.js"></script>
<link rel="Stylesheet" href="Calendar.css">
<!--#include file="Data.inc"-->
<!--#include file="Connection.inc"-->
<!--#include file="Connection2.inc"-->
<!--#include file="Body.inc"-->
<%
    MinDate_Query="SELECT DatePart(dw,Min(Activity_Date)) MinDate FROM Dates WHERE Month_Start = '" &Date_Db(MonthDate(Activity_Date))& "'"
    rs.Open MinDate_Query,objconn,0,1
    IF rs.EOF <> true THEN MinDate = rs("MinDate") ELSE MinDate = 1 END IF  
    rs.close
%>
<script type="text/javascript">
    function FilterMyOrder(ThisValue)
        {
        document.location.href='<%=Page_Name%>.asp?Activity_Date=<%=Date_db(Activity_Date)%>&MyOrder='+ThisValue;
        }
    function NewActivity(ThisDate)
        {
        document.getElementById('PopWin01').style.display = '';
        parent.frames['PopFrame01'].location.href = 'Data.asp?Data_Page_Type=INSERT&Activity_Date=' + ThisDate;
        document.getElementById('PopTitle').value = 'New Scheduling';
        }
    function DtlActivity(PastDate,ThisID,Activity)
        {
        if ('<%=Login_Type%>' == 'Admin' && PastDate == '1')
            {
            parent.frames['PopFrame01'].location.href = 'Data.asp?Data_Page_Type=UPDATE&Primary_ID=' + ThisID;
            document.getElementById('PopHeaderImg').src = 'TB_Secure.gif';
            }
        else
            {
            parent.frames['PopFrame01'].location.href = 'View.asp?Data_Page_Type=SELECT&Primary_ID=' + ThisID;
            document.getElementById('PopHeaderImg').src = 'TB_App.png';
            }
        document.getElementById('PopTitle').value = Activity;
        document.getElementById('PopWin01').style.display = '';
        }
    function ClosePop()
        {
        parent.frames['PopFrame01'].location.href = 'Nada.asp';
        document.getElementById('PopWin01').style.display='none';
        document.getElementById('PopWin01').style.width = '<%=PopWinWidth%>px';
        document.getElementById('PopWin01').style.height = '<%=PopWinHeight%>px';
        document.getElementById('PopFrame01').style.width = '<%=PopWinWidth%>px';
        document.getElementById('PopFrame01').style.height = '<%=PopFrameHeight%>px';
        }
    function PreviousMonth()
        {
        document.location.href='<%=Page_Name%>.asp?MyOrder=<%=MyOrder%>&Activity_Date=<%=Date_db(DateAdd("m",-1,Activity_Date))%>';
        }
    function NextMonth()
        {
        document.location.href='<%=Page_Name%>.asp?MyOrder=<%=MyOrder%>&Activity_Date=<%=Date_db(DateAdd("m",1,Activity_Date))%>';
        }
    function AdminLogin()
        {
        var ThisWidth = '260px';
        var ThisHeight = '200';
        var FrameHeight = ((ThisHeight*1)-22) + 'px';
        ThisHeight = ThisHeight + 'px';
        document.getElementById('PopWin01').style.width = ThisWidth;
        document.getElementById('PopWin01').style.height = ThisHeight;
        document.getElementById('PopFrame01').style.width = ThisWidth;
        document.getElementById('PopFrame01').style.height = FrameHeight;
        document.getElementById('PopWin01').style.top = '20px';
        document.getElementById('PopWin01').style.left = '5px';
        document.getElementById('PopWin01').style.display = '';
        parent.frames['PopFrame01'].location.href = 'Login.asp';
        }
    function PrintThis()
        {
        alert('Print in [Landscape] mode');
        NewWin('Calendar/Print.asp?Activity_Date=<%=Activity_Date%>&MyOrder=<%=MyOrder%>','PrintWin',500,600,'');
        }
</script>
<div style="position:absolute; top:0px; left:0px; width:100%"><center>
    <table width=840 border=0 cellpadding=0 cellspacing=0><tr>
        <td style="text-align:left"><%
    IF Verify = VerifyPrefix & VerifyNumber THEN
        %><a href="JavaScript:document.location.href='Log_Out.asp'">Log Out</a><%
    ELSE
        %><a href="JavaScript:AdminLogin()">Admin Login</a><%
    END IF
    %></td>
        <td style="text-align:right">
            <a href="JavaScript:PrintThis()">Print</a>
        </td>
    </tr></table>
</center></div>
<br>
<br>
<br>

<center>
    <span class=buttons onClick="PreviousMonth()">&lt;&lt;&nbsp;Prev</span>
    <span class=buttons onClick="NextMonth()">Next&nbsp;&gt;&gt;</span>
    <br /><br />
    <table border=0 cellspacing=0 cellpadding=0 class=Calendar_Schedule width=840>
        <tr><td style="border:0px" colspan=7 class=Header1><center>
            <b><%=Months(DatePart("m",Activity_Date))%>,&nbsp;<%=Year(Activity_Date)%></b>
        </center></td></tr>
        <tr style="background:#DDDDDD; text-align:center">
            <td><b>Sunday</b></td>
            <td><b>Monday</b></td>
            <td><b>Tuesday</b></td>
            <td><b>Wednesday</b></td>
            <td><b>Thursday</b></td>
            <td><b>Friday</b></td>
            <td><b>Saturday</b></td>
        </tr><tr><%
    IF MinDate <> 1 THEN
        %><td style="border:0px" colspan="<%=MinDate-1%>">&nbsp;</td><%
    END IF

    sql_Query = "SELECT Activity_Date FROM Dates WHERE Month_Start = '" &Date_Db(MonthDate(Activity_Date))& "'"
    i = MinDate-1
    DIM Past_Date
    Past_Date = "0"
    rs.Open sql_Query,objconn,0,1
    while(not rs.EOF)
    i = i + 1
    IF i = 8 THEN
        %></tr><tr><%
        i = 1
    END IF
    IF rs("Activity_Date") >= Date() AND Login_Type = "Admin" THEN
        Past_Date = "1"
        Calendar_Day = "<a href=" &Quote& "JavaScript:NewActivity('" &Date_db(rs("Activity_Date"))& "')" & Quote & ">" & Day(rs("Activity_Date")) & "</a>"
    ELSE
        Past_Date = "0"
        Calendar_Day = "<b>" & Day(rs("Activity_Date")) & "</b>"
    END IF
    IF Date_db(rs("Activity_Date")) = Date_db(Date()) THEN bgColor = ";background:#FFFFBB" ELSE bgColor = "" END IF
    %><td VAlign=Top style="height:70px<%=bgColor%>" class=Calender_Box><%=Calendar_Day%><%
        Calender_Events = ""
        sql_Query = "Activities_Calendar '" & Date_Db(rs("Activity_Date")) & "','" & MyOrder & "'"
        rs2.Open sql_Query,objconn2,0,1
        while(not rs2.EOF)
        Calender_Events2 = "<span class=Cal_Info onClick=" &Quote& "DtlActivity('" &Past_Date& "','" &rs2("ID")& "','" & rs2("Activity") & "')" &Quote& ">"
        Calender_Events2 = Calender_Events2 & Time_Only(rs2("Start_DateTime")) & " [" & rs2("Chapter_ID") & "] " & rs2("Activity")
        Calender_Events2 = Calender_Events2 &  "</span>"
        IF rs2("ID") <> 0 THEN
        Calender_Events = Calender_Events & "<br />" & Calender_Events2
        END IF
        rs2.MoveNext
        wend
        rs2.Close
    %><%=Calender_Events%></span><br /></td><%
    rs.MoveNext
    wend
    rs.Close
    IF i < 7 THEN ClosingTD = "<td style='border:0px' colspan=" & 7 - i & ">&nbsp;</td>" ELSE ClosingColSpan = "" END IF
    %><%=ClosingTD%></tr>
    <tr><td style="border:0px" colspan=7><center>
        <br />
        <b>Filter to your Court</b>
        <br />
        <select id="New_Chapter_ID" name="New_Chapter_ID" style="width:150px" onChange="FilterMyOrder(this.value)">
            <option Value="">All</option><%
            rs.Open "SELECT ID,Name FROM Chapters WHERE Active = 1 ORDER BY Order_by",objConn,0,1
            while(not rs.EOF)
            IF rs("ID") = MyOrder THEN SELECTED = "SELECTED" ELSE SELECTED = "" END IF
            %><option <%=SELECTED%> Value="<%=rs("ID")%>"><%=rs("Name")%>&nbsp; [<%=rs("ID")%>]</option><%
            rs.MoveNext
            wend
            rs.Close
        %></select>
    </center></td></tr>
</table>
</center>
<div id="PopWin01" class=PopWin style="width:<%=PopWinWidth%>px; height:<%=PopWinHeight%>px; display:none; position:absolute; top:60px; left:60px; z-index:1002;" onMouseDown="dragStart(event,'PopWin01');this.style.cursor='move'">
    <table border=0 cellpadding=0 cellspacing=0 width="100%" class=PopWinHeader><tr>
        <td><img id="PopHeaderImg" src="TB_Secure.gif" height=20 width=20 /></td>
        <td><input id="PopTitle" id="PopTitle" class=Nada style="width:100%; color:#FFFFFF; padding-top:2px; font-weight:bold" READONLY value="Admin Login" /></td>
        <td width=80 style="text-align:right; padding-right:4px"><button onClick="ClosePop()">X</button></td>
    </table>
    <iframe id="PopFrame01" name="PopFrame01" src="Nada.asp" width="<%=PopWinWidth%>" height="<%=PopFrameHeight%>" style="border:0px;">&nbsp;</iframe>
</div>
</body>
</html>
</body></html>

Array of images each with an onload event listener

I have an array of image objects that I set an event listener for. Inside the event listener, I just increment the value of a progress bar (the full bar when all images finish loading.

    let images = new Array(pageList.length);
    pageList.forEach((e, idx, arr) => {
        let i = new Image;
        i.crossOrigin = "";
        i.onload = () => { progs[progs.length-1].value += 1; }
        i.src = e.url + '&w=1280';
        images[idx] = i;
    });

I also need to perform several actions only after all the images have finished loading. I use Promise.all() for that…

    Promise.all(images.filter(img => !img.complete).map(img => new Promise(resolve => { img.onload = img.onerror = resolve; }))).then(() => {
        images.forEach((i) => {
            let dpi = i.height/dimensions[1];
            pdf.addPage([Math.round(i.width/dpi * 100) / 100, dimensions[1]], 'p');
            pdf.addImage(i, 'JPEG', 0, 0, Math.round(i.width/dpi * 100) / 100, dimensions[1]);
        });
    })
    .then();

The top snippet works correctly if and only if I do not do Promise.all() (such as commenting it out). This is because of the resolve => { img.onload = img.onerror = resolve; } which is overriding the img.onload. The promise.all works as intended/expected. I’ve never been strong on the Promise/aysnc stuff, and I’m having difficulty finding the correct pattern to make this work.

The full function (if needed).

CameraType is Declared but its value is never read

Edited from old post: I’m having an issue where I use the exact code from Expo Camera Usage, but CameraType is identified as “declared but never read.” I previously ran npx expo install and npx expo install expo-camera but the import for some reason just isnt working and Quick Fixes suggest deleting it. I’ve also tried -rf node_modules and my package-lock.json to clean up everything, but keep running into this issue.

import { CameraView, CameraType, useCameraPermissions } from 'expo-camera';
import { useState } from 'react';
import { Button, StyleSheet, Text, TouchableOpacity, View } from 'react-native';

export default function App() {
  const [facing, setFacing] = useState<CameraType>('back');
  const [permission, requestPermission] = useCameraPermissions();

  if (!permission) {
    // Camera permissions are still loading.
    return <View />;
  }

  if (!permission.granted) {
    // Camera permissions are not granted yet.
    return (
      <View style={styles.container}>
        <Text style={styles.message}>We need your permission to show the camera</Text>
        <Button onPress={requestPermission} title="grant permission" />
      </View>
    );
  }

  function toggleCameraFacing() {
    setFacing(current => (current === 'back' ? 'front' : 'back'));
  }

  return (
    <View style={styles.container}>
      <CameraView style={styles.camera} facing={facing}>
        <View style={styles.buttonContainer}>
          <TouchableOpacity style={styles.button} onPress={toggleCameraFacing}>
            <Text style={styles.text}>Flip Camera</Text>
          </TouchableOpacity>
        </View>
      </CameraView>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
  },
  message: {
    textAlign: 'center',
    paddingBottom: 10,
  },
  camera: {
    flex: 1,
  },
  buttonContainer: {
    flex: 1,
    flexDirection: 'row',
    backgroundColor: 'transparent',
    margin: 64,
  },
  button: {
    flex: 1,
    alignSelf: 'flex-end',
    alignItems: 'center',
  },
  text: {
    fontSize: 24,
    fontWeight: 'bold',
    color: 'white',
  },
});

ElectronJS will not execute. No Error Messages

I am having some issues with executing an Electron application.

I had a working version last night that started without issue but this morning the Electron application that was previously working failed to execute. Upon failure I also received no error messages in the console.

To see if there was something messed up with that specific project I decided to follow the tutorial for Electron quickstart at the following link : https://www.electronjs.org/docs/latest/tutorial/tutorial-first-app

Following this tutorial through where we are asked to put a console.log(‘Hello from Electron’) into the main.js file and performing npm run start the newly created project also fails. I receive the following output in the VS Code terminal. It should also be noted that upon running the npm run electron command ( I have mapped this script to ‘electron .’ ), VSCode decides to open main.js and place the cursor at the end of the file regardless of the file contents.

I have tried reinstalling Node.js, reinstalling NPM, deleting the Electron folder in %appdata%, deleting node_modules folder. Not sure what to do or even how to approach this problem.

I have the following environment : Windows 11 | [email protected] | [email protected]

enter image description here

Why does Promise.all wait for slow microtasks even if all Promises resolve immediately? [duplicate]

Note: This is not a duplicate of questions about blocking or long-running loops. There is no CPU-intensive or infinite loop here — the issue is that Promise.all is unexpectedly delayed due to unrelated queueMicrotask() calls. It’s a subtle event loop/microtask interaction, not a case of blocking code.

I’m working with some async code where all Promises are already resolved, but there’s also a queue of microtasks triggered before Promise.all runs. Surprisingly, Promise.all still seems to wait for all of them to finish before resolving, even though the Promises themselves are resolved instantly.

Here’s a minimal repro:

 // This is a synchronous busy loop that blocks the event loop
function busyLoop(iterations) {
  const start = Date.now();
  while (Date.now() - start < iterations) {
    // intentionally blocking
  }
}

function microtaskFlood() {
  for (let i = 0; i < 1000; i++) {
    queueMicrotask(() => {
      // Just a microtask that does nothing
    });
  }
}

async function test() {
  console.log('Start');

  busyLoop(100); // Blocks event loop synchronously for ~100 ms

  // Schedule many microtasks after blocking
  microtaskFlood();

  // Promise.all waits for these microtasks to finish
  await Promise.all([
    Promise.resolve('done1'),
    Promise.resolve('done2')
  ]);

  console.log('End');
}

test();

Expected:
Since both a and b are resolved, I expected Promise.all to resolve immediately.

Actual:
The Promise.all .then() only fires after the microtask finishes. This seems unintuitive because the microtask has no relation to a or b.

Questions:

  1. Is this behavior according to the ECMAScript spec?
  2. Why doesn’t Promise.all resolve in the same tick when all Promises are already resolved?
  3. Is there a way to make it resolve without waiting on unrelated microtasks?

Any explanation about how JavaScript’s microtask queue affects Promise.all scheduling would help.

Thanks!