node:test flush timers when using t.mock.timers.tick?

I have the following simple function:

export async function useTimeout() {
    const sleep = () => new Promise((resolve) => setTimeout(resolve, 1000));
    let c = 1;
    while (true) {
        c += 1;
        if (c > 5) {
            break;
        }
        // THIS LINE BREAKS THE TEST
        // await new Promise((resolve) => {resolve()});
        await sleep();
        console.log('sleep done!')
    }
    return c
}

I am testing the function using node:test on node v22 (same with node v24)


import { test } from 'node:test';
import assert from 'node:assert/strict';
import { useTimeout } from './useTimeout.js'; // Adjust the import path as necessary

test('useTimeout waits for 5 seconds and logs message', async (t) => {
  t.mock.timers.enable(['setTimeout']);
  const timeoutFunction = useTimeout();
  // Manually advance timers and yield to microtasks for each second
  for (let i = 0; i < 5; i++) {
    t.mock.timers.tick(1000);
    console.log(`Tick ${i + 1}: 1 second passed`);
    await Promise.resolve();
  }
  // Await the result
  const result = await timeoutFunction;
  assert.strictEqual(result, 6, 'useTimeout should return 6 after 5 iterations');
 
});

If I uncomment the line before calling the sleep function and thereby introducing a second promise in the loop the test fails.

Why is that?

Is there a way to store Trie in chrome extension with a deeply nested root?

I’m trying to create a chrome extension where the user adds text snippets to the extension, then when they type in textarea/input/contenteditable/rich-text editors a selection dropdown appears with autocomplete suggestions.

I’m utilizing a Trie for the autocomplete suggestions part, but my issue is that, if the root depth becomes too deep chrome.storage fails to serialize it, same thing with if I use JSON.stringify.

// In content.js

class TrieNode {
    constructor() {
        this.children = {};
        this.wordEnd = false;
    }
}

class Trie {
    constructor(tree) {
        this.root = tree || new TrieNode();
    };
    // Trie methods here

}
    trieInsert(key) {
        this.trie.insert(key);
        chrome.runtime.sendMessage({
            action: "saveTrie",
            data: this.trie.root
        });
    }

    async _loadTrieFromStorage() {
        return new Promise((resolve) => {
            chrome.runtime.sendMessage({ action: "getTrie" }, (response) => {
                if (response && response.data) {
                    this.trie = new Trie(response.data);
                } else {
                    this.trie = new Trie();
                }
                resolve();
            });
        });
    }

// In background.js
  if (request.action === "getTrie") {
    chrome.storage.local.get("trie", (data) => {
      sendResponse({data: data.trie});
    });
    return true; // Keep message channel open for async response
  }
  
  if (request.action === "saveTrie") {
    chrome.storage.local.set({"trie": request.data});
    sendResponse({success: true});
    return true;
  }

My question is, is it possible to store a deeply nested trie in storage in chrome extensions? or should I re-insert each string everytime the content.js is loaded in pages and iframes, or should I be using Trie at all in this case?

React header element not rendering in root div when using vanilla HTML setup

I’m trying to create a simple React application using vanilla HTML and CDN links for React 18. I have a basic setup where I want to render a header element inside a root div. I’m using React 18 with the UMD development builds from unpkg.

I created an HTML file with the React CDN scripts and wrote a simple App component that returns a header element using React.createElement.

I expected the header element to be rendered inside the div with id=”root”, but when I inspect the browser, the header element is not appearing in the DOM. The root div remains empty, and there are no visible errors in the console.

Here’s my complete code:
html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Hello React!</title>
  </head>
  <body>
    <div id="root"></div>
    
    <script
      src="https://unpkg.com/react@18/umd/react.development.js"
      crossorigin
    ></script>
    <script
      src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"
      crossorigin
    ></script>
    
    <script>
      function App() {
        return React.createElement("header");
      }
      
      const root = REACTDOM.createRoot(document.getElementById("root"));
      root.render(React.createElement(App));
    </script>
  </body>
</html>

Expected result: A header element should appear in the root div when I open the page in the browser.

Actual result: The root div remains empty, and no header element is rendered. When I inspect the element, I see with no content inside.

How do I get turn a permutation into an index (and back) in a context where there is a fixed amount of each permutable elements? [closed]

The problem

Let’s say you have 4 red balls, 2 blue balls and 1 green ball. That is 7 balls, and considering a ball can’t be distinguished from another if it has the exact same color, this makes for a total of (7!)/(4!2!1!) = 105 possible permutations (Source).

Meaning, say we associate red with 0, blue with 1 and green with 2, there are 105 ways to arrange the [0, 0, 0, 0, 1, 1, 2] array.

More generally, this can be seen as n balls, m ball types, and nₖ balls of type k with 1 <= k <= m and (n₁+n₂+...+nₖ) = n, having (n!)/(n₁!*n₂!*...*nₖ!) possible permutations.

I need an algorithm that can get a unique number from a given permutated array, and get this permutated array back from that exact, same, unique number (also refered to as index).

Constraints

  • The number, in the case of the given example, must be a value between 0 and (n!)/(n₁!*n₂!*...*nₖ!) - 1.

    With the example I’ve given, this would be between 0 and 104.

  • The algorithm must not require calculating all possible permutations.

    While I’m taking an easy example with 105 permutations here, I’d like this to be usable for something that could have 30 trillions of them, which we obviously can’t possibly all calculate, so your algorithm’s complexity very much matters here.

  • Please, do not solely rely on libraries. I need the algorithm, not magic.

    Using libraries for basic structures like lists is fine, but a magic function from an existing library that’s a bajillion lines long and lost in some gigantic codebase that does all the job is not fine.

    Since I’m looking for the algorithm here, it needs to be understandable and theoratically rewritable in any language, hence this constraint.

Allowed

I’ve tagged this question and , but really, I’m fine with any type-C language, including but not limited to TypeScript, C++, Java, C#, PHP. Even pseudocode is fine.

I don’t care about the order of the permutations, the only thing that matters is that you can get a unique index from each one, and get the permutation back from its index.

This isn’t a duplicate of:

Considering all of these questions are on SO, and that I’m asking for a software algorithm, I’m assuming this is on-topic. Please don’t redirect me to Math.SE, I need code, not lone formulas. If think this is still off-topic, please explain how so and I’ll edit the question accordingly.

Footnotes

Bonus points if you can explain the algorithm, provide your reasoning and/or sources for formulas, and give the complexity of the algorithm. Just working code is also fine, though.

Sending back index.html to frontend in Node.js/Express with res.sendFile() sets all my fetched data to undefined?

I have a frontend in React and a backend in Node.js, and an Express webserver to communicate between them. I have a lot of useStates() in React with the proper starting values set for my variables waiting to get fetched from the backend, mostly empty arrays. Since I’m using React Router to navigate through my website, I have ran into the problem of Cannot GET /pageName when refreshing a page other than the homepage. I looked for a solution to this, and they said to write this Express endpoint into my backend:

app.get('/*', function(req, res) {

  res.sendFile(

    path.join(__dirname, '../frontend/build/index.html'),

    function(err) {

      if (err) {

        res.status(500).send(err);
      }
  });
})

However, now I cannot get the webpages to load even the first time, as there is always an error. After a short debugging I found that after initially loading in my useStates with their starting values they are all quickly set to undefined. All the pages are constructed with starting values in mind, so I would rather not go around and write a check for every variable in case they become undefined for no reason, especially since I still don’t know if the original problem have been solved.

What can I do to stop having my states set automatically to undefined in this situation?

How to Allow Admin Users to Edit Formulas for Pricing Computation in Laravel/JS?

Please guide me to execute the following, I’m using JavaScript with Laravel:

  1. An admin role can CRUD a formula list that would appear in a dropdown option, for instance:

    • They can select from a list of products and its price would be retrieved.

    • The user can edit the formula by specifying whether
      (Item Price) - (input) + (input) % (input)
      etc.

  2. The formulas will be stored in dropdown that would affect the calculation of another form for final computation.

For instance in a sales form:

<h1>Sales Pricing Form</h1>

<form id="pricingForm">
    <!-- Dropdown for Formula Selection -->

    <label for="formulaDropdown">Select Formula</label>
    <select id="formulaDropdown" name="formula">
        <option value="avgFormula">Average Formula</option>
        <option value="saleFormula">Sale Formula</option>
    </select>
    <br><br>

    <!-- Input Fields -->
    <label for="quantity">Quantity</label>
    <input type="number" id="quantity" name="quantity" required>
    <br><br>

    <label for="totalAmount">Total Amount</label>
    <input type="number" id="totalAmount" name="totalAmount" required readonly>
    <br><br>

    <button type="submit">Submit</button>
</form>

The overall goal is when user clicks on a specific formula, it would affect the computation of the total amount.

I’m just currently brainstorming on how to best solve this problem. Thanks a lot!

When I attempt to generate HTML reports in Cypress, the authentication URL displays an error. What’s the solution?

// Cypress login session setup for a2i backoffice
const login = () => {
    cy.session('a2i-login', () => {
        cy.visit('https://backoffice.a2i.gov.bd');
        cy.url().should('include', 'https://login-npf-v2.softbd.xyz/realms/npf-global/protocol/openid-connect/auth');

        // Login credentials
        cy.get('input[name="username"]').type('[email protected]');
        cy.get('input[name="password"]').type('Npf@12345');
        cy.get('button[type="submit"]').click();

        // OTP verification
        cy.get('input[name="code"]').type('123456');
        cy.get('.pf-v5-c-button').click();
    });
};

beforeEach(() => {
    login();
    cy.visit('https://backoffice.a2i.gov.bd/contents');
});

Terminal –

npf.a2i.gov.bd"before each" hook for "
2. Choose ministry cluster": AssertionError: Timed out retrying after 4000ms: expected '' to include 'https://login-npf-v2.softbd.xyz/realms/npf-global/protocol/openid-connect/auth'
This error occurred while creating the session. Because the session setup failed, we failed the test.
Because this error occurred during a before each hook, we are skipping the remaining tests in the current suite: npf.a2i.gov.bd

Screenshot: enter image description here & enter image description here

This program will run properly-

  • If I run the program normally without generating HTML reports, it works properly and run the test cases, and also showing the result on terminal. However, when I try to generate HTML reports using cypress-mochawesome-reporter, the authentication URL shows an error. Why? What’s the reasons?

Parsing JSON response in java script and build html table dynamically

I have below Javascript code

rdnStats = JSON.parse(response)     
document.getElementById("rdninfojson").textContent = JSON.stringify(rdnStats, undefined, 2);

<pre id="rdninfojson"></pre>

With above code on web page I can see below information

{
  "Redundancy mode": "ACTIVE",
  "Static conf values ": {
    "Validation": 1,
    "Period": "20 milliseconds",
    "Limit": 1,
    "Remote IP link1": "a.b.c.d",
    "Remote IP link2": "e.f.g.h",
    "Remote IP link3": "j.k.l.m",
    "Split size": 15360
  },
  "Redundancy statics": {
    "Mode": {
      "Local": {
        "Status": "ACTIVE",
        "Error": "0"
      },
      "Remote": {
        "Status": "BACKUP",
        "Error": "0"
      },
      "Network": {
        "Status": "LK3 ALIVE",
        "Error": "0"
      },
      "Comment": "Shows node mode"
    }
  }
}

Now I want to access element with below code

var confData = rdnStats['Static conf values '];
        alert(confData);

I am getting below output

[object Object]

I am expecting list of values as { … }. What mistake I am making? How can I get the values? Basically, I have to parse JSON data and put attribute values in each table for example “Static conf values ” in one table, Redundancy statics in another table?

How can I better achieve this in Javascript? I am new to Javascript and not sure how to achieve this.

Troubleshooting: Firebase Password Reset Emails Not Received (Vanilla JavaScript)

I’m trying to implement a password reset functionality using Firebase Authentication in my web application. While the code executes without errors, the reset password email is not being sent to users.
Note : i am currently working on localhos
Environment:

Firebase SDK version: 7.2.0
Using Firebase Auth and Firestore
Running on Laravel blade template

current code :


<script type="text/javascript">

    var database = firebase.firestore();

    function callForgotPassword() {
        var email_address = $('#email_address').val();

        $('.error').html("");
        if (email_address == "") {
            $('#email_address_error').html("{{trans('lang.email_address_error')}}");

        } else {
            database.collection("users").where("email", "==", email_address).where('role', '==', 'vendor').get().then(async function (snapshots) {
                console.log(snapshots.docs.length);
                if (snapshots.docs.length > 0) {

                    firebase.auth().sendPasswordResetEmail(email_address).then((result) => {
                        console.log(result);
                        $('#authentication_error').html("{{trans('lang.email_sent')}}");

                    }).catch((error) => {

                        $('#authentication_error').html(error.message);

                    });
                } else {

                    $('#authentication_error').html("{{trans('lang.email_user')}}");
                }
            });

        }
    }

</script>

What I’ve Verified:

The user email exists in Firestore (confirmed by snapshots.docs.length > 0)
Firebase Authentication is properly initialized
Email/Password sign-in method is enabled in Firebase Console
No errors are shown in the console
The .then() callback is executed successfully
The user’s email address is correct and properly formatted

Expected Behavior: User should receive a password reset email when requesting it.

Actual Behavior:

Code executes successfully (no errors)
Success message is displayed
But no email is received by the user
result in console is undefined

Note : i tried to use my own smtp settings in firebase to send email it did not work
and note i am trying to send to gmail account(and also other mail accounts it does not work).
Questions:

Are there specific Firebase Console settings I need to verify?
Does Firebase Auth require additional configuration for password reset emails?
How can I debug if the email is actually being sent by Firebase?
Are there any known issues with Firebase password reset in version 7.2.0?

Copy Image Into Chrome Browser’s Clipboard for MacOS, Windows, Ubuntu

I am trying to copy an image into browser’s(specifically chrome) clipboard for later paste via ctrl + v or cmd + v. I tried 2 different way to implement that feature but failed. And note that this is a test automation framework, and this action should run in headless browser as well.

First Approach:

My previous code was (After data parsing):

if image_path.lower().endswith(".svg"):
    mime_type = "image/svg+xml"
elif image_path.lower().endswith(".png"):
    mime_type = "image/png"
else:
    CommonUtil.ExecLog(sModuleInfo, "Unsupported file format. You can copy only PNG or SVG image.", 2)
    return "zeuz_failed"

with open(image_path, "rb") as image_file:
    image_data = image_file.read()

# Convert
image_b64 = base64.b64encode(image_data).decode('utf-8')

async_script = """
const base64Data = arguments[0];
const mimeType = arguments[1];
const callback = arguments[arguments.length - 1];

function b64toBlob(b64Data, contentType) {
    contentType = contentType || 'image/png';
    const byteCharacters = atob(b64Data);
    const byteArrays = [];
    
    for (let offset = 0; offset < byteCharacters.length; offset += 512) {
        const slice = byteCharacters.slice(offset, offset + 512);
        const byteNumbers = new Array(slice.length);
        
        for (let i = 0; i < slice.length; i++) {
            byteNumbers[i] = slice.charCodeAt(i);
        }
        
        const byteArray = new Uint8Array(byteNumbers);
        byteArrays.push(byteArray);
    }
    
    return new Blob(byteArrays, {type: contentType});
}

const blob = b64toBlob(base64Data, mimeType);
const item = new ClipboardItem({ [mimeType]: blob });

navigator.clipboard.write([item])
    .then(() => callback(true))
    .catch(async (err) => {
        console.error('Standard clipboard failed:', err);
        callback(false);
    });
"""

success = selenium_driver.execute_async_script(async_script, image_b64, mime_type)
if success:
    CommonUtil.ExecLog(sModuleInfo, f"The image ({mime_type}) successfully copied to clipboard.", 1)
    return "passed"
else:
    CommonUtil.ExecLog(sModuleInfo, "Failed to write image to clipboard", 3)
    return "failed"

This code was working for Ubuntu & Windows’s chrome, but asking for clipboard write permission. so i was unable to bypass this permission by using this approach(if you can then please share the solution). It’s an automation test framework, so we can’t give permission manually.

Second Approach:

Then i tried another approach, which is, i will create temporary container for that image and place the image in DOM & copy via selecting, then simply copy the image. So i wrote this code:

if image_path.lower().endswith(".svg"):
    mime_type = "image/svg+xml"
elif image_path.lower().endswith(".png"):
    mime_type = "image/png"
else:
    CommonUtil.ExecLog(sModuleInfo, "Unsupported file format. You can copy only PNG or SVG image.", 2)
    return "zeuz_failed"

with open(image_path, "rb") as image_file:
    image_data = image_file.read()

# Convert
image_b64 = base64.b64encode(image_data).decode('utf-8')

js_script = f"""
try {{
    const tempDiv = document.createElement('div');
    tempDiv.style.position = 'absolute';
    tempDiv.style.left = '-9999px';
    tempDiv.style.top = '-9999px';
    tempDiv.contentEditable = 'true';
    document.body.appendChild(tempDiv);
    
    const img = document.createElement('img');
    img.src = 'data:{mime_type};base64,{image_b64}';
    tempDiv.appendChild(img);
    
    // Select and copy
    const range = document.createRange();
    range.selectNodeContents(tempDiv);
    const selection = window.getSelection();
    selection.removeAllRanges();
    selection.addRange(range);
    const success = document.execCommand('copy');
    selection.removeAllRanges();
    
    document.body.removeChild(tempDiv);
    
    const event = new CustomEvent('copyImageResult', {{ detail: {{ success }} }});
    document.dispatchEvent(event);
}} catch (error) {{
    const event = new CustomEvent('copyImageResult', {{ detail: {{ error: error.message }} }});
    document.dispatchEvent(event);
}}
"""

blob_script = f"""
return new Promise((resolve) => {{
    const scriptBlob = new Blob([`{js_script}`], {{ type: 'application/javascript' }});
    const scriptUrl = URL.createObjectURL(scriptBlob);
    const script = document.createElement('script');
    
    const nonce = document.querySelector('script[nonce]')?.nonce;
    if (nonce) script.nonce = nonce;
    
    script.src = scriptUrl;
    
    document.addEventListener('copyImageResult', (e) => {{
        URL.revokeObjectURL(scriptUrl);
        script.remove();
        resolve(e.detail);
    }});
    
    document.head.appendChild(script);
}});
"""

try:
    result = selenium_driver.execute_script(blob_script)
    
    if result.get('success'):
        CommonUtil.ExecLog(sModuleInfo, f"Image copied to clipboard: {image_path}", 1)
        return "passed"
    else:
        error_msg = result.get('error', 'Unknown error')
        CommonUtil.ExecLog(sModuleInfo, f"Failed to copy image: {error_msg}", 3)
        return "failed"
except Exception as e:
    CommonUtil.ExecLog(sModuleInfo, f"JavaScript execution failed: {str(e)}", 3)
    return "failed"

this code giving error in browser’s console:

utils_js.js:2716 Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' 'wasm-unsafe-eval' 'inline-speculation-rules' http://localhost:* http://127.0.0.1:*". Either the 'unsafe-inline' keyword, a hash ('sha256-QgRF5QQhYvcb8AOx8AIBAHlvrqLG1SyG/Jlfg9eyGlI='), or a nonce ('nonce-...') is required to enable inline execution.

Trigger SVG such that it affects the elements that reference it in Firefox

When <animate> that is referenced by <use> is triggered (using beginElement()), the animation of <use> happens in Chrome but not in Firefox.

<svg>
  <path id="my-path" d="M 10 10 L 40 10 L 40 40 L 10 40">
    <animate attributeName="d" to="M 20 5 L 10 50 L 70 10 L 10 20" dur="1s" begin="indefinite"/>
  </path>
  <use href="#my-path" x="100"/>
  <use href="#my-path" x="200"/>
</svg>

<button onclick="document.querySelector('animate').beginElement()">
  Click here (all shapes change in Chrome, only one in Firefox)
</button>

Scheduling the animation relative to the page load with begin="1s" works, triggering it through specific events with begin="startButton.click" works, but triggering it any time with beginElement() doesn’t animate the <use> elements.

Is there a way to animate several shapes identically with a resource-efficient approach such as <use> instead of duplicating/cloning them?

For example, can JS access the <animate> that is inside <use>‘s shadow DOM? If this question about triggering the animation of each <use> individually is solved, we can use that as a (not necessarily the most efficient and synchronized) solution here.

getElementById() returns null in JavaScript

I’d like to create a dynamic select menu in JavaScript and hit a problem below.

When I run the codes below, I got an error which reads “Uncaught TypeError: Cannot read properties of null (reading ‘addEventListener’)”.

And the response to console.log(genreSelect) is null.
So I think document.getElementById('genre') doesn’t work as I expected.

Can anyone tell me what is wrong with me?

Here are the codes.
First “index.html”

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="select.js" ></script>
    <title>Document</title>
</head>
<body>
    <select name="genre" id="genre">
      <option disabled selected>Select a genre</option>
      <option value="japaneseFoods">Japanese</option>
      <option value="italianFoods">Italian</option>
    </select>

    <select name="food-name" id="food-name" disabled>
      <option disabled selected>Select a food</option>
    </select>
</body>
</html>

And next, “select.js”

const foodMenu = 
      {
        "japaneseFoods": ["sushi", "tenpura", "oden"],
        "italianFoods": ["pasta", "pizza", "minestrone"]
      };

function setMenuOptions(selectedGenre) {
  const selectFoodName = document.getElementById('food-name'); 
  menuList.disabled = false;

  foodMenu[selectedGenre].forEach((menu, index) => {
    const option = document.createElement('option');
    option.value = index;
    option.innerHTML = menu;
    selectFoodName.appendChild(option);
  });
}

const genreSelect = document.getElementById('genre');

console.log(genreSelect); // null

genreSelect.addEventListener('change', (e) => {
  console.log("a");
  setMenuOptions(e.target.value);
})

I put these codes on a Linux server(Ubuntu 22.04.4 LTS) and I access to the server from Mac(12.4), Chrome 137.0.7151.57

Judge0: “cannot write /sys/fs/cgroup/memory/box-XXX/memory.limit_in_bytes” Error on Ubuntu 24.04

I’m self-hosting Judge0 on a server running Ubuntu 24.04 (latest update). Everything was working fine on earlier versions (like Ubuntu 22.04), but now after setting it up on 24.04, I’m getting the following error for most code submissions:

cannot write /sys/fs/cgroup/memory/box-147/memory.limit_in_bytes: No such file or directory

enter image description here

What I’ve Done So Far:

  • I have installed Judge0 properly by following the official documentation from GitHub insite CHANGELOG.md file.

  • All required dependencies and services are installed and running via Docker and Docker Compose.

  • I verified that the containers are working correctly.

  • My setup includes the Full version (with all language runners, not just Base).

  • I’ve checked and confirmed that my request payloads are correctly structured.

  • I read multiple official docs, searched online forums, asked AI tools, and tried various suggested solutions, but the issue still remains unresolved.

About the autoconfig and JavaScript browser

Ok. Here are three reply options for that email thread:

  1. Nathan, the bug I see relates to addConfig() being executed outside of macro config UI activity.
  2. Thanks, Nathan. Yes, I’m referring to the bug with addConfig() firing unexpectedly.
  3. I am seeing an issue with how addConfig() is functioning, could we discuss it further? I think if you take a look at the keyboard there is a error prone in the browser of the Google keyboard …. And also the which keeps the chrome from updating so need code to remove that or need a new browser minus the error prone in the browser
    strong text keeps it from updates

HTML Geolocation display user and server

Is there a posible way to display client location and rider location using HTML Geolocation like deliver app.. like food panda.. using JavaScript or php.. and display the pathway of the client?

I want to display customer and deliver rider location on HTML Geolocation like foodpand