Cannot find ESLint loader (eslint-loader)

When running ´npm start´ i get this error in the console:

package.json start:

"scripts": {
  "start": "craco start"
}

craco.config.js file:

const million = require('million/compiler')


const cracoConfig = {
  webpack: {
    plugins: { add: [million.webpack({ auto: true })] },
  },
  typescript: {
    enableTypeChecking: true
  },
};

the error itself:

> start
> craco start

craco:  *** Cannot find ESLint loader (eslint-loader). ***
(node:3916) [DEP_WEBPACK_DEV_SERVER_ON_AFTER_SETUP_MIDDLEWARE] DeprecationWarning: 'onAfterSetupMiddleware' option is deprecated. Please use the 'setupMiddlewares' option.
(Use `node --trace-deprecation ...` to show where the warning was created)
(node:3916) [DEP_WEBPACK_DEV_SERVER_ON_BEFORE_SETUP_MIDDLEWARE] DeprecationWarning: 'onBeforeSetupMiddleware' option is deprecated. Please use the 'setupMiddlewares' option.

I tried doing the ./node_modules/.bin/eslint --init but it didn’t fix the problem.

How to find the following HTML Element

I have a menu with submenu with a structure like this:

   <ul>
     <li>
       <a class="navigation-item">Menu Item 1</a>
       <a class="submenu-toggle" />
       <ul class="submenu">
         <li>
           <a class="navigation-item">Submenu Item 1</a>
         </li>
       </ul>
     </li>
    </ul>

I want to add a class to submenu-toggle if Submenu Item 1 is selected. How can I find the submenu-toggle in this case?

closest('li') won’ work, this will only find the li after the submenu. closest('li > .submenu-toggle') doesn’t work either because the .submenu-toggle has to be an ancestor of the submenu item. If I could select the correct li, I could then use find('.submenu-toggle'). But how do I select the correct li?

Drag-and-drop action is being interpreted as a click, bypassing the confirmation dialog

We’ve got an EF6 MVC3 codeFirst-site. And recently i learned that if you click it, the confirm dialog works fine, but if you click and try to undo it by drag the link somewere and let go, you would assume that the click is cancelled. That works fine on my dev-environment but in production the link is really clicked, bypassing the confirmation dialog?

  <a href="@Url.Action("something","somecontroller")[email protected][i].CListId" onclick="return confirm('Do you really want this?');" class="btn btn-xs menulink" download><span class="glyphicon glyphicon-cloud-download"></span> Download</a>

 

Here is another example, click-drag is not making a click on localhost, but in production it is interpreted as a click

@Html.ActionLink("Välj", "BuyTicket", new { ticketTypeID = 11 }, new { @onclick = "return confirm('Vill du använda 124 poäng?')", @class = "btn btn-primary btn-xs orange pull-right" })

Does anyone have any suggestions?

TypeError: blocker.reset is not a function – useBlocker from react router dom v6.24

I’m using the useBlocker hook to display a custom modal alerting users about unsaved changes. The custom popup successfully triggers when the user attempts to navigate away. After form submission, the user should be redirected to the dashboard, so I’m calling blocker.proceed or blocker.reset to prevent the page from being blocked. but getting following error

TypeError: blocker.reset is not a function

index.js

const blocker = useBlocker(
    ({ currentLocation, nextLocation }) =>
      formData.projectName !== '' &&
      currentLocation.pathname !== nextLocation.pathname
  );

  useEffect(() => {
    if (createSolutionSpaceRes || createSolutionSpaceErrorRes) {

     blocker?.proceed() // error TypeError: blocker.proceed is not a function 
    }
    return () => {
      blocker?.reset();// error TypeError: blocker.reset is not a function 
    };
  }, [createSolutionSpaceRes, createSolutionSpaceErrorRes,blocker]);

enter image description here

following this example react router dom useBlocker hook

Is there any way to simulate touch events on iOS devices such as iPad?

I have coded it so that when you run this, it prompts for cps, and generates a red dot as indicator where you click, I don’t believe that this is working for ios, is there any way to make this work? This is intended to be ran as a bookmark.
‘’’
javascript:(function(){let cps=parseInt(prompt(“Enter clicks per second (CPS):”),10);if(isNaN(cps)||cps<=0){cps=1;}function createRedDot(x,y){const redDot=document.createElement(‘div’);redDot.style.position=’absolute’;redDot.style.width=’10px’;redDot.style.height=’10px’;redDot.style.backgroundColor=’red’;redDot.style.borderRadius=’50%’;redDot.style.pointerEvents=’none’;redDot.style.left=${x-5}px;redDot.style.top=${y-5}px;document.body.appendChild(redDot);setTimeout(()=>{redDot.remove();},1000);}function simulateTouch(x,y){const targetElement=document.elementFromPoint(x,y);if(targetElement){const touchStartEvent=new Event(‘touchstart’,{bubbles:true,cancelable:true});touchStartEvent.touches=[{clientX:x,clientY:y,target:targetElement}];targetElement.dispatchEvent(touchStartEvent);const touchEndEvent=new Event(‘touchend’,{bubbles:true,cancelable:true});touchEndEvent.changedTouches=[{clientX:x,clientY:y,target:targetElement}];targetElement.dispatchEvent(touchEndEvent);}}let isAutoClicking=false;function startAutoClicking(x,y){if(isAutoClicking)return;isAutoClicking=true;const interval=1000/cps;const clickInterval=setInterval(()=>{simulateTouch(x,y);},interval);setTimeout(()=>{clearInterval(clickInterval);isAutoClicking=false;},5000);}document.addEventListener(‘touchstart’,(e)=>{const touch=e.touches[0];const x=touch.clientX;const y=touch.clientY;createRedDot(x,y);startAutoClicking(x,y);});})();
‘’’

I tried changing the any the auto clicker works, and limited the rate of clicking, everything works except to the clicking part, as I’m not quite familiar with iOS systems and how they click.

growthladder design and worflow [closed]

I want to make a growthladder but I dont know how I set this thing up.

It should be a vertical line like a ruler and when you hover over it should scale the timeline and on the right it should shows a picture of the child in that period of time.

Can anyone guide me or know how to create this?

I know it is a very complex thing here. Hope someone can help

Thnx in advance!!
Dennis

Here I upload a example I quickly build in After Effects:
growthLadder_example

Track and control multiple microfrontends launched in a browser and update local storage on unloading the application

I have a microfrontend application or a website built in react. Every time I launch this application, it should increment the counter by one to track number of instances launched. And when I close, it should decrement the counter.

I am managing this in local storage of the browser. And if there is more than one instance I should not allow user to continue.

The problem is for the first application it is capable of decrementing the counter by detecting the unload event on closing the browser tab, but it does not do the same for the second MFE when tab is closed. Probably because the event is not detected due to browser trying to ignore such events and to optimise the behaviour.

Please suggest some ideas how this can be handled.

I have tried couple of ways to handle, but the problem I end up being is the browser ignoring the unload or beforeunload event when tabs are closed for the second instance of the application.

This way when I begin a new application the counter is always set to 1 if I do not restart the browser. This way it defeats the purpose of handling the instance where a user can only have one instance of the application.

Other way to handle this is to force user to click on Exit button for reliable experience and then decrement the counter.

How to effectively disable tab switching and application switching in React?

I’m working on a React application where I need to prevent users from switching tabs or applications when certain conditions are met. Specifically, I’m using the Visibility API to detect when the user switches tabs and the blur event to detect when the user switches to another application. I also attempt to block key combinations like Ctrl + Tab and Alt + Tab using a keydown event listener.

Here’s my code:

import { useEffect, useRef } from "react";
import { toast } from "@/utils/toast";

interface Props {
  isDisabled: boolean;
}

const DisableTabSwitch: React.FC<Props> = ({ isDisabled }) => {
  const listenersAdded = useRef(false);
  const tabSwitchCount = useRef(0);

  useEffect(() => {
    if (isDisabled && !listenersAdded.current) {
      listenersAdded.current = true;

      // Handle when the user switches tabs (using the Visibility API)
      const handleVisibilityChange = () => {
        if (document.visibilityState === "hidden") {
          tabSwitchCount.current += 1;
          toast.error(
            "Tab switching is not allowed. Please stay on the current tab. Your session is being recorded.",
            { duration: 3000, position: "top-right" }
          );
          window.focus();
        }
      };

      // Handle when the window loses focus (user switches away from the current app)
      const handleWindowBlur = () => {
        tabSwitchCount.current += 1;
        toast.error(
          "Please stay on this window. Switching applications is not allowed.",
          { duration: 3000, position: "top-right" }
        );
        window.focus();
      };

      // Handle specific keyboard shortcuts that allow switching between tabs/applications
      const handleKeyboardEvent = (event: KeyboardEvent) => {
        if (
          (event.ctrlKey && event.key === "Tab") || // Ctrl + Tab (Windows/Linux)
          (event.altKey && event.key === "Tab") || // Alt + Tab (Windows/Linux)
          (event.metaKey && event.key === "Tab") || // Cmd + Tab (macOS)
          (event.shiftKey && event.key === "Tab") // Shift + Tab
        ) {
          event.preventDefault();
          toast.error(
            "Keyboard shortcuts for tab/application switching are disabled during the session.",
            { duration: 3000, position: "top-right" }
          );
          window.focus();
        }
      };

      // Attach event listeners
      document.addEventListener("visibilitychange", handleVisibilityChange, true);
      window.addEventListener("blur", handleWindowBlur, true);
      window.addEventListener("keydown", handleKeyboardEvent, true);

      // Clean up event listeners when the component is unmounted or toggled off
      return () => {
        document.removeEventListener("visibilitychange", handleVisibilityChange, true);
        window.removeEventListener("blur", handleWindowBlur, true);
        window.removeEventListener("keydown", handleKeyboardEvent, true);
        listenersAdded.current = false;
      };
    }
  }, [isDisabled]);

  return null;
};

export default DisableTabSwitch;

This works to an extent, as I can detect when the tab or application switch happens. However, I’m still able to switch tabs using Ctrl + Tab (on Windows) and switch applications with Alt + Tab, or Cmd + Tab on macOS. I want to block these actions during the session but understand that browser security restrictions limit what can be done.

My questions are:

  1. Is there any way to more reliably prevent tab and application switching in modern browsers?
  2. Are there other ways to detect and discourage tab/application switching that I haven’t considered?
  3. How can I block or prevent these actions in a more secure way, or at least track them more effectively?

Thanks for any suggestions!

Smooth playback of real-time AMR audio packets in web client

I’m developing a real-time PTT (Push-to-Talk) system. The server receives compressed AMR packets, decompresses them to WAV format, and sends them to a web client. However, the audio playback on the client isn’t smooth. I suspect it’s because each packet sent to the client includes the entire WAV header, causing interruptions.
How can I optimize this process for smoother real-time audio playback? What’s the best practice for handling streaming audio in this scenario?

Here’s a snippet of what I’m currently working with on the client side:

class AudioPlayer {
    constructor(websocketUrl) {
        this.socket = new WebSocket(websocketUrl);
        this.audioContext = new (window.AudioContext || window.webkitAudioContext)();
        this.socket.onmessage = (event) => this.handleAudioData(event.data);
    }

    async handleAudioData(data) {
        const arrayBuffer = await data.arrayBuffer();
        const audioBuffer = await this.audioContext.decodeAudioData(arrayBuffer);
        this.playAudioBuffer(audioBuffer);
    }

    playAudioBuffer(audioBuffer) {
        const source = this.audioContext.createBufferSource();
        source.buffer = audioBuffer;
        source.connect(this.audioContext.destination);
        source.start();
    }
}

Thanks in advance for any help or insights!

populating audio source in lamejs

I have this code from the lamejs example:

let channels = 1; //1 for mono or 2 for stereo
let sampleRate = 44100; //44.1khz (normal mp3 samplerate)
let kbps = 128; //encode 128kbps mp3
let mp3encoder = new lamejs.Mp3Encoder(channels, sampleRate, kbps);
let mp3Data;

********** this line is stumping me: **********
let samples = new Int16Array(44100); //one second of silence (get your data from the source you have) 
let sampleBlockSize = 1152; //can be anything but make it a multiple of 576 to make encoders life easier
let mp3buf;

mp3Data = [];
for (let i = 0; i < samples.length; i += sampleBlockSize) {
  let sampleChunk = samples.subarray(i, i + sampleBlockSize);
  mp3buf = mp3encoder.encodeBuffer(sampleChunk);
  if (mp3buf.length > 0) {
    mp3Data.push(mp3buf);
  }
}
mp3buf = mp3encoder.flush(); //finish writing mp3

if (mp3buf.length > 0) {
  mp3Data.push(new Int8Array(mp3buf));
}

let audioBlob = new Blob(mp3Data, { type: "audio/mp3" });

I am not sure how to add my own source/samples: I am using the browser mediarecorder:

mediaRecorder.ondataavailable = (e) => {
  chunks.push(e.data);
};

I have tried to use chunks as the source/samples but I am not knowledgable enough about audio in general so can anyone help me on how to format the data and the underlying reason? I am just so lost as to where to start. Thanks in advance.

ENOENT: no such file or directory error when deploying Next.js app on Vercel

I’m encountering the following error after deploying my Next.js app on Vercel:

[Error: ENOENT: no such file or directory, open '/var/task/problems/add-two-numbers/boilerplate-full/function.java'] { errno: -2, code: 'ENOENT', syscall: 'open', path: '/var/task/problems/add-two-numbers/boilerplate-full/function.java', digest: '3522486023' }

This error occurs when the backend tries to access a .java or any other file in the /var/task/problems directory. The file exists locally and works fine in my development environment, but it doesn’t seem to be found on Vercel.

My Project Structure:

next-app:
--problems:
----add-two-numbers:
------boilerplate-full:
--------function.java
--------function.py
--------function.js
------inputs:
--------0.txt
--------1.txt
------outputs:
--------0.txt
--------1.txt
----other-problems:
--src:
----actions:
------problem.js:
----app:
------problem/[...problemSlug]/page.js
------page.jsx
------layout.jsx

src/actions/problem.js:

"use server";

import fs from "fs";
import path from "path";
import { LanguagesToExtension } from "./types";

const MOUNT_PATH = path.join(process.cwd(), "problems");

export const getProblem = async (problemSlug, languageId) => {
  languageId = LanguagesToExtension[languageId];
  const fullBoilderPlate = await getProblemFullBoilerplateCode(
    problemSlug,
    languageId
  );

  const inputs = await getProblemInputs(problemSlug);
  const outputs = await getProblemOutputs(problemSlug);

  return {
    id: problemSlug,
    fullBoilerplateCode: fullBoilderPlate,
    inputs: inputs,
    outputs: outputs,
  };
};

async function getProblemFullBoilerplateCode(problemSlug, languageId) {
  return new Promise((resolve, reject) => {
    fs.readFile(
      `${MOUNT_PATH}/${problemSlug}/boilerplate-full/function.${languageId}`,
      { encoding: "utf-8" },
      (err, data) => {
        if (err) {
          reject(err);
        }
        resolve(data);
      }
    );
  });
}

async function getProblemInputs(problemSlug) {
  return new Promise((resolve, reject) => {
    fs.readdir(
      `${MOUNT_PATH}/${problemSlug}/tests/inputs`,
      async (err, files) => {
        if (err) {
          console.log(err);
        } else {
          await Promise.all(
            files.map((file) => {
              return new Promise((resolve, reject) => {
                fs.readFile(
                  `${MOUNT_PATH}/${problemSlug}/tests/inputs/${file}`,
                  { encoding: "utf-8" },
                  (err, data) => {
                    if (err) {
                      reject(err);
                    }
                    resolve(data);
                  }
                );
              });
            })
          )
            .then((data) => {
              resolve(data);
            })
            .catch((e) => reject(e));
        }
      }
    );
  });
}

async function getProblemOutputs(problemSlug) {
  return new Promise((resolve, reject) => {
    fs.readdir(
      `${MOUNT_PATH}/${problemSlug}/tests/outputs`,
      async (err, files) => {
        if (err) {
          console.log(err);
        } else {
          await Promise.all(
            files.map((file) => {
              return new Promise((resolve, reject) => {
                fs.readFile(
                  `${MOUNT_PATH}/${problemSlug}/tests/outputs/${file}`,
                  { encoding: "utf-8" },
                  (err, data) => {
                    if (err) {
                      reject(err);
                    }
                    resolve(data);
                  }
                );
              });
            })
          )
            .then((data) => {
              resolve(data);
            })
            .catch((e) => reject(e));
        }
      }
    );
  });
}

Earlier, the position of problems folder is in src folder.

I have also used
const MOUNT_PATH = path.relative(_dirname,”src”,”problems”); &&
const MOUNT_PATH = path.join(“src”, “problems”);

Ensured the file paths are correct.
Checked that the file is committed to GitHub and included in the build.
I’m unsure if this issue is related to Vercel’s file system or a configuration error.

GitHub Repository:
https://github.com/chman-chaudhary/gla-Codify

Any help to resolve this would be appreciated! Thanks in advance!

After upgrading from bootstrap 4.3.1 to 5.3.3 am getting error

I have upgraded bootstrap library from 4.3.1 to 5.3.3 and when I tried to run the code am getting error like this :

Uncaught Error: Module build failed (from ./node_modules/react-scripts/node_modules/sass-loader/dist/cjs.js):
SassError: calc(1.25rem * 1em) isn't a valid CSS value.
 @return if($return-calc == true, calc(#{$value1} + #{$value2}), $value1 + unquote(" + ") + $value2);

2. ./node_modules/react-scripts/node_modules/css-loader/dist/cjs.js??ref--5-oneOf-6-1!./node_modules/postcss-loader/src??postcss!./node_modules/resolve-url-loader??ref--5-oneOf-6-3!./node_modules/react-scripts/node_modules/sass-loader/dist/cjs.js??ref--5-oneOf-6-4!./src/styles/index.scss)
SassError: calc(1.25rem * 1em) isn't a valid CSS value.
 @return if($return-calc == true, calc(#{$value1} + #{$value2}), $value1 + unquote(" + ") + $value2);

The Sass error @return if($return-calc == true, calc(#{$value1} + #{$value2}), $value1 + unquote(" + ") + $value2); is in _variables.scss file

Can anyone help me to solve this issue?

I have upgraded the bootstrap library and along with that I have upgraded sass to 1.79.5 from 1.54.9, sass-loader, css-loader to latest versions and tried downgrading the versions also.

I tried reverting the bootstrap version to 4.3.1 and it is working fine problem is only when I upgrade it.

Can anyone help me to resolve this issue?

How to Use the Vertex API With Long Text Prompts

Overview

I’ve been using the Vertex API relatively successfully for the past few months, but I’ve noticed that when the text part of your prompt becomes extremely long, for example, 130,000 characters or so, the API seems to malfunction.

Implementation Details

  • Gemini 1.5 Pro as the llm
  • React front-end
  • Firebase / Firestore / Cloud Functions as the back-end

API Infrastructure

I’ve tried two approaches to integrating with Vertex:

  1. Using the vertexai-preview package that ships with firebase
  2. Using the VertexAI NodeJS package in a cloud function with increased (1 GB) memory allocation and a longer (120 sec) max runtime

Package Structure

All of my calls to Vertex follow the documentation’s pattern, where the “files” sent to the llm are included via a Cloud Storage URI and the text parts of the prompt are text parts. Like this:

async function multiPartContent() {
    const filePart = {fileData: {fileUri: "gs://generativeai-downloads/images/scones.jpg", mimeType: "image/jpeg"}};
    const textPart = {text: 'What is this picture about?'};
    const request = {
        contents: [{role: 'user', parts: [textPart, filePart]}],
      };
    const streamingResult = await generativeVisionModel.generateContentStream(request);
    for await (const item of streamingResult.stream) {
      console.log('stream chunk: ', JSON.stringify(item));
    }
    const aggregatedResponse = await streamingResult.response;
    console.log(aggregatedResponse.candidates[0].content);
}

In my case, I am using the generateContentStream approach.

Expected Behavior

Given the massive context window, I expect to be able to send lots of information to the llm, then get a response back.

Observed Behavior

vertexai-preview client-side package

When using the vertexai-preview package, I get a Firebase Error with no message property as I start pushing the requests, including more files and text.

I can confirm that my usage is nowhere near the 2m token context window. Usually, these heavier requests are around 200k tokens.

VertexAI server-side approach

Here’s a relevant code block from my Cloud Function:

const req = {
      contents: [{ role: "user", parts }],
    };

    console.log(`Initiating content generation for docId: ${docId}`);
    const streamingResp = await generativeModel.generateContentStream(req);

This logic will work for non-large requests, but when there’s a heavier request, it will fail. In the cloud logs, I’ll see the “Initiating content generation” and, even though I’m catching the errors in my code (the block you see is inside a try / catch block), I don’t see any additional cloud logs. The process literally just poof ends.

Some things I’ve tried

Chunking the text parts

I’ve tried to convert long text strings into multiple smaller (e.g. ~50k character) text parts. So, the parts I send the llm have, for example:

  • 3 fileUri parts
  • 3 text parts

This didn’t work at all.

Sending the long text part as a fileUri part

I’ve tried converting long text strings into stored plain text files, then sending them as fileUri parts.

This approach does seem to improve reliability. Here, I run into something of a prompt engineering problem, because the prompt actually is in the now-stored text file that I’ve sent to the LLM.

Summary

Overall, I’m finding it difficult to work with the Vertex API with these larger requests. The Vertex API claims to be able to process these heavy requests, but I’m just finding that as I make these higher-token requests the API completely fails with errors that are non-descriptive.

  • I never see any max memory errors
  • I never see any function run time errors
  • I never see any errors talking about the length of the text part of my prompt (also, if you happen to know what, if any, limitations there are on the text part of Vertex prompts, please let me know)

I’d love to know how to approach this.

dev tools: $0.click(); behaves differently to the object it contains

In the HTML there is an element:

<div class=​"data-grid-cell-content" data-bind=​"text:​ $col.getLabel($row())">100000028</div>

in a row that is clickable. I use ‘inspect’ to get that element as $0. The following commands work:

$0.click();
row = $0;
row.click();

However, the following snippet doesn’t, giving this error:

Uncaught SyntaxError: Unexpected token ‘<‘

<div class=​"data-grid-cell-content" data-bind=​"text:​$col.getLabel($row())">100000028</div>.click();

I need to put parentheses () somewhere but can’t work out where?

Attach ID to K6 requests to help keep track under concurrent usage

I am using K6 to performance/load test my API and test its concurrency handling.

I have set up a config of 10 concurrent users for 10 seconds, but I would like to track the actual unique requests coming into the API.

I initially thought about adding an ID header (I log out the header in the API for debugging) like and doing an iteration such as:

export default function() {
  const params = {...PARAMS};
  for (let i = 1; i < 10000; i++) {
    params.headers['some-id'] = `id-${i}`;
    http.get(ENDPOINT, PARAMS);
    sleep(SLEEP);
  }
}

However this didn’t yield the output I was initially expecting, with there being 10 instances of id-1, 10 instance of id-2 and so on…

After seeing the output I understand that this is due to there essentially being 10 users sending the first request with ID-1 etc.

Is there a way in which I can achieve concurrent users with different header params being sent in?