error: node_modulesaxiosindex.js:D:MindInsight-mainnode_mo (reading “addHelper

When I tried npm install jest, and the console showed that I had four high-risk vulnerabilities, I executed the NPM audit fix-force as he gave me the command, and I hadn’t run my program yet, when I tried to run the app on my phone again, I was given the following error.
enter image description here
enter image description here

I tried to clear the cache while I was trying to fix the error, then re-npm install and re-run, what is the problem and how should I solve it?

Ignore whitespace in the end of the string [duplicate]

I am using RegExp. I am trying to filter elements according to a list of specific values I have. Some of the elements have whitespace in the end of the value. Trying to use s+ or s* or other options, sadly do not work.

I ended up using Playwright’s or functionality, once without whitespace and once with whitespace. There must be a better option, but none seem to work for me.

.getByText(new RegExp(`^${value}$`))
    .or(page.getByText(new RegExp(`^${value} $`)))

Editing:
My input contains a list of names (Daniel, Tanya, Vered). The elements on the webpage might contain a whitespace in the end of the string.

How do I use jsdoc to document a set of functions that destructured from the return value of another function?

Firstly, I have read this question/answer, and it doesn’t quite apply to my situation.

I’m calling a library function, which dynamically creates and returns an array of functions. My module then exports those functions, so I want them to be documented. My code looks like like this:

import createFunctions from 'some-library'

/**
* What do I write here, to document `functionA` and `functionB`?
*/
const [functionA, functionB] = createFunctions('a', 'b');

// This doesn't seem to work:
/**
* Some docs
*/
functionA;

// This also doesn't seem to work:
/**
* Some docs
*/
export { functionA };

/**
* I don't know how this would work either
*/
export { functionA, functionB };

I don’t control createFunctions, so I can’t write doc comments inside it to describe the returned functions, as suggested in the other answer.

EDIT: I’ve already tried both of these approaches and they don’t seem to work, at least vscode does not pick them up:



Double Color in Three Js Buffer Geomtery shapes

I am using three.js to create shapes, but while drawing my irregular polygon shapes face double coloring using while drawing from certain directions. Example: I attached two pictures of same shapes, while one drawn from right side will be good but the one drawn from left will create a double color effect. How can I fix this?

Here is the image of shape with double color problem; the yellow height shows double color issue

enter image description here

Here the code of generating the shapes

let polyShape = new THREE.Shape(coordinates.map((coord) => new THREE.Vector2(coord.x, coord.y)))
const polyGeometry = new THREE.ShapeGeometry(polyShape);
polyGeometry.setAttribute("position", new THREE.Float32BufferAttribute(coordinates.map(coord => [coord.x, coord.y, coord.z]).flat(), 3))
let polygon = new THREE.Mesh(polyGeometry, new THREE.MeshBasicMaterial({ color: "white",side: THREE.DoubleSide, opacity:0.05, transparent:true,depthTest:false}))

I want that drawing from any direction won’t cause such problem.

How do I load Google Earth in the browser?

I cannot seem to load Google Earth in browser (client-side).

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Sat Tracker</title>
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBz-dBHvKyjhsCiKwyGT7x_qIFp91yTLYM"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/earthengine/0.1.226/earthengine-api.min.js"></script>
    <script async src="data.js"></script>
    <script async src="app.js"></script>
  </head>
  <body>
    <div id="map" style="width: 100%; height: 100vh"></div>
  </body>
</html>

I get a bunch of cors errors and I can’t find any instructions.

Puppeteer ignoring background-color property in generated PDF

I’m using Puppeteer to generate PDF reports from HTML content, and I’m encountering an issue where the background-color property defined in the HTML is being ignored in the generated PDF. I have ensured that the HTML content includes inline styles with background-color properties, but the background colors are not being applied in the PDF output.

Here’s a simplified version of the code I’m using:

const puppeteer = require('puppeteer');

async function generatePDF() {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  
  const htmlContent = `
    <html>
      <head>
        <title>PDF Report</title>
      </head>
      <body>
        <div style="background-color: red; padding: 20px;">
          <h1>Sample Report</h1>
          <p>This is a sample PDF report with a red background.</p>
        </div>
      </body>
    </html>
  `;
  
  await page.setContent(htmlContent);
  const pdfBuffer = await page.pdf({ format: 'A4' });
  
  await browser.close();
  
  return pdfBuffer;
}

generatePDF().then(pdfBuffer => {
  // Handle PDF buffer
});

In the above code, I’m setting the background-color property to red for a element in the HTML content. However, when I generate the PDF using Puppeteer, the background color is not applied in the output PDF.

I have verified that the HTML content is correctly formatted and that other styles (e.g., padding) are applied as expected. I’m wondering if there’s a limitation or issue with Puppeteer’s rendering engine that is causing it to ignore the background-color property specifically.

How can I ensure that the background-color property defined in the HTML is properly applied in the generated PDF output using Puppeteer?

Calculate rotation between 2 points in openlayers using javascript

I’m using OpenLayers with JavaScript, and I’m calculating the rotation between two points (they represent arrows indicating the path taken by a vehicle). I have the following function:

function calculateAngleBetweenTwoPoints(point1, point2) {
  let lonLat1 = ol.proj.toLonLat(point1.getGeometry().getCoordinates());
  let lonLat2 = ol.proj.toLonLat(point2.getGeometry().getCoordinates());

  let angleRad = - Math.atan2(lonLat2[1] - lonLat1[1], lonLat2[0] - lonLat1[0]);
  let angleDeg = (angleRad * 180) / Math.PI;

  let vector_angle = Math.abs(angleDeg) % 360 ;
  vector_angle = (vector_angle * Math.PI) / 180;
  return vector_angle;
}

Although the orientation is correct for some points, it fails with some points. All points are rendered, I call it here:

function createArrowVectorLayer(points, image) {
  const features = [];

  for (let i = 0; i < points.length; i++) {
      const point1 = points[i];
      let point2 = "";
      let rotation = 0;
      if (points[i + 1] === undefined) {
        rotation = 0;
      } else {
        point2 = points[i + 1];
        rotation = calculateAngleBetweenTwoPoints(point1, point2);
    }

    const arrowStyle = new ol.style.Style({
        image: new ol.style.Icon({
            src: image,
            scale: 0.03,
            rotation: rotation,
            anchor: [0.5, 0.5],
            graphicXOffset: -18,
            graphicYOffset: -18,
        }),
    });

    point1.setStyle(arrowStyle);
    features.push(point1);
}

Does anyone know what is wrong?

How to get an index of random property of array of objects?

I have an array of objects.

const items = [{
  name: "item1",
  img: "img/pic/picture1.png"
},
  name: "item2",
  img: "img/pic/picture2.png"
},
  name: "item3",
  img: "img/pic/picture3.png"
}];

I’m getting a random img property from it.

const randomImg =items[Math.floor(Math.random() *items.length)].img;
itemImg.src = `${randomImg}`;

I’d like to get a name property and assign it as alt. Could you direct me in which way I should do this?

I tried findIndex() method and indexOf(). But still got undefined or -1.

const altIndex = items.indexOf(randomImg);
itemImg.alt = items[altIndex].name;

//or
const altIndex = items.findIndex(ele => ele === randomImg[ele]);

Am I on the right way? Thank you in adavance and have a good day!

502 when using websockets

import React, { useEffect, useState } from "react";
import "../App.css";
import Maps from "./Maps";
import SideNavigation from "../Sidebar/Navigation";
import axios from "axios";
import io from "socket.io-client";
import { faVolumeUp, faVolumeXmark } from "@fortawesome/free-solid-svg-icons";
import Cookies from "js-cookie";

const socket = io.connect(`${process.env.REACT_APP_SERVER_IP}:3001`, { withCredentials: true, transports: [ "websocket" ] });

export const Location = () => {
    const [shake, setShake] = useState(false);
    const [state, setState] = useState(false);
    const [lat, setLat] = useState("");
    const [lng, setLng] = useState("");
    const [gpsTime, setGPSTime] = useState("");
    const [disconnected, setDisconnected] = useState(true);
    const [speaker, setSpeaker] = useState(true);

    async function getData() {
        const userID = Cookies.get("userID");
        const response = await axios.get(
            `${process.env.REACT_APP_SERVER_IP}/api/getData?userID=${userID}`
        );
        if (response.data.state === 0) {
            setState(false);
            setSpeaker(faVolumeXmark);
            setShake(false);
        } else if (response.data.state === 1) {
            setState(true);
            setSpeaker(faVolumeUp);
            setShake(true);
        } else {
            console.log(response);
        }
    }

    function checkConnectivity() {
        if(lng === "" || lat === "") {
            setDisconnected(true);
        }
    }

    async function getGPS() {
        const userID = Cookies.get("userID");
        if(lng === "" || lat === "") {
            const response = await axios.get(
                `${process.env.REACT_APP_SERVER_IP}/api/getGPS/${userID}`
            );
            setLat(response.data.latitude);
            setLng(response.data.longitude);
            setGPSTime(response.data.updatedDateTime);
            setDisconnected(true);
        }
    }

    async function buzzer(event) {
        event.stopPropagation();
        const userID = Cookies.get("userID");
        fetch(`${process.env.REACT_APP_SERVER_IP}/api/updateBuzzer/${userID}`, {
            headers: {
                "Content-Type": "application/json",
            },
            method: "PUT",
            body: JSON.stringify({
                state: !state,
                output: "buzzer",
            }),
        }).then([
            setShake(!shake),
            setState(!state),
            state ? setSpeaker(faVolumeUp) : setSpeaker(faVolumeXmark),
        ]);
    }
    
    useEffect(() => {
        getData();
        checkConnectivity();
        getGPS();
        socket.on("postData", (data) => {
            if (!data.lat || !data.lng || !data.lat === 0 || !data.lng === 0) {
                getGPS();
            } else {
                setLat(data.lat);
                setLng(data.lng);
                setGPSTime(data.dateTime);
                setDisconnected(false);
            }
        });
    }, [shake, state, lat, lng, gpsTime, disconnected, speaker]);

    return (
        <div className="d-flex flex-row">
            <div>
                <SideNavigation></SideNavigation>
            </div>
            <div
                style={{ width: "100%", height: "100vh" }}
                className="d-flex flex-column">
                <Maps
                    buzzer={buzzer}
                    shake={shake}
                    lat={lat}
                    lng={lng}
                    gpsTime={gpsTime}
                    disconnected={disconnected}
                    speaker={speaker}
                />
            </div>
        </div>
    );
};

Before socket.on:
Response headers:
HTTP/1.1 200 OK
Server: nginx/1.18.0 (Ubuntu)
Date: Thu, 18 Apr 2024 10:43:12 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 11
Connection: keep-alive
X-Powered-By: Express
Access-Control-Allow-Origin: https://www.inswalst.com
Vary: Origin
Access-Control-Allow-Credentials: true
ETag: W/”b-P4CuhGK30Ou/ASQzSDPwfuj0UVU”

Request headers:
GET /api/getData?userID=1713172252 HTTP/1.1
Host: inswalst.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/115.0
Accept: application/json, text/plain, /
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Origin: https://www.inswalst.com
Connection: keep-alive
Referer: https://www.inswalst.com/
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site

When socket.on:
Response headers:
HTTP/1.1 502 Bad Gateway
Server: nginx/1.18.0 (Ubuntu)
Date: Thu, 18 Apr 2024 10:49:13 GMT
Content-Type: text/html
Content-Length: 166
Connection: keep-alive

Request headers:
GET /api/getData?userID=1713172252 HTTP/1.1
Host: inswalst.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/115.0
Accept: application/json, text/plain, /
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Origin: https://www.inswalst.com
Connection: keep-alive
Referer: https://www.inswalst.com/
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
If-None-Match: W/”b-P4CuhGK30Ou/ASQzSDPwfuj0UVU”

Why I get 502 for https://inswalst.com/api/getData?userID=1713172252 when socket.on? How to solve it?

Issue in JSX (TSX) Component React

I was working on React Native Project with Typescript. I got the issue with only index.tsx filename in ColoredDate folder. I also have same folders like Dialog & Search but those aren’t throwing any errors

Folder Structure

- Root Of The Project
|
|
 --- components/
       |
       -- ColoredDate/
             |
             --- index.tsx

Here’s The Error
Error

Here’s Folder Structure
Folder Structure

If I change the filename from index.tsx to anything.tsx All issues resolved. But changing file name isn’t the appropriate solution in my opinion.

Electron app auth0 SSO login with system default browser

I followed this auth0 electron app documentation to login inside electron app for auth0 but when an accaount is SSO(Single Sign On) electron BrowserWindow doesn’t work like system default chrome and can’t authenticate the single sign on users. But when I login on chrome directly chrome sees. How can I implement auth0 login in electron app as login works on system default chrome.
createAuthWindow() method uses BrowserWindow and it doesn’t open system default browser for SSO.

const jwtDecode = require('jwt-decode');
const axios = require('axios');
const url = require('url');
const envVariables = require('../env-variables');
const keytar = require('keytar');
const os = require('os');

const {apiIdentifier, auth0Domain, clientId} = envVariables;

const redirectUri = 'http://localhost/callback';

const keytarService = 'electron-openid-oauth';
const keytarAccount = os.userInfo().username;

let accessToken = null;
let profile = null;
let refreshToken = null;

function getAccessToken() {
  return accessToken;
}

function getProfile() {
  return profile;
}

function getAuthenticationURL() {
  return (
    "https://" +
    auth0Domain +
    "/authorize?" +
    "scope=openid profile offline_access&" +
    "response_type=code&" +
    "client_id=" +
    clientId +
    "&" +
    "redirect_uri=" +
    redirectUri
  );
}

async function refreshTokens() {
  const refreshToken = await keytar.getPassword(keytarService, keytarAccount);

  if (refreshToken) {
    const refreshOptions = {
      method: 'POST',
      url: `https://${auth0Domain}/oauth/token`,
      headers: {'content-type': 'application/json'},
      data: {
        grant_type: 'refresh_token',
        client_id: clientId,
        refresh_token: refreshToken,
      }
    };

    try {
      const response = await axios(refreshOptions);

      accessToken = response.data.access_token;
      profile = jwtDecode(response.data.id_token);
    } catch (error) {
      await logout();

      throw error;
    }
  } else {
    throw new Error("No available refresh token.");
  }
}

async function loadTokens(callbackURL) {
  const urlParts = url.parse(callbackURL, true);
  const query = urlParts.query;

  const exchangeOptions = {
    'grant_type': 'authorization_code',
    'client_id': clientId,
    'code': query.code,
    'redirect_uri': redirectUri,
  };

  const options = {
    method: 'POST',
    url: `https://${auth0Domain}/oauth/token`,
    headers: {
      'content-type': 'application/json'
    },
    data: JSON.stringify(exchangeOptions),
  };

  try {
    const response = await axios(options);

    accessToken = response.data.access_token;
    profile = jwtDecode(response.data.id_token);
    refreshToken = response.data.refresh_token;

    if (refreshToken) {
      await keytar.setPassword(keytarService, keytarAccount, refreshToken);
    }
  } catch (error) {
    await logout();

    throw error;
  }
}

async function logout() {
  await keytar.deletePassword(keytarService, keytarAccount);
  accessToken = null;
  profile = null;
  refreshToken = null;
}

function getLogOutUrl() {
  return `https://${auth0Domain}/v2/logout`;
}

module.exports = {
  getAccessToken,
  getAuthenticationURL,
  getLogOutUrl,
  getProfile,
  loadTokens,
  logout,
  refreshTokens,
};
const { BrowserWindow } = require('electron');
const authService = require('../services/auth-service');
const createAppWindow = require('../main/app-process');

let win = null;

function createAuthWindow() {
  destroyAuthWin();

  win = new BrowserWindow({
    width: 1000,
    height: 600,
    webPreferences: {
      nodeIntegration: false,
      enableRemoteModule: false
    }
  });

  win.loadURL(authService.getAuthenticationURL());

  const {session: {webRequest}} = win.webContents;

  const filter = {
    urls: [
      'http://localhost/callback*'
    ]
  };

  webRequest.onBeforeRequest(filter, async ({url}) => {
    await authService.loadTokens(url);
    createAppWindow();
    return destroyAuthWin();
  });

  win.on('authenticated', () => {
    destroyAuthWin();
  });

  win.on('closed', () => {
    win = null;
  });
}

function destroyAuthWin() {
  if (!win) return;
  win.close();
  win = null;
}

function createLogoutWindow() {
  const logoutWindow = new BrowserWindow({
    show: false,
  });

  logoutWindow.loadURL(authService.getLogOutUrl());

  logoutWindow.on('ready-to-show', async () => {
    await authService.logout();
    logoutWindow.close();
  });
}

module.exports = {
  createAuthWindow,
  createLogoutWindow,
};

Adding dynamic Data to Fortune Sheet React is retruning in correct result while logging the Workbook data

i am using Frotune Sheet to render my dynamic Excel data into the sheet below is my code .


import React, { useState, useEffect } from 'react';
import { Workbook } from "@fortune-sheet/react";
import "@fortune-sheet/react/dist/index.css";
import { data } from "./data";
import useConvertAlphabet from './convertAlphabet';

const Sheet = () => {
   Converted Cell is the hook that convert my data into expected workboot structure which [{ r: 0, c: 0, v: "nsssull" }] }]
    const { ConvertedCell } = useConvertAlphabet(data);
    const [workbookData, setWorkbookData] = useState(null);

    useEffect(() => {
        if (ConvertedCell) {
            setWorkbookData(ConvertedCell);
        }
    }, [ConvertedCell]);

    const settings = {
        data: [{ name: 'Sheet1', celldata: [{ r: 0, c: 0, v: "nsssull" }] }],
        onChange: (data) => { setWorkbookData(data) },
        lang: 'en',
        showToolbar: false,
        showSheetTabs: false,
        cellContextMenu: ["copy", "paste", "delete-row", "delete-column"],
        row: 50
    };

    console.log(workbookData, "workbookData");

    return (
        <div className='w-full h-full flex flex-col gap-2'>
            <Workbook {...settings} />
        </div>
    );
};

export default Sheet;
import { useEffect, useState } from "react"

 const useConvertAlphabet  = (data) => {

    const [cellData,setCellData] = useState(data);
    const [ConvertedCell,setConvertedCell] = useState([])


    const getColumnNumber = (column) => {
        const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        let colNumber = 0;
      
        // If the column reference is a single character, return its index
        if (column.length === 1) {
          return alphabet.indexOf(column.toUpperCase());
        }
      
        // For multi-character column references like "AA", "AB", etc.
        for (let i = 0; i < column.length; i++) {
          const char = column.charAt(i); // Get the current character
          const charIndex = alphabet.indexOf(char.toUpperCase()) + 1; // Get the index of the character in the alphabet
          colNumber = colNumber * 26 + charIndex; // Calculate the numeric value of the column
        }
      
        return colNumber - 1; // Adjusting to start from 0
      };


      useEffect(() => {
        const convertedData = cellData?.map((item, index) => {
            const col = getColumnNumber(item.column);
            return { r: item.rows, c: col, v: item.value };
        });

        setConvertedCell(convertedData);
    }, [cellData]);


 return {ConvertedCell}
}

export default useConvertAlphabet

The above is the custom hook for converting the alphabet Cell value to a numeric like A to 0 and and AA to 26 something like it

but the issue is when i try to log the workbook data it return some thing like in the Ss , Plz help
enter image description here