npm run dev is not working after installing vite for my react project

The server is not starting. Please someone Help me!
Showing this error:-

D:javascript PractiseReact1viteReactnode_modulesrollupdistnative.js:64
                throw new Error(
                      ^

Error: Cannot find module @rollup/rollup-win32-x64-msvc. npm has a bug related to optional dependencies (https://github.com/npm/cli/issues/4828). Please try `npm i` again after removing both package-lock.json and node_modules directory.
    at requireWithFriendlyError (D:javascript PractiseReact1viteReactnode_modulesrollupdistnative.js:64:9)
    at Object.<anonymous> (D:javascript PractiseReact1viteReactnode_modulesrollupdistnative.js:73:48)
    ... 2 lines matching cause stack trace ...
    at Module.load (node:internal/modules/cjs/loader:1207:32)
    at Module._load (node:internal/modules/cjs/loader:1023:12)
    at cjsLoader (node:internal/modules/esm/translators:345:17)
    at ModuleWrap.<anonymous> (node:internal/modules/esm/translators:294:7)
    at ModuleJob.run (node:internal/modules/esm/module_job:218:25)
    at async ModuleLoader.import (node:internal/modules/esm/loader:329:24) {
  [cause]: Error: The specified module could not be found.
  \?D:javascript PractiseReact1viteReactnode_modules@rolluprollup-win32-x64-msvcrollup.win32-x64-msvc.node
      at Module._extensions..node (node:internal/modules/cjs/loader:1473:18)
      at Module.load (node:internal/modules/cjs/loader:1207:32)
      at Module._load (node:internal/modules/cjs/loader:1023:12)
      at Module.require (node:internal/modules/cjs/loader:1235:19)
      at require (node:internal/modules/helpers:176:18)
      at requireWithFriendlyError (D:javascript PractiseReact1viteReactnode_modulesrollupdistnative.js:62:10)
      at Object.<anonymous> (D:javascript PractiseReact1viteReactnode_modulesrollupdistnative.js:73:48)
      at Module._compile (node:internal/modules/cjs/loader:1376:14)
      at Module._extensions..js (node:internal/modules/cjs/loader:1435:10)
      at Module.load (node:internal/modules/cjs/loader:1207:32) {
    code: 'ERR_DLOPEN_FAILED'
  }
}

I tried everything I found on the web.

  1. Reinsalling node-modules & package.lock.json file
  2. After deleting node-modules & package.lock.json I also cleared the cache using npm cache clear --force.
    Please Someone Help!

Web Speech Recognition API only working in Chrome and Edge, not Opera, Brave, etc

I have a script written in JavaScript that utilizes the Web Speech Recognition API. It is supposed that the API is compatible with all browsers based on Chromium, but my script only works in Google and Edge; it doesn’t work in Opera, Brave, or other browsers. Is there anything wrong with my script? (ignore the text in spanish please).

// Verifica si el navegador es compatible con la API de reconocimiento de voz
  if (
    "SpeechRecognition" in window ||
    "webkitSpeechRecognition" in window ||
    "OculusSpeechRecognition" in window
  ) {
    // Intenta acceder directamente a la propiedad proporcionada por el entorno
    recognition = new (window.SpeechRecognition ||
      window.webkitSpeechRecognition ||
      window.OculusSpeechRecognition)();
    recognition.lang = "es-ES"; // Establece el idioma de reconocimiento en español
    console.log("API de reconocimiento soportada");
  } else {
    console.log("API de reconocimiento no soportada");
    alert("La API de reconocimiento de voz no es compatible con este navegador."); // Muestra un mensaje de error de compatibilidad
    document.getElementById("startButton").disabled = true; // Deshabilita el botón de inicio
  } 

Javascript I cannot remove eventlistener

I have a shortened version of my code below. The thing is I cannot remove the event listener inside a function, which fires a simple alert. Any help?

const resizers = document.querySelectorAll(".resizer");

for (let resizer of resizers) {
  resizer.addEventListener("mousedown", mousedownForResizer);

  function mousedownForResizer(e) {
    console.log('deneme');
  }
}

function deneme() {
  let resizers = document.querySelectorAll(".resizer");
  for (let resizer of resizers) {
    resizer.removeEventListener("mousedown", mousedownForResizer, true);
  }
}

deneme();
.resizer {
  background: grey;
  width: 50px;
  height: 50px;
  border: 1px solid red;
}
<div class="resizer ne"></div>
<div class="resizer nw"></div>
<div class="resizer sw"></div>
<div class="resizer se"></div>

Problem with floating button on page load

I have a website with a page that contains links to pages in the same website. I need to have the link open in a new tab, with a CHAT button floating over the page in the new tab, or (if needed) sit at the top of the page. However, the button is not showing up on the new tab when it is opened. The website is running on Ubuntu 18.04 with Nginx. Does anyone know what I can add or change to get it to show up? I should add that I don’t mind if the new page needs to be loaded into a thin border frame in order to make it work (e.g iframe) – as long as it dynamically adjusts to the size of the new page.

Here’s how the code looks in each file: In one file (index9.php) I have the following code:


<!DOCTYPE html>
    <html>
    <head>
      <title>My Website</title>
      <script src="script.js" defer></script>
    </head>
    <body>
      <h1>Welcome to My Website</h1>
      <p><a href="about.html" target="_blank" onclick="executeScript()">About</a></p>
    </body>
    </html>"

In another file (script.js) in the same folder I have the following code:


/// Get all links on the page
const links = document.querySelectorAll('a');

// Add an event listener to each link
links.forEach(link => {
  link.addEventListener('click', (event) => {
    // Prevent the default link behavior
    event.preventDefault();

    // Open the link in a new tab
    const newTab = window.open('', '_blank');
    newTab.location.href = link.href;

    // Inject the floating button into the new tab's content document
    newTab.document.addEventListener('DOMContentLoaded', () => {
      const button = document.createElement('button');
      button.innerHTML = 'Chat';
      button.style.backgroundColor = 'green'; // Change the chat button background to green
      button.onclick = function() {
        // Open the chat window in a new tab
        window.open('chat.php', '_blank');
      };

      newTab.document.body.appendChild(button);
    });
  });
});

Any suggestions are welcome.

I have tried numerous iterations. All of them result in the new page opening properly, but the floating button is not showing up there.

Placing grouped points randomly on a 2d grid

Let’s say I’m working on a grid of binary values like so:

  1  1  0  0  0  0  0  
  0  0  0  0  0  0  1  
  0  1  0  0  0  0  0  
  0  0  0  0  0  0  0  
  0  0  0  1  0  0  0  

I have a set of “shapes” made up of 1s, that I want to place randomly on this grid, without overlapping each other or the other 1s on the grid:

  1  1     1           
           1  1     1  

Is there an algorithmic approach I can use to achieve this which is more efficient and reliable than the “brute force” approach, i.e. picking random spots for each shape until I find one that fits?

I’ve seen a few past questions dealing with similar problems, but they were all either contingent on specific details or had unclear answers, so I’m hoping you all can provide me with some more tailored advice. Thank you.

Trying to use JavascriptExecutor to test a button but getting ‘Unexpected keyword or identitfier’

i have the following line in my code:

JavascriptExector js = (JavascriptExector) driver;

I’m getting red lines under it with the error message ‘Unexpected keyword or identitfier’

i tried importing import org.openqa.selenium.JavascriptExecutor; but i got this error:

‘import … =’ can only be used in TypeScript files.ts(8002)`

im new to javascript i mostly use python, thanks!

PKIJS signature and verification don’t match

Consider the following code

    const data = await Deno.readFile("./README.md");
    const certificate = (await loadPEM("./playground/domain.pem"))[0] as Certificate;
    const privateKey = (await loadPEM("./playground/domain-pkcs8-nocrypt.key", "PRIVATE KEY"))[0] as CryptoKey;

    const signedData = await signData(data.buffer, certificate, privateKey);

    // verify same
    const ok = await signedData.verify({
        signer: 0,
        checkChain: true,
        trustedCerts: [certificate],
        data: data.buffer
    })

    console.log(ok); // false :(

    // verify external signed like this
    // openssl cms -sign -signer domain.pem -inkey domain-pkcs8-nocrypt.key -binary -in README.md -outform der -out signature

    const cms = ContentInfo.fromBER(await Deno.readFile("./playground/signature")) as ContentInfo;
    if (cms.contentType !== ContentInfo.SIGNED_DATA)
        throw new Error("CMS is not Signed Data");

    const signedData1 = new SignedData({ schema: cms.content });

    const ok1 = await signedData1.verify({
        signer: 0,
        checkChain: true,
        trustedCerts: [certificate],
        data: data.buffer
    })

    console.log(ok1); // true

In the first part I sign data and then I verify it against loaded certificate and it FAILS

In the second part I load a generated signature with openssl with same certificate and private key used in the first part and the verification against the loaded certificate is OK.
So, since verification method is the same in both examples, I guess my signature method has something wrong.
Here is the code for signature creation

export async function signData(data:ArrayBuffer, certificate: Certificate, privateKey: CryptoKey):Promise<SignedData>{
    const cmsSigned = new SignedData({
        encapContentInfo: new EncapsulatedContentInfo({
            eContentType: ContentInfo.DATA,
            //eContent: new ans1js.OctetString({ valueHex: data })
        }),
        signerInfos: [
            new SignerInfo({
                sid: new IssuerAndSerialNumber({
                    issuer: certificate.issuer,
                    serialNumber: certificate.serialNumber
                })
            })
        ],
        certificates: [certificate]
    });

    await cmsSigned.sign(privateKey, 0, "SHA-256", data);
    return cmsSigned;
}

Here is how I load certificate and key:

export async function loadPEM(src:string,
    type: PEMType = "CERTIFICATE" ):Promise<PkiObject[] | CryptoKey[]> {
    const buffer = pvtsutils.BufferSourceConverter.toArrayBuffer(await Deno.readFile(src));
    const binary = pvtsutils.Convert.ToBinary(buffer);
    const bers = decodePEM(binary, type);
    const ret = [];
    switch (type) {
      case "CERTIFICATE":
        return bers.map(ber => Certificate.fromBER(ber) as Certificate);
      case "PRIVATE KEY":
        for( const ber of bers) 
            ret.push(await crypto.importKey("pkcs8", ber, {
                name: "RSA-PSS",
                hash: "SHA-256",
                },
                true,
                ["sign"]));
        return ret;
      case "PUBLIC KEY":
        return bers.map(ber => PublicKeyInfo.fromBER(ber) as PublicKeyInfo);
    }
    
}

one of 3 vue3 aplication doenst work in the samsung smart tv tizen

I work with 3 vue3 projects, and of these 3, only 1 is not running correctly in the Samsung browser on the Samsung smart TV with Tizen OS. The problem is that the other 2 projects that work, there is this one that doesn’t work as a base, which really confuses me a lot, as apparently none of the 3 were supposed to work. The main error is that the Login Form component, on the home screen, is not mounted. it simply doesn’t exist, and it’s the same as other projects. I downloaded tizen studio to emulate the browser, but it is a complex tool and I was able to emulate the TV, without a browser. So, I accept tips on what and where to look for the error.
Is there any way to view the TV browser console to check for errors?
link of project doenst work: acampa.app

How to play different audio fragments in js continuously like a stream?

I’m trying to create simple audio streamer. On js client i’m sending 1 second audio fragments via websocket. Python server returns this audio and it’s played on client. The problem is the presence of gaps in the stream. What is the best way to manage this?

Frontend:

const ws = new WebSocket('ws://localhost:8001'),
    audio = new Audio()

ws.onopen = () => {
    console.log('opened');
    navigator.mediaDevices.getUserMedia({audio: true, video: false})
    .then(audioStream => {
        const mr = new MediaRecorder(audioStream)
        mr.ondataavailable = event => {ws.send(event.data)}
        stream(mr)
    })
}

function stream(mr) {mr.start();setTimeout(() => {mr.stop(); stream(mr)}, 1000)}
ws.onmessage = event => {audio.src = window.URL.createObjectURL(event.data);audio.play()}
ws.onclose = event => {console.log(`closed with code ${event.code}`)}
ws.onerror = () => {console.log('error')}

Backend:

import asyncio
import websockets


async def handler(websocket):
    while True:
        try:
            message = await websocket.recv()
            await websocket.send(message)
        except Exception as e:
            print(e)
            break


async def main():
    async with websockets.serve(handler, "", 8001):  # listen at port 8001
        await asyncio.Future()                       # run forever

if __name__ == "__main__":
    asyncio.run(main())

I tried to create queue of audios but it didn’t work

Lodash mergeWith not giving desired output using customizer

I’m using lodash with nodejs –

function customizer(objValue, srcValue, key) {
  if (key === 'required' && _.isArray(objValue) && _.isArray(srcValue)) {
    return _.intersection(objValue, srcValue);
  }
}

var a = { 
  'a': {
    'required': [1,2,3]
  }, 
  'b': {
    'required': [1,3]
  },
  'c': {
    'd': {
      'e': {
        'f': {
          'required': [4,5]
        }
      }
    }
  }
}

var b = { 
  'a': {
    'required': [1,2]
  }, 
  'b': {
    'required': [1,2,3]
  }
}

let c = {}
console.log(_.mergeWith(c, a, b, customizer));
.as-console-wrapper { max-height: 100% !important; }
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>

Right now it’s giving me following output –

{ 
  'a': { 
    'required': [1,2] 
  }, 
  'b': { 
    'required': [1,3] 
  }, 
  c: { 
    d: { 
      e: { 
        f: { 
          'required': [4,5] 
        } 
      } 
    } 
  } 
}

But I need following output –

{ 
  'a': { 
    'required': [1,2] 
  }, 
  'b': { 
    'required': [1,3] 
  }, 
  c: { 
    d: { 
      e: { 
        f: { 
          'required': [] 
        } 
      } 
    } 
  } 
}

Basically I wanted to make values for required key empty if it’s not common. My real life scenario is merging two templates where couple of keys might different. I wanted to keep those key-value pairs but wants to set required as empty for those fields.

transition not working without setTimeout in useEffect – ReactJS

I have one small component, with some text.

In useEffect, I am simply setting the top of the element to some values.

CSS:

.box {
   display: flex;
   flex-direction: column;
   position: relative;
   top: 0;
   transition: top 0 ease-in;
}





 useEffect(() => {
   setTimeout(()=> { // with this it is working.

    const elems = document.getElementsByClassName("box");
    
    [...elems].forEach(function (e) {
   
      e.style.top =`-200px`; // without settimeout transition is not working
  
    });
    });
  }, []);

Now when I do frequent refreshes, I see the transition happening a few times, but not every time.

But when I wrap my code in setTimeout I see a transition every time.

I am not sure why is this happening.

How to resolve flickering CSS in React App?

There’s a flicker when loading each page in my React app. I’ve tried bundling the stylesheets, but doesn’t seem to get rid of the flickering.

This is my root html:

  <div>
    <title>{props.title}</title>
    <link href="../css/normalize.css" rel="stylesheet" type="text/css" />
    <link href="../css/webflow.css" rel="stylesheet" type="text/css" />
    <link href="../css/webapp.webflow.css" rel="stylesheet" type="text/css" />
    <link href="https://fonts.googleapis.com" rel="preconnect" />
    <link href="https://fonts.gstatic.com" rel="preconnect" crossOrigin="anonymous" />
    <link href="../images/favicon.ico" rel="shortcut icon" type="image/x-icon" />
    <link href="../images/webclip.png" rel="apple-touch-icon" />
    <link
   href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css"
      integrity="sha512-nMNlpuaDPrqlEls3IX/Q56H36qvBASwb3ipuo3MxeWbsQB1881ox0cRv7UPTgBlriqoynt35KjEwgGUeUXIPnw=="
      crossOrigin="anonymous"
      referrerPolicy="no-referrer"
      rel="stylesheet"/>
    <link
      href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/css/intlTelInput.css"
      rel="stylesheet" />
    <link
      rel="stylesheet"
      href="../css/plugin.css" />
    {/*  REQUIRED CUSTOM CSS  */}
    <link
      rel="stylesheet"
      href="../css/custom.css" />
    <div className="x-access-body">
      {props.children}
    </div>
  </div>

fetch instagram data for n8n for my new ulanzi pixel clock

I run node.js with n8n. Now my problem: If I enter the url: https://i.instagram.com/api/v1/users/web_profile_info/?username=chrisschwaab (my profile) it does not give any information about the follower count back.

I also tried to enter this url:
https://i.instagram.com/api/v1/users/web_profile_info/chrisschwaab/

Also without any result. What would be the right url to get the follower-count-data?

Thanks!
Chris

I tried this:
https://i.instagram.com/api/v1/users/web_profile_info/chrisschwaab/
and
https://i.instagram.com/api/v1/users/web_profile_info/?username=chrisschwaab/