spinning wheel in react doesn’t stops on a specific position and also dosn’t gives the exact value where it stops

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

.App {
    background-image: url('./images//bg.webp');
    background-position: center;
    background-size: cover;
    object-fit: contain;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100vh;
    overflow: hidden;
}

.container {
    width: 500px;
    height: 500px;
    background-image: url('./images/wheel.webp');
    background-repeat: no-repeat;
    background-size: cover;
    border-radius: 50%;
    position: relative;
    overflow: hidden;
    transition: transform 5s; 
    transform-origin: center;
}

.container div {
    position: absolute;
    transform-origin: center;
    text-align: center;
    font-size: 20px;
    font-weight: bold;
    font-family: sans-serif;
    color: #fff;
    
}

.container .one {
    left: 37.2%;
    top: 5%;
    background-image: url('./images/star1.webp');
    object-fit: cover;
    background-size: cover;
    height: 24%;
    width: 24%;
    position: relative;
    border-radius: 50%;
}

.container .two {
    background-image: url('./images/star2.webp');
    /* background-repeat: no-repeat; */
    object-fit: cover;
    background-size: cover;
    height: 24%;
    width: 24%;
    position: relative;
    border-radius: 50%;
    left: 65%;
    top:-4%;
    /* transform: rotate(50deg); */
}
.container  h1{
    position: absolute;
    font-size: 1.2rem;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 50;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    gap: 15px;
    text-shadow: 0px 4px 0px darkred;  /* Dark red text shadow */

    /* height: auto; */
    /* width: 60%; */
}
.container h1 span {
    font-size: 1.5rem;
    position: fixed;
    top: 60%;
    font-weight: 800;
    /* text-shadow: 0px 4px 0px darkred; Dark red text shadow */
}
.container .three {
    background-image: url('./images/star1.webp');
    /* background-repeat: no-repeat; */
    object-fit: cover;
    background-size: cover;
    height: 24%;
    width: 24%;
    position: relative;
    border-radius: 50%;
    left: 68%;
    top:4%;
}

.container .four {
    background-image: url('./images/star2.webp');
    /* background-repeat: no-repeat; */
    object-fit: cover;
    background-size: cover;
    height: 24%;
    width: 24%;
    position: relative;
    border-radius: 50%;
    left:40%;
    top:-1%;
}

.container .five {
    background-image: url('./images/star1.webp');
    /* background-repeat: no-repeat; */
    object-fit: cover;
    background-size: cover;
    height: 24%;
    width: 24%;
    position: relative;
    border-radius: 50%;
    left:10.5%;
    top:-39.7%;
}

.container .six {
    background-image: url('./images/star1.webp');
    /* background-repeat: no-repeat; */
    object-fit: cover;
    background-size: cover;
    height: 24%;
    width: 24%;
    position: relative;
    border-radius: 50%;
    left:8.5%;
    top:-95.5%;
}

.arrow {
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    z-index: 50;
}

.arrow img {
    position: absolute;
    top: -40px;
    left:   -80px;
}

#spin {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 100px; 
    height: 100px; 
    display: flex; 
    align-items: center; 
    justify-content: center; 
    cursor: pointer;
    z-index: 100; 
  }
  
  #spin img {
    width: 100%; 
    height: auto; 
    pointer-events: none; 
  }
  


@media (max-width: 540px) {
    .container {
        width: 350px;
        height: 350px;
    }

    #spin {
        top: 52.5%;
        width: 70px;
        height: 70px;
    }

    .container div {
        font-size: 14px;
    }

    .arrow {
        height: 50px;
        width: 50px;
    }
}




.birds {
    position: absolute;
    display: flex;
    justify-content: space-between;
    align-items: center;
    top: 20%;
}

.birds img {
    width: 20%;
}



.stars {
    position: absolute;
    z-index: 50;
}

.stars .bird-1 {
    position: fixed;
    top: 0;
    left: 0;
    width: 10%;

}
.stars .bird-2 {
    position: fixed;
    bottom: 0;
    right: 0;
    width: 10%;
}

.design {
    position: absolute;
    z-index: 50;
}

.design img {
    position: fixed;
    bottom: -23%;
    left: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
import React, { useState, useRef, useEffect } from 'react';
import './App.css';
import bird1 from "./images/paret.webp";
import bird2 from "./images/paret2.webp";
import star1 from "./images/star1.webp";
import star2 from "./images/star2.webp";
import arrow from "./images/arrow.webp";
import spin from "./images/btn.png";
import PopUp from './components/PopUp';
import bg from "./images/bg3.webp";
import startSound from './audio/start.mp3';
import winSound from './audio/win.mp3';
import loseSound from "./audio/lose.mp3"
function App() {
  const [clicks, setClicks] = useState(0);
  const [rotation, setRotation] = useState(0);
  const [showPopUp, setShowPopUp] = useState(false);
  const [prices, setPrices] = useState({
    price1: 5,
    price2: 1568,
    price3: 1000,
    price4: 15,
    price5: 105,
    price6: 300,
  });
  const [winPrize, setWinPrize] = useState();

  const startAudioRef = useRef(null);
  const winAudioRef = useRef(null);
  const loseAudioRef = useRef(null)
  useEffect(() => {
    const popUpShown = localStorage.getItem('popUpShown') === 'true';
    const savedClicks = parseInt(localStorage.getItem('clicks'), 10) || 0;
    const savedWinPrize = localStorage.getItem('winPrize');
    setShowPopUp(popUpShown);
    setClicks(savedClicks);
    if (savedWinPrize) {
      setWinPrize(savedWinPrize);
    }
  }, []);

  const handleSpinClick = () => {
  if (clicks > 0) {
    return;
  }
  setClicks(1);
  localStorage.setItem('clicks', '1');

  // Assuming 0 degrees is the top of the wheel and segments are evenly distributed.
  const degreesPerSegment = 360 / 6;
  const offsetToCenterOfSegment = degreesPerSegment / 2;

  // Calculate a random segment to stop on, then adjust to the segment's center
  const chosenSegment = Math.floor(Math.random() * 6);
  const newRotation = rotation + 360 * 5 + (chosenSegment * degreesPerSegment) + offsetToCenterOfSegment;

  setRotation(newRotation);
  startAudioRef.current.play();

  setTimeout(() => {
    const finalRotation = newRotation % 360;
    console.log(`Final Rotation: ${finalRotation}`);
    const winningSector = Math.floor((finalRotation + degreesPerSegment / 2) % 360 / degreesPerSegment);
    console.log(`Winning Sector: ${winningSector}`);
    const winningPrice = prices[`price${winningSector + 1}`];
    console.log(`Winning Price: ${winningPrice}`);

    localStorage.setItem('winPrize', winningPrice);
    setWinPrize(winningPrice);
    winningPrice === "Empty" ? loseAudioRef.current.play() : winAudioRef.current.play();

    localStorage.setItem('popUpShown', 'true');
    setShowPopUp(true);
  }, 5000);
};

  

  const handleClaimBonus = () => {
    setShowPopUp(true);
    setClicks(1);
    localStorage.setItem('popUpShown', 'true');
    localStorage.setItem('clicks', '1');
    // localStorage.removeItem('winPrize');
    // setWinPrize(undefined);
  };

  const handleCloseBtn = () => {
    setShowPopUp(false);
    setClicks(0);
    localStorage.setItem('popUpShown', 'false');
    localStorage.setItem('clicks', '0');
    localStorage.removeItem('winPrize');
    setWinPrize(undefined);
  }


  return (
    <div className="App">
      <div id="spin" onClick={handleSpinClick}>
        <img src={spin} alt="Spin" />
      </div>
      <div className='birds'>
        <img className='bird-1' src={bird1} alt="Bird 1" />
        <img className='bird-2' src={bird2} alt="Bird 2" />
      </div>
      <div className='stars'>
        <img className='bird-1' src={star1} alt="Bird 1" />
        <img className='bird-2' src={star2} alt="Bird 2" />
      </div>
      <div className='design'>
        <img src={bg} width={500} height={500} alt="Background" />
      </div>
      <span className="arrow">
        <img src={arrow} alt="Arrow" />
      </span>
      <div className="container" style={{ transform: `rotate(${rotation}deg)` }}>
        <div className="one">
          <h1>FS <span>{prices.price1}</span></h1>
        </div>
        <div className="two">
          <h1>R$<span>{prices.price2}</span></h1>
        </div>
        <div className="three">
          <h1>R$<span>{prices.price3}</span></h1>
        </div>
        <div className="four">
          <h1>R$<span>{prices.price4}</span></h1>
        </div>
        <div className="five">
          <h1>R$<span>{prices.price5}</span></h1>
        </div>
        <div className="six">
          <h1>R$<span>{prices.price6}</span></h1>
        </div>
      </div>
      {showPopUp && clicks > 0 && (
        <PopUp winPrize={winPrize} onClaimBonus={handleClaimBonus} handleCloseBtn={handleCloseBtn} />
      )}

      <audio ref={startAudioRef} src={startSound} preload="auto"></audio>
      <audio ref={winAudioRef} src={winSound} preload="auto"></audio>
      <audio ref={loseAudioRef} src={loseSound} preload="auto"></audio>
    </div>
  );
}

export default App;

Is there any way to iterate on two linkedlist at the same time

I am trying find a way to loop through on multiple linkedlist but in this code it gives an error on l2 = l2.next

Is there any other way to find the longer linkedlist and loop through for both of them? I am not even sure if it is possible

enter image description here

const addTwoNumbers = function (l1, l2) {
    let sumList = null;

    while(l1){
        const tmp1 = l1
        l1 = l1.next;
        tmp1.next =null;

        const tmp2 = l2
        l2 = l2.next;
        tmp2.next = null;

    console.log('tmp',tmp1)
    }
};

Discord.js RangeError: Maximum call stack size exceeded

The pingChart file is create on the /, but this error appears. I type /ping in Discord and this happens:

C:UsersErenayDesktopbotnode_modulesdiscord.jssrcutilUtil.js:21
.filter(key => !key.startsWith(‘_’))
^

RangeError: Maximum call stack size exceeded

/commands/ping.js

const {
  Discord,
  EmbedBuilder,
  SlashCommandBuilder,
  AttachmentBuilder
} = require('discord.js')
const {
  updatePingChart,
  canvas
} = require("../helpers/chart");

function wait(time) {
  return new Promise(resolve => setTimeout(resolve, time));
}
const fs = require("fs")
module.exports = {
  slash: true,
  cooldown: 1200,

  data: new SlashCommandBuilder()
    .setName('ping')
    .setDescription('Shows bot ping.'),

  async execute(client, interaction) {

    let pinge = '<:Bot:1065675104027148338>'
    let bote = '<:Ping:1065675122683412481>'
    let messageping = new Date().getTime() - interaction.createdTimestamp
    let ping = await client.ws.ping
    
    await updatePingChart(ping)
    
    const stream = canvas.createPNGStream();
    const attachment = new AttachmentBuilder(stream, {
      name: 'ping.png'
    });
    
    const embed = new EmbedBuilder()
      .addFields({
        name: `${bote} **Bot ping:**`,
        value: ``${ping}ms``
      }, {
        name: `${pinge} **Message ping:**`,
        value: ``${messageping}ms``
      })
      .setColor(`Gold`)
      
    await interaction.reply({
      embeds: ,
      attachments: [attachment]
    })
    
    wait(5000)
    
    const fileName = 'pingChart.png';
    fs.unlinkSync(fileName);
  }
}

/helpers/chart.js

const db = require("croxydb")
const { createCanvas } = require("canvas")
const width2 = 800;
const height2 = 400;
const Chart = require("chart.js/auto")

function wait(time) {
  return new Promise(resolve => setTimeout(resolve, time));
}

const fs = require("fs")
let myChart;
const canvas = createCanvas(width2, height2);
const ctx2 = canvas.getContext('2d');

async function updatePingChart(url) {
  if (myChart) {
    myChart.destroy();
  }

  const uptimeLinks = db.get("Ping") || {};
  console.log(uptimeLinks);
  const labels = uptimeLinks[0].label
  const pinkg = uptimeLinks[0].ping
  console.log(labels, pinkg);
  
  const configuration = {
    type: 'line',
    data: {
      labels: labels,
      datasets: [{
        label: 'Ping (ms)',
        backgroundColor: 'rgba(75, 192, 192, 0.2)',
        borderColor: 'rgba(75, 192, 192, 1)',
        data: pinkg,
        yAxisID: 'y-axis-1',
      }]
    },
    options: {
      scales: {
        x: [{
          type: 'linear',
          position: 'bottom',
          ticks: {
            callback: function(value, index) {
              if (index % 12 === 0 && labels[index / 12]) {
                return labels[index / 12];
              } else {
                return '';
              }
            }
          }
        }],
        y: [{
            type: 'linear',
            display: true,
            position: 'left',
            id: 'y-axis-1',
          },
          {
            type: 'linear',
            display: true,
            position: 'right',
            id: 'y-axis-2',
            ticks: {
              max: 1,
              min: 0,
              stepSize: 1,
              callback: function(value) {
                return value === 1 ? 'Up' : 'Down';
              }
            }
          },
        ]
      }
    }
  };

  myChart = new Chart(ctx2, configuration);

  const out = fs.createWriteStream('pingChart.png');
  const stream = canvas.createPNGStream();

  return new Promise((resolve, reject) => {
    stream.pipe(out);
    out.on('finish', () => {
      resolve('The chart image was saved.');
    });
    out.on('error', (err) => {
      reject(err);
    });
  });
}

module.exports = {
  updatePingChart: updatePingChart,
  canvas: canvas
};

React front-end startup failure error ‘umi’ is not an internal or external command or a runnable program

Several attempts were made to reinstall the dependency, but after the installation, it was not allowed successfully and appeared as follows( 尝试多次重新安装依赖 但是安装之后还是没有成功允许且出现如下) enter image description here

0 info it worked if it ends with ok
1 verbose cli [
1 verbose cli   'C:\Program Files\nodejs\node.exe',
1 verbose cli   'C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js',
1 verbose cli   'run',
1 verbose cli   'start'
1 verbose cli ]
2 info using [email protected]
3 info using [email protected]
4 verbose run-script [ 'prestart', 'start', 'poststart' ]
5 info lifecycle [email protected]~prestart: [email protected]
6 info lifecycle [email protected]~start: [email protected]
7 verbose lifecycle [email protected]~start: unsafe-perm in lifecycle true
8 verbose lifecycle [email protected]~start: PATH: C:Users27632AppDataRoamingnvmv14.17.0node_modulesnpmnode_modulesnpm-lifecyclenode-gyp-bin;E:codegitlabcodeing3.12zlink-frontnode_modules.bin;D:appWINDOWS.X64_193000_db_homebin;D:toolsVmbin;C:Program Files (x86)Common FilesOracleJavajavapath;C:WINDOWSsystem32;C:WINDOWS;C:WINDOWSSystem32Wbem;C:WINDOWSSystem32WindowsPowerShellv1.0;C:WINDOWSSystem32OpenSSH;C:Program FilesTortoiseGitbin;D:toolsGitcmd;C:Program FilesJavajdk1.8.0_331bin;D:toolsXftp;D:toolsXshell;D:toolsMAVENapache-maven-3.8.8-binapache-maven-3.8.8bin;C:Users27632AppDataRoamingnvm;C:Program Filesnodejs;D:tools微信web开发者工具dll;D:toolsapache-tomcat-9.0.68-windows-x64apache-tomcat-9.0.68bin;C:Program FilesPandocpandoc.exe;C:Program FilesInkscapebininkview.exe;D:toolsGobin;C:Program FilesAzure Data Studiobin;C:Users27632AppDataLocalMicrosoftWindowsApps;D:toolsMicrosoft VS Codebin;C:Users27632AppDataRoamingnvm;C:Program Filesnodejs;C:texlive2023binwindows;C:Users27632gobin;C:Program FilesAzure Data Studiobin
9 verbose lifecycle [email protected]~start: CWD: E:codegitlabcodeing3.12zlink-front
10 silly lifecycle [email protected]~start: Args: [ '/d /s /c', 'umi dev' ]
11 silly lifecycle [email protected]~start: Returned: code: 1  signal: null
12 info lifecycle [email protected]~start: Failed to exec start script
13 verbose stack Error: [email protected] start: `umi dev`
13 verbose stack Exit status 1
13 verbose stack     at EventEmitter.<anonymous> (C:Users27632AppDataRoamingnvmv14.17.0node_modulesnpmnode_modulesnpm-lifecycleindex.js:332:16)
13 verbose stack     at EventEmitter.emit (events.js:376:20)
13 verbose stack     at ChildProcess.<anonymous> (C:Users27632AppDataRoamingnvmv14.17.0node_modulesnpmnode_modulesnpm-lifecyclelibspawn.js:55:14)
13 verbose stack     at ChildProcess.emit (events.js:376:20)
13 verbose stack     at maybeClose (internal/child_process.js:1055:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:288:5)
14 verbose pkgid [email protected]
15 verbose cwd E:codegitlabcodeing3.12zlink-front
16 verbose Windows_NT 10.0.22631
17 verbose argv "C:\Program Files\nodejs\node.exe" "C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js" "run" "start"
18 verbose node v14.17.0
19 verbose npm  v6.14.13
20 error code ELIFECYCLE
21 error errno 1
22 error [email protected] start: `umi dev`
22 error Exit status 1
23 error Failed at the [email protected] start script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 1, true ]

Unable to Access Javascript Variable in R Shiny Application

Trying to under stand what this code is not working, keep in mind I am not even a JS novice. The observeEvent does not even get triggered.

shinyjs::runjs(
‘var metadata = “{“id”:[115],”email”:[“[email protected]”]}”;
Shiny.setInputValue(“InputName”, metadata)’
)

observeEvent(input$InputName, {
ShinyVariable <- fromJSON(input$InputName)
updateF7Button(inputId = ‘Button’, label = ‘Success’)
updateF7TextArea(inputId = ‘TextArea’, value = ShinyVariable$email)
})

Load data from file and create html elements in electron js

What is expected:

Coming from Flask-JS I had a web app kind of thing that would read from a JSON file and create html elements based on that all by Jinja2 and that data would come from python (Everything Normal!).

How do I perform this in Electron?

I have tried the documentation (may be I am lacking there to understand) but did not work. I went to well known AIs and they give me some ipcMain and ipcRenderer option but again I don’t know it is my system or luck or else they throw TypeError.

I am new to Electron and whole Node.js world, I know survival level of JS.

STRAPI : it is not building admin panel always showing this error [closed]

││ TypeError: Cannot destructure property ‘client’ of
‘db.config.connection’ as it is undefined. ││
at getDialect
││
(C:UsershpOneDriveDesktopCrudcrrud_Bbacjnode_modules@strapidatabasedistindex.js:1014:11)
││ at new Database
││
(C:UsershpOneDriveDesktopCrudcrrud_Bbacjnode_modules@strapidatabasedistindex.js:6114:20)
││ at Database.init
││
(C:UsershpOneDriveDesktopCrudcrrud_Bbacjnode_modules@strapidatabasedistindex.js:6100:16)
││ at Strapi.bootstrap
││
(C:UsershpOneDriveDesktopCrudcrrud_Bbacjnode_modules@strapistrapidistStrapi.js:371:39)
││ at Strapi.load
││
(C:UsershpOneDriveDesktopCrudcrrud_Bbacjnode_modules@strapistrapidistStrapi.js:425:16)
││ at async Object.develop
(C:UsershpOneDriveDesktopCrudcrrud_Bbacjnode_modules@strapiadmindist_chunks
││ index-ffd2f664.js:1245:28)
││ at async develop
(C:UsershpOneDriveDesktopCrudcrrud_Bbacjnode_modules@strapiadmindist_chunksdevelop
││ -da585b1e.js:52:5)
││ at async Command.parseAsync
││
(C:UsershpOneDriveDesktopCrudcrrud_Bbacjnode_modulescommanderlibcommand.js:923:5)
││ at async Module.runStrapiCommand
││
(C:UsershpOneDriveDesktopCrudcrrud_Bbacjnode_modules@strapistrapidistcommandsindex.js:124:3)
││

i want to start strapi always throwing is error.,,,know how to solve

Is there a more efficient way to match keys between an object array and a map in JavaScript?

I have an array of objects, arr1, where each object has multiple properties. I also have a map, map2, where the keys are strings and the values can be of any type. My goal is to find the matching keys between arr1 and map2.

Here is an example of the code I currently have:

// Assume arr1 is an array of objects, each object having multiple properties
var arr1 = [{Alice: 1, Bob: 2}, {Alice: 2,Charlie: 3, David: 4}, {Charlie: 4,Eve: 5, Frank: 6}];
// Assume map2 is a map, with keys as strings and values of any type
var map2= new Map();
map2.set("Alice", 1);
map2.set("David", 2);
map2.set("Eve", 3);

// Original nested for loop
for (var i = 0; i < arr1.length; i++) {
  for (var [key, value] of map2) {
    for (var name in arr1[i]) {
      if (arr1[i][name] == key) {
        console.log("Matching key: " + key);
      }
    }
  }
}

// Optimized nested for loop
for (var i = 0; i < arr1.length; i++) {
  for (var name in arr1[i]) {
    if (map2.has(name)) {
      console.log("Matching key: " + name);
    }
  }
}

The code works as expected, but I wonder if any further optimizations can be done to improve its efficiency. Currently, I iterate over arr1 and check every property of every object against the key in map2. If a match is found, the matching key is recorded. However, the large amount of arr1 data and the number of map keys are inefficient, and I do not know if there is a better way.

Is there a more efficient approach to achieve the same result? Any suggestions or insights would be greatly appreciated. Thank you!

How to make the excel sheet download or set process.env.HOME environment in render?

I have a workbook saved and I am updating information according to the data available. I am able to make changes on the workbook but I am unable to download it.
OR HOW CAN WE SET process.env.HOME === C:/Users/${Username}.???
please find the code below:

//invoice.jsx
import Wrapper from '../assets/wrappers/DashboardFormPage';
import { FormRow, FormRowSelect, SubmitBtn } from '../components';
import { toast } from 'react-toastify';
import customFetch from '../../utils/customFetch.js';
import { useLoaderData, Form, redirect, useActionData } from 'react-router-dom';
import { CUSTOMER_CODE } from '../../../utils/constants.js';

export const loader = async () => {
  try {
    const response = await customFetch.get('/users/admin/app-stats');
    return response.data;
  } catch (error) {
    toast.error('You are not authorized to view this page');
    return redirect('/dashboard');
  }
};

export const action = async ({ request }) => {
  const formData = await request.formData();
  const data = Object.fromEntries(formData);
  // console.log(data);
  try {
    await customFetch.post('/users/admin/invoice', data);
    toast.success('Invoice Downloaded');
    return redirect('/dashboard/invoice');
  } catch (error) {
    toast.error(error?.response?.data?.msg);
    return error;
  }
};

const Invoice = () => {
  return (
    <Wrapper>
      <Form className="form" method="post">
        <h4 className="form-title">Generate Invoice</h4>
        <div className="form-center">
          <FormRow
            type="text"
            labelText="Invoice Number"
            name="invoiceNumber"
          />
          <FormRow type="date" labelText="Start Date" name="startDate" />
          <FormRow type="date" labelText="End Date" name="endDate" />
          <FormRowSelect
            labelText="Customer Code"
            name="customer"
            list={Object.values(CUSTOMER_CODE)}
          />
          <SubmitBtn formBtn />
        </div>
      </Form>
    </Wrapper>
  );
};
export default Invoice;

-------------------------------------------------------------------------------------------------
//userController.js

export const downloadInvoice = async (req, res) => {
  const data = req.body;
  const startDateObject = data.startDate === '' ? '' : new Date(data.startDate);
  const endDateObject = data.endDate === '' ? '' : new Date(data.endDate);
  if (data.invoiceNumber === '') {
    res
      .status(StatusCodes.BAD_REQUEST)
      .json({ msg: 'Please provide Invoice Number' });
  } else if (data.invoiceNumber.length < 10) {
    res.status(StatusCodes.NOT_FOUND).json({ msg: 'Incorrect Invoice Number' });
  } else {
    const agr = data.invoiceNumber.slice(-4);
    try {
      switch (data.customer) {
        //ASP INVOICE CREATION
        case 'ASP':
          if (startDateObject === '' || endDateObject === '') {
            res
              .status(StatusCodes.BAD_REQUEST)
              .json({ msg: 'Please fill both dates' });
            return;
          } else {
            const graphicOrAspire = data.invoiceNumber[3];
            let aspTripData = [];
            if (graphicOrAspire === 'M') {
              aspTripData = await Trip.find({
                customer: data.customer,
                tripDate: {
                  $gte: startDateObject,
                  $lte: endDateObject,
                },
                oceanLine: OCEAN_LINE.DRYVAN,
                loadCode: {
                  $ne: LOAD_CODE.ASPGRAPHIC,
                },
              });
            } else if (graphicOrAspire === 'G') {
              aspTripData = await Trip.find({
                customer: data.customer,
                tripDate: {
                  $gte: startDateObject,
                  $lte: endDateObject,
                },
                oceanLine: OCEAN_LINE.DRYVAN,
                loadCode: LOAD_CODE.ASPGRAPHIC,
              });
            }
            const totalTrips = aspTripData.length;
            if (totalTrips === 0) {
              res
                .status(StatusCodes.NOT_FOUND)
                .json({ msg: 'No trips found between given date range.' });
            } else {
              ///////////////////////////////////////////////////////////
              const workbook = new ExcelJS.Workbook();
              await workbook.xlsx.readFile(
                path.join(__dirname, '../public/aspTemplate.xlsx')
              );

              // Get the first worksheet
              const worksheet = workbook.getWorksheet('Sheet1');

              // Add data to specific cells
              //invoice number
              worksheet.getCell('I1').value = data.invoiceNumber;

              //invoice date
              const currentDate = new Date();
              worksheet.getCell('I2').value = currentDate.toLocaleDateString();

              //week number
              const d = new Date(startDateObject);
              d.setHours(0, 0, 0, 0);
              d.setDate(d.getDate() + 4 - ((d.getDay() + 6) % 6)); // Make the adjustment more dynamic
              const yearStart = new Date(d.getFullYear(), 0, 1);
              const weekNumber = Math.ceil(
                ((d - yearStart) / 86400000 + 1) / 7
              );

              worksheet.getCell('H9').value = `WEEK ${weekNumber}`;

              //from
              worksheet.getCell('D16').value = startDateObject;

              //to
              worksheet.getCell('E16').value = endDateObject;

              //Total trips
              worksheet.getCell('G16').value = totalTrips;

              //rate
              worksheet.getCell('H16').value = ASP_CHARGES.ASPWHOUT_BASE_AMOUNT;

//I HAVE ISSUE HERE!!!!!!
              const outputFilePath = path.join(
                process.env.HOME || process.env.USERPROFILE,
                'Invoices',
                'ASP',
                `${data.invoiceNumber}.xlsx`
              );
              console.log(`1: ${process.env.HOME}`);
              console.log(`2: ${process.env.USERPROFILE}`);
              console.log(`PATH: ${outputFilePath}`);
              await workbook.xlsx.writeFile(outputFilePath);
              //////////////////////////////////////////////////////////
// I AM ABLE TO SAVE CHANGES WHEN I RUN IT LOCALLY, BUT AFTER DEPLOYING IT... I NEED TO DOWNLOAD THIS FILE.
//PLEASE SUGGEST HOW CAN I DOWNLOAD THIS FILE ON BROWSER.

              res
                .status(StatusCodes.OK)
                .json({ aspTripData, msg: 'Aspire Invoice Downloaded' });
            }
          }
          break;
        default:
          break;
      }
    } catch (error) {
      console.log(error);
      res.status(StatusCodes.NOT_FOUND).json({ msg: 'Something went wrong' });
    }
  }
};

I tried using XLSX… by creating a new workbook and then trying to download it… but unfortunately unable to do so.

please help!

How to change array of object to new array of object with conditions using javascript

I have array of object and need to modify and return new array of object

For the below array of object, i need to return new array of object with label, value and children props using javascript.

should change every property value to label, value and if property value is array then embed in children prop as shown in expected output

var arrobj = [
  {
    title: "Test A",
    group: ['Travel', 'Health'],
    details: {
      'Travel': ['domestic', 'international'],
      'Health': ['hospital']
   }
  },
  {
    title: "Test B",
    group: ['Finance'],
    details: {
      'Finance': ['family']
   }
  }
]
Expected Output:

[
 {
   value: "Test A",
   label: "Test A",
   children: [
     {
       value: 'Travel', label: 'Travel',
       children: [
        { value: 'domestic', label: 'domestic'},
        { value: 'international', label: 'international'},
      ]
     },
     {
       value: 'Health', label: 'Health',
       children: [
        { value: 'hospital', label: 'hospital'},
      ]
     }  
   ]
 },
 {
   value: "Test B",
   label: "Test B",
   children: [
      { 
        value: 'Finance', label: 'Finance',
        children: [
          { value: 'family', label: 'family'},
        ]
      }
   ]
 }

]

Tried

arrrobj.map(e=> {
  label: e.title,  
  value: e.title,
  children: [
     {
       label: e.group;
       value: e.group;
       children: e.details.Travel
     }
   ]
})

Tuning behaviour of Luxon toRelative, around year cross-over?

We are using Luxon in a Javascript frontend project, and are running into a small issue where a date 20 December 2023, is showing as “last year” when using toRelative() on
11 January 2024.

Our expectation is that “last year” would be used only if the date range is sufficiently large (maybe 10 months or 365 days?) and anything below that would be in the form of “last month ago” or “2 months ago”.

The toRelative() function does support a unit option, which can take an array and while we could provide ["months", "days", "hours", "minutes", "seconds"], this would remove the use of year from relative time.

Is there any way to get Luxon to provide the behaviour we are looking for and if so, can you share an example.

How to make an alert show up when the page won’t load AND it’s been 7 seconds

How to make an alert show up when the page won’t load AND it’s been 7 seconds.

This is the expected behavior and I would like the alert to explain to the user why this is happening. I see this code written for the time but not for the “page not loading” part.

I tried this code but I can’t find information on if both the page didn’t load AND it’s been 7 seconds.

window.onload = setTimeout(function(){
        alert('Looks like this page hasn't loaded yet, it could be because...);
      window.location = 'EXPLANATION PAGE';
    }, 7000);

i want to disable options that are not matched with the data from database

i have this list of days of doctor’s practice days in database

<select class="form-control select2" name="hari_praktek" style="width: 100%;">
     <option value="-" selected="true" disabled="disabled">Pilih Hari Praktek</option>
     <option value="Monday">Senin</option>
     <option value="Tuesday">Selasa</option>
     <option value="Wednesday">Rabu</option>
     <option value="Thursday">Kamis</option>
     <option value="Friday">Jumat</option>
     <option value="Satuday">Sabtu</option>
     <option value="Sunday">Minggu</option>
 </select>

and i plan to create consultation form for the patient. i want that whenever i choose a doctor. the dropdown list that i’m gonna make will show days & dates which only days that are matched with doctor’s practice day that are not disabled, others are disabled. i will use ajax and i want to know how i make the fetch file that takes practice’s day from database and compare them with the days from date function. thank you in advance.

Convert mouse coordinate into game grid coordinate

In my game I tried making a converter from my mouse click coordinates to real game coordinates on a 2d grid.
The problem I’m facing is that it gets inaccurate the further away it is from the center camera, also I’m not sure how to incorporate my camera zoom with it. Cause I can get more F.O.V. or less by zooming in and out.
camX and camY is the center point to where I’m spectating on the grid and i have a certain F.O.V. within where I’m spectating (screen width, screen height).

 function mouseXY(n,camX,camY){
// idk how to incorporate zoomX and zoomY
const c = canvas.getBoundingClientRect();
const mouseX = n.clientX - c.left;
const mouseY = n.clientY - c.top;
const offsetX = mouseX - c.width / 2;
const offsetY = mouseY - c.height / 2;
const realGameX = camX + offsetX;
const realGameY = camY + offsetY;
return {x: realGameX, y: realGameY}

/*
accurate when clicking close to camX and camY gets more inaccurate further away from center     point.
it projects it too far from center point and to where my mouse is but in the right direction.
*/
    }

trying to understand the use of libraries and when to include them

I’m new and I have some questions.
The queries are for each type of graph.

If I wanted to have all the functionalities of each type of graph and load them, how do I do it without having to include the huge list of libraries?

Are there some that include everything?

If I wanted to mix the types of graphs on the same page, for example For example, a normal graph, a stock graph, a map, is it possible?

Are there conflicts between the libraries?

How can I know which ones cause conflict?

I would like to be able to load the smallest number of libraries and have all the functionalities.

thank you.

load a huge list of js libraries. The idea is to have them available to use. I know what they will tell me, you only load what you need, but I explicitly want to know how to load them all without literally listing the gigantic list of js that there is.