Recursively apply a projection to a nested object in Mongo DB

I have a data structure like this in MongoDB. It can have many levels:

{
    _id: ObjectId("123"),
    name: "Top level",
    someData: "hello world",
    parent: null,
    children: {
        "456": {
            _id: ObjectId("456"),
            name: "Nested Obj",
            parent: "123",
            someData: "lorem ipsum",
            children: {
                "963": {
                    _id: ObjectId("963"),
                    name: "2nd level nesting",
                    parent: "456",
                    someData: "some data",
                    children: {}
                }
        },
        "798": {
            _id: ObjectId("798"),
            parent: "123",
            name: "Another entry",
            someData: "more data here",
            children: {},
        }
    }
}

Is there a way to make a query that would allow me to:

  1. Recursively apply a projection to all nested objects.
  2. Create a calculated field that contains the path to get to each object.

For example, say that I am only interested in the _id and name fields, I would expect to see this as a result of the query:

{
    _id: ObjectId("123"),
    name: "Top level",
    path: []
    children: {
        "456": {
            _id: ObjectId("456"),
            name: "Nested Obj",
            path: ["123"]
            children: {
                "963": {
                    _id: ObjectId("963"),
                    name: "2nd level nesting",
                    path: ["123", "456"]
                    children: {}
                }
        },
        "798": {
            _id: ObjectId("798"),
            name: "Another entry",
            path: ["123"]
            children: {},
        }
    }
}

Is there a way to feed a microphone recording from MediaRecorder API to howler.js?

I’m currently trying to create audio clip blocks using howler.js, In order to create a sort of collaborative Garageband using HTML & JS.

My issue is that I’m trying to feed the audio from my microphone – MediaRecorder API to howler.js Sprite object. By passing in the blob to the source. In theory this should work. However, this is not the case.

I’m suspecting that the type of the Blobl is actually a video/webm instead of an audio/webm and that the howler.js Sprite can’t process the type.

There are no errors, just a lack of sound. The Sprite can process mp3s and webms in the directory, but cannot process the webm recorded by MediaRecorder, either as a blob or downloaded.

const blob = new Blob(chunks, {type: "audio/webm"});
chunks = [];
console.log("recorder stopped");
const audioURL = window.URL.createObjectURL(blob);

const audioSprite = new Sprite({
                width: [1500, 200],
                left: [20, 2000],
                src: [audioURL],
                html5: true,
                sprite: {
                    beat: [10000, 11163]
                },
                spriteMap: {
                    sprite1: 'beat',
                },
                format: ['webm', 'mp3'] // Specify the format of the blob
            });

If anyone has any suggestions as to how to get around this, I looked into using ffmpeg but unsure how to go about it. Any suggestions on an alternative for MediaRecorder or something to convert the file types that would be great.

Does calling dom manipulation functions from dom.js module in the index.js module count as logic and dom seperation?

I’m working on a Battleship game project and wanted to get some feedback on my approach to separating game logic and DOM manipulation.

Here’s what I’m doing:

In index.js, I manage the overall game flow, call functions from the gameboard, ship, and player modules for game logic, and also call DOM manipulation functions from dom.js to update the UI based on the current game state.

DOM manipulation (rendering the board, updating cells, etc.) is handled separately in the dom.js file.

The game logic (state, player actions, game flow) is managed in the gameboard, ship, and player modules.

So, in index.js, I’m coordinating everything, calling both the logic functions and the DOM functions from dom.js to handle the UI updates. Does this still count as a clean separation between game logic and DOM manipulation?

Would love to hear your thoughts!

How to create interactive images in web applications? [closed]

Have any of you had any experience creating interactive images? I need to create a wiring diagram that is interactive. You could zoom in, drag, and click on specific elements in the image, which might open the model or highlight elements on that image and more.

this is my end-goal:
https://service.tesla.com/docs/ModelY/ElectricalReference/prog-202/interactive/html/index.html?page=2&

Here is another example just in case:
https://liveleya.com/floor-plans/#/map

What tools are required to do that? Is it just an exported SVG image? Is there any material on how to do them?

How to integrate a header and footer from an existing site into a new landing page?

I’m working on a landing page that is built using an index.php file. I want to extract the header and footer (including their styles) from an existing news website and integrate them into my landing page.

Here’s what I’m looking to do:

Extract the header and footer HTML and styles from the news website.

Embed this header and footer into my landing page, keeping their original design and responsiveness.

Ensure that the styles (CSS) and any associated JavaScript that are part of the header and footer work seamlessly in my new landing page.

How can I achieve this? Should I manually copy the code, or is there a better way to reference and include them in my landing page without breaking the design and functionality?

Page modified with JS persists even after refresh [duplicate]

I have the following HTML page with 2 buttons. The first is disabled and the second, if clicked, enables the first. Everything works correctly except that when the page is refreshed, the first button remains enabled. This only happens on firefox and derivatives forks, on chrome based browsers it does not. Is there a solution to this without having to manually force the first button with ‘window.load’?

<html>
    <head>
    <title>Test</title>
    <style>
        button {
            display: inline-block;
            outline: 0;
            border: none;
            cursor: pointer;
            font-weight: 600;
            border-radius: 4px;
            font-size: 13px;
            height: 30px;
            background-color: #9147ff;
            color: white;
            padding: 0 20px;
        }
        button:hover {
            background-color: #772ce8;
        }
        button:disabled {
            background-color: #6433ae;
        }        
        body{
            background-color: black;
        }
    </style>
</head>
<body>
    <button id="a" onclick="saluta()" disabled>Test</button>
    <button id="b" onclick="enableA()">Enable A</button>
    
    <script>
        function enableA(){
            let buttonA = document.getElementById('a');
            buttonA.disabled = false;
            alert("Button 'Test' enabled");
        }
        function saluta(){
            alert("Hi!");
        }
    </script>
</body>
</html>

Does this Deno REPL in the browser resemble FIFO, Unix Domain Sockets, something else?

A file system experiment I’ve thought about for a while. Somehow creating a FIFO or Unix Domain Socket that is a bi-directional connection with streaming capabilities between arbitrary Web pages and whatever program I launch locally – without using Native Messaging, which is IPC over a JSON-like format, at least on Chromium.

Reading this Principle of Unix Domain Socket. How does it work? I thinkit’s kind of a mix of both.

The difference between FIFOs and Unix sockets, is that FIFO use file sys calls, while Unix sockets use socket calls.

Is this structure closure to a FIFO or Unix Domain Socket? Or something else? Not that I need a name or box for the communication channel. I just care that it does what I tell it to do. Just curious if the system fits into one of those standard Unix boxes? Something else…?

repl.js

for await (const e of Deno.watchFs("/home/user/Documents")) {
  for (const [index, path] of Object.entries(e.paths)) {
    if (path.split("/").pop() === "sock") {
      const input = Deno.readTextFileSync(path);
      console.log(e.kind, path);
      if (input.length > 0) {
        console.log(input);
        const command = new Deno.Command(Deno.execPath(), {
          args: [
            "eval",
            input,
          ],
        });
        const { code, stdout, stderr } = command.outputSync();
        await Deno.stdout.write(stdout);
        Deno.writeFileSync(path, stdout);
      } else {
        continue;
      }
    }
  }
}

repl-sock.js

  startIn: "documents",
  suggestedName: "sock",
});

async function repl(script, fs) {
  let readWrites = 0;
  const { resolve, promise } = Promise.withResolvers();
  const fso = new FileSystemObserver(async ([{
    changedHandle,
    root,
    type,
  }], record) => {
    try {
      if (++readWrites === 2) {
        readWrites = 0;
        const text = await (await changedHandle.getFile()).text();
        fso.unobserve(fs);
        fso.disconnect();
        const currentHandle = await changedHandle.createWritable();
        await currentHandle.truncate(0);
        await currentHandle.close();
        resolve(text);
      }
    } catch (e) {
      console.log(e);
    }
  });

  fso.observe(fs);
  return new Response(script).body.pipeTo(await handle.createWritable())
    .then(() => promise).then(console.log).then(() =>
      console.log(`Done writing to and reading from ${handle.name}`)
    ).catch((e) => console.log(e));
}

Usage, from DevTools console or Snippets on arbitrary Web page

repl(`console.log(Deno.version)`, handle).then(console.log)

// { deno: "2.2.6+b880087", v8: "13.5.212.4-rusty", typescript: "5.7.3" }
// Done writing to and reading from sock

Why does Drizzle ORM with TypeScript not recognize my schema and show missing properties in VS Code?

I recently migrated my Drizzle ORM setup from JavaScript to TypeScript, and now I’m facing an issue where the database schema is not recognized correctly.

enter image description here
Problem:
When I try to query my database using Drizzle ORM, I get the following TypeScript error:
Property ‘users’ does not exist on type ‘{}’.ts

Additionally, I am seeing this error when trying to assign drizzle to my db instance:
Type ‘DbQuery’ is not assignable to type ‘NodePgDatabase<Record<string, unknown>> & { $client: NodePgClient; }’.
Type ‘DbQuery’ is missing the following properties from type ‘NodePgDatabase<Record<string, unknown>>’: _, query, $with, $count, and 10 more.

import * as schema from "../core/models/index";
import { Pool } from "pg";
import { drizzle } from "drizzle-orm/node-postgres";
import { environmentVar } from "./env";

class DatabaseConnection {
  private static instance: DatabaseConnection | null = null;
  private pool!: Pool;
  private db: ReturnType<typeof drizzle> | null = null;

  constructor() {
    if (DatabaseConnection.instance) {
      return DatabaseConnection.instance;
    }

    if (!environmentVar.DATABASE_URL) {
      throw new Error("DATABASE_URL is not defined in the environment.");
    }

    this.pool = new Pool({
      connectionString: environmentVar.DATABASE_URL,
      max: 20,
      idleTimeoutMillis: 60000 * 5,
      connectionTimeoutMillis: 5000,
    });

    DatabaseConnection.instance = this;
  }

  getConnection() {
    if (!this.db) {
      this.db = drizzle(this.pool, { schema });
    }

    return this.db;
  }

  async close() {
    if (this.pool) {
      await this.pool.end();
      console.log("Database pool closed.");
    }
  }
}

const dbInstance = new DatabaseConnection();
export const db = dbInstance.getConnection();

query code

import { db } from "../../config/database";
import { eq } from "drizzle-orm";
import { users } from "../core/models/index";

async function findUserByPhoneNumber(phoneNumber: string) {
  const user = await db.query.users.findFirst({
    where: eq(users.phoneNumber, phoneNumber),
  });
  return user;
}

What I’ve Tried So Far:
✅ Confirmed that my schema is correctly exported from ../core/models/index.ts

✅ Tried console.log(db.query)—it returns [“userStatus”, “users”], so the schema does exist

✅ Manually imported users from the schema file instead of relying on db.query.users

✅ Changing database.ts to JavaScript (.js) makes it work without errors, but I want to use TypeScript

✅ Checked TypeScript configuration (tsconfig.json) to ensure strict mode is enabled

✅ Tried using as any as a workaround, but this is not a proper solution

Questions:
Why does TypeScript not recognize my schema and show an error even though the code works?

How can I fix this issue so that I get proper TypeScript auto-completion for db.query.users in VS Code?

Is there a proper way to define db so that Drizzle ORM correctly infers the schema?

note that this was working fine when my entire project was in javascript. it was giving proper suggestions in vs code autocompletion and was working fine.

Why does my linked JS file not work with my html file? I want to run JS script alongside my html file [closed]

I’m setting up a test website for the first time using html, css and JS. I’ve got a simple html page and a JS script page with a single javascript function to change some innerHTML text. However, I can’t seem to get the JS to work.

I’ve added an embedded piece of JS code into the html file (alert: hello world) which works fine.

Not sure what I’m doing wrong. I’ve used a relative path for the script link and I’m testing it by opening on my browser via VS code.

HTML:

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Projects</title>
    <link rel="stylesheet" href="./css.css">
    <link href="https://fonts.googleapis.com/css2?family=Oswald:[email protected]&family=Playfair+Display:ital,wght@0,400..900;1,400..900&family=Tektur:[email protected]&display=swap" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Oswald:[email protected]&family=PT+Serif:ital,wght@0,400;0,700;1,400;1,700&family=Playfair+Display:ital,wght@0,400..900;1,400..900&family=Tektur:[email protected]&display=swap" rel="stylesheet">
</head>



<body>
    <header>
        <nav class="navbar">
            <ul>
                <li><a href="Projects/MySite/Home.html">Developer  |  Steven Llewellyn</a></li>
                <li><a href="Projects/MySite/Projects.html">Projects</a></li>
                <li><a href="Projects/MySite/Skills.html">Skills</a></li>
                <li><a href="Projects/MySite/Contact.html">Contact</a></li>
              </ul>
        </nav>
    </header>



<main>

    <script>
       
        alert ('Hello World');
      
    </script>

    <section id="projheader">
        <h1>Projects</h1>
        <p>This page is to demonstrate what I've learned on my coding journey. Each section will have it's own description on 
        what it does.
        </p>
    </section>

      
    <section id="projcontainer">
        <h2>Project 1 - Logo Maker</h2>
        <p>This is a desciption of the project</p>
        <div id="proj1div">
            <h2>WHAT I WANT TO CHANGE</h2>
        </div>
    </section>

</main>



<footer>
 <address>
        <h2>London, UK</h2>
    </address>
</footer>

<!--  This code links the Javascript file to the page. --> 
<script src="Projects/MySite/Scripts/JS_logoMaker.js" ></script> 


</body>


</html>

JS file:

document.getElementById("projheader").innerHTML = 'THIS HAS BEEN CHANGED BY JAVASCRIPT CODE';

Add side resize for rectangle polygon layer in Mapbox GL

I’m building a tool for editing rectangular polygon on a Mapbox map in web. I rectangle has controls on the middle of each rectangle side that allow side resizing. This resizing should allow move only one certain side and make rectangle smaller or bigger.

Now I have below decision for handling move event:

onPointerMove = (event: MapMouseEvent) => {
    if (!isNumber(this.knobIndex)) return;
    if (!this.raster.coordinates?.length) return;

    const pointB = [event.lngLat.lng, event.lngLat.lat];

    const indexA = this.knobIndex;
    const indexB = (this.knobIndex + 1) % 4;

    const pointA = this.raster.coordinates[indexA];
    const pointC = this.raster.coordinates[indexB];

    const deltaX = pointB[0] - (pointA[0] + pointC[0]) / 2;
    const deltaY = pointB[1] - (pointA[1] + pointC[1]) / 2;

    const newCoordinates = [...this.raster.coordinates];
    newCoordinates[indexA] = [pointA[0] + deltaX, pointA[1] + deltaY];
    newCoordinates[indexB] = [pointC[0] + deltaX, pointC[1] + deltaY];

    this.onUpdate(newCoordinates);
  };

It works, but while resizing right side, for example, it moves not only in x axis, but also y axis. See photos.
[enter image description here](https://i.sstatic.net/pBlwuLCf.png)

But the rectangle should always maintain 90° angles (no distortion).

How can I correctly calculate the new positions of the two adjacent corners when moving a side while keeping the rectangle’s shape?

Overwrite video element: display a different image (manually decoded frame) & WebGL compatibility

Context

I’m currently building a library to precisely record (ideally any) javascript-based animation, even on slow computers or at very high framerate (e.g. 120fps to do motion blur later…). What I did so far was redefining all main functions (e.g. requestAnimationFrame, setTimeout, performance.now…) like window.Date.prototype.getTime = function(){return myfaketime;} so that they return a fake time or call the function only when I’m ready to play it (this may be after the actual time, or before if the computer is super fast or if the timeout are scheduled much later), following (and extending to CSS) what is done in Ccapture.js (I’m surprised how this technique works well so far).

Now, my goal is to also deal with video & audio. For now, let’s focus on videos. For video, one important issue is that seeking a video via myvideo.currentTime = foo is not frame-precise (all browsers will sometime randomly be off by a few frames), so I’d like instead to hook into <video> to replace the displayed content with a fixed frame generated, e.g., via the Web Codec API.

Question

Is it possible to programmatically overwrite the <video> element so that:

  1. I can add a method like myvideo.setContent(mybuffer), where mybuffer is a buffer/canvas containing the frame that I actually want my video to show. I tried to implement this with shadow root, but seems like video are not compatible with this (at least I get an error when I try…)? Ideally, I’d like to avoid solutions like replacing the <video> with, e.g., a canvas, as the user-defined animation may internally start/stop video by listing all <video> tags, and it might be tedious to adapt the code when a new video is added/removed etc. Also this would not be compatible with my second requirement:
  2. such that this method is compatible with, e.g., WebGL, that allows a texture to be generated from a video, i.e. I want WebGL to obtain my new frame and not the actual frame of the video. For now, I found a solution that involves changing all functions like WebGL2RenderingContext.prototype.texImage2D and it seems to work (at least I can intercept them), but there are many edge cases (WebGL/WebGL2/GPU, texImage2D/texSubImage…) so I’d prefer to find a simple solution that works directly for all methods.

Note that in the end, my library uses pupeetter, so if needed I can even imagine relying on browser extensions to do this instead of plain JS, even if I’d like to avoid this to stay browser-agnostic.

MWE

Here is a MWE with WebGL-based code copy/pasted from ThreeJS examples. Note that you should ideally not modify anything beyond the first (for now empty) <script> to illustrate the fact that this solution should work without modifying the animation defined by the user.

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>three.js webgl - materials - video</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
    <script>
      // We should ideally only overwrite here the components to play it differently
      // Ideally, both the standalone video and the threejs video should show
      // (up to the webgl added effects) the same frame, that is generated from, e.g.,
      // a canvas with something like:
      //       var c = document.createElement("canvas");
      //       var ctx = c.getContext("2d");
      //       ctx.beginPath();
      //       ctx.arc(95, 50, 40, 0, 2 * Math.PI);
      //       ctx.stroke();

    </script>
  </head>
  <body>

    <div id="overlay">
      <button id="startButton">Play</button>
    </div>
    <div id="container"></div>

    <div id="info">
      <a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> - webgl video demo<br/>
      playing <a href="http://durian.blender.org/" target="_blank" rel="noopener">sintel</a> trailer
    </div>

    <div id="testshadow"></div>
    
    Original video:
    <video id="video" loop playsinline style="width: 500px;">
      <!-- Downloaded from https://download.blender.org/durian/trailer/sintel_trailer-720p.mp4,
           must be hosted via https as webgl read of the video raises error as this is insecure -->
      <source src="sintel_trailer-720p.mp4" type='video/mp4'>
    </video>

    Threejs video:
    <script type="importmap">
      {
    "imports": {
          "three": "https://cdn.jsdelivr.net/npm/[email protected]/build/three.module.js",
          "three/addons/": "https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/"
    }
      }
    </script>

    <script type="module">

      import * as THREE from 'three';

      import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';
      import { RenderPass } from 'three/addons/postprocessing/RenderPass.js';
      import { BloomPass } from 'three/addons/postprocessing/BloomPass.js';
      import { OutputPass } from 'three/addons/postprocessing/OutputPass.js';

      let container;

      let camera, scene, renderer;

      let video, texture, material, mesh;

      let composer;

      let mouseX = 0;
      let mouseY = 0;

      let windowHalfX = window.innerWidth / 2;
      let windowHalfY = window.innerHeight / 2;

      let cube_count;

      const meshes = [],
        materials = [],

        xgrid = 20,
        ygrid = 10;

      const startButton = document.getElementById( 'startButton' );
      startButton.addEventListener( 'click', function () {

    init();

      } );

      function init() {

    const overlay = document.getElementById( 'overlay' );
    overlay.remove();

    container = document.createElement( 'div' );
    document.body.appendChild( container );

    camera = new THREE.PerspectiveCamera( 40, window.innerWidth / window.innerHeight, 1, 10000 );
    camera.position.z = 500;

    scene = new THREE.Scene();

    const light = new THREE.DirectionalLight( 0xffffff, 3 );
    light.position.set( 0.5, 1, 1 ).normalize();
    scene.add( light );

    renderer = new THREE.WebGLRenderer();
    renderer.setPixelRatio( window.devicePixelRatio );
    renderer.setSize( window.innerWidth, window.innerHeight );
    renderer.setAnimationLoop( animate );
    container.appendChild( renderer.domElement );

    video = document.getElementById( 'video' );
    video.play();
    video.addEventListener( 'play', function () {

      this.currentTime = 3;

    } );

    texture = new THREE.VideoTexture( video );
    texture.colorSpace = THREE.SRGBColorSpace;

    //

    let i, j, ox, oy, geometry;

    const ux = 1 / xgrid;
    const uy = 1 / ygrid;

    const xsize = 480 / xgrid;
    const ysize = 204 / ygrid;

    const parameters = { color: 0xffffff, map: texture };

    cube_count = 0;

    for ( i = 0; i < xgrid; i ++ ) {

      for ( j = 0; j < ygrid; j ++ ) {

        ox = i;
        oy = j;

        geometry = new THREE.BoxGeometry( xsize, ysize, xsize );

        change_uvs( geometry, ux, uy, ox, oy );

        materials[ cube_count ] = new THREE.MeshLambertMaterial( parameters );

        material = materials[ cube_count ];

        material.hue = i / xgrid;
        material.saturation = 1 - j / ygrid;

        material.color.setHSL( material.hue, material.saturation, 0.5 );

        mesh = new THREE.Mesh( geometry, material );

        mesh.position.x = ( i - xgrid / 2 ) * xsize;
        mesh.position.y = ( j - ygrid / 2 ) * ysize;
        mesh.position.z = 0;

        mesh.scale.x = mesh.scale.y = mesh.scale.z = 1;

        scene.add( mesh );

        mesh.dx = 0.001 * ( 0.5 - Math.random() );
        mesh.dy = 0.001 * ( 0.5 - Math.random() );

        meshes[ cube_count ] = mesh;

        cube_count += 1;

      }

    }

    renderer.autoClear = false;

    document.addEventListener( 'mousemove', onDocumentMouseMove );

    // postprocessing

    const renderPass = new RenderPass( scene, camera );
    const bloomPass = new BloomPass( 1.3 );
    const outputPass = new OutputPass();

    composer = new EffectComposer( renderer );

    composer.addPass( renderPass );
    composer.addPass( bloomPass );
    composer.addPass( outputPass );

    //

    window.addEventListener( 'resize', onWindowResize );

      }

      function onWindowResize() {

    windowHalfX = window.innerWidth / 2;
    windowHalfY = window.innerHeight / 2;

    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();

    renderer.setSize( window.innerWidth, window.innerHeight );
    composer.setSize( window.innerWidth, window.innerHeight );

      }

      function change_uvs( geometry, unitx, unity, offsetx, offsety ) {

    const uvs = geometry.attributes.uv.array;

    for ( let i = 0; i < uvs.length; i += 2 ) {

      uvs[ i ] = ( uvs[ i ] + offsetx ) * unitx;
      uvs[ i + 1 ] = ( uvs[ i + 1 ] + offsety ) * unity;

    }

      }


      function onDocumentMouseMove( event ) {

    mouseX = ( event.clientX - windowHalfX );
    mouseY = ( event.clientY - windowHalfY ) * 0.3;

      }

      //

      let h, counter = 1;

      function animate() {

    const time = Date.now() * 0.00005;

    camera.position.x += ( mouseX - camera.position.x ) * 0.05;
    camera.position.y += ( - mouseY - camera.position.y ) * 0.05;

    camera.lookAt( scene.position );

    for ( let i = 0; i < cube_count; i ++ ) {

      material = materials[ i ];

      h = ( 360 * ( material.hue + time ) % 360 ) / 360;
      material.color.setHSL( h, material.saturation, 0.5 );

    }

    if ( counter % 1000 > 200 ) {

      for ( let i = 0; i < cube_count; i ++ ) {

        mesh = meshes[ i ];

        mesh.rotation.x += 10 * mesh.dx;
        mesh.rotation.y += 10 * mesh.dy;

        mesh.position.x -= 150 * mesh.dx;
        mesh.position.y += 150 * mesh.dy;
        mesh.position.z += 300 * mesh.dx;

      }

    }

    if ( counter % 1000 === 0 ) {

      for ( let i = 0; i < cube_count; i ++ ) {

        mesh = meshes[ i ];

        mesh.dx *= - 1;
        mesh.dy *= - 1;

      }

    }

    counter ++;

    renderer.clear();
    composer.render();

      }


    </script>

  </body>
</html>

Validating Thickness (Margin/Padding) string using Regex for different platforms

I have a specific Regex pattern requirement for a string pattern which contains margin/padding (Thickness) for max 3 different platform and devices separated by semicolon. Margin and Padding format is for .NET MAUI where you can have Universal, Horizontal/Vertical, LTRB.

Comma separated is Thickness (Margin) and semicolon separator is for different devices/platforms. Note that end of string shouldn’t end with comma or semicolon.

Should Match (spaces are intentional for visibility)

  • 10
  • 10,10 ; 5,5
  • 10,11,12,13 ; 20,30 ; 50

Shouldn’t Match (spaces are intentional for visibility)

  • 10 ,
  • 10,10,999 ; 10,10 ,;
  • 10,10 ; , 10;10,10
  • 10 ;; 10

Tried this myself, but couldn’t achieve above.

^((?:d{1,3},?){1,4};?){1,3}$

SyntaxError: Cannot use import statement outside a module in Vercel

I am trying to deploy my React frontend on Vercelm but I am getting an error saying,

SyntaxError: Cannot use import statement outside a module

And the full message is:

(node:11) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
(node:11) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
/var/task/wh100/frontend/src/index.js:1
import React from 'react'
^^^^^^

SyntaxError: Cannot use import statement outside a module

I’ve searched online, and people have suggested using "type": "module", in packages.json, which I have.

If I try and use the .mjs extension, npm run start fails locally with:

ERROR in ./src/index.mjs 7:0-24
Module not found: Error: Can't resolve './App' in '/home/joshua/Documents/private_voti/voti/wh100/frontend/src'
Did you mean 'App.js'?
BREAKING CHANGE: The request './App' failed to resolve only because it was resolved as fully specified
(probably because the origin is strict EcmaScript Module, e. g. a module with javascript mimetype, a '*.mjs' file, or a '*.js' file where the package.json contains '"type": "module"').
The extension in the request is mandatory for it to be fully specified.
Add the extension to the request.

How do I deploy my frontend to vercel without running into this error?

Overriding window.alert() doesn’t seem to work [duplicate]

I have a recalcitrant alert() box I’m trying to troubleshoot in Chrome. I tried overriding alert(), confirm() and prompt() to trigger a debugger; statement, but no matter what I do, I cannot hit that debugger statement, even though I have DevTools opened the whole time.

Screenshot of the alert:

the alert box

My code (running in a small Chrome extension that runs on all frames (it has "all_frames": true in its manifest.json). I took the code from debug JS code which triggers an alert():

  window.alert_ = window.alert;
  window.alert = function () {
      debugger;
      alert_.apply(window, arguments);
  };

  window.confirm_ = window.confirm;
  window.confirm = function () {
      debugger;
      confirm_.apply(window, arguments);
  };

  window.prompt_ = window.prompt;
  window.prompt = function () {
      debugger;
      prompt_.apply(window, arguments);
  };