Spotify API Endpoint for “Add Item to Playback Queue” returns CORS error

I have a simple React app that displays the current song and allows users to add songs to the queue.
This is my code for adding the song to the queue:

export const addToQueue = async () => {
  const { access_token } = await getAccessToken(
    client_id,
    client_secret,
    refresh_token
  );

  // hardcoded the song for testing 
  let url = QUEUE_ENDPOINT + "?uri=spotify%3Atrack%" + "4iV5W9uYEdYUVa79Axb7Rh" + "&device_id=cb9d6538382380f513e2036b145dcab303b7b156";
  return fetch(url, {
    headers: {
      "Content-Type": 'application/json',
      Authorization: `Bearer ${access_token}`,
    },
    method:"POST"
  });

But I get the following error:

Access to fetch at ‘https://api.spotify.com/v1/me/player/queue?uri=spotify%3Atrack%4iV5W9uYEdYUVa79Axb7Rh&device_id=cb9d6538382380f513e2036b145dcab303b7b156’ from origin ‘http://localhost:8080’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.

Does anyone have any ideas on how to fix this?

Handling Multiple Timezones in Laravel for Shared Calendar

I’m working on building a shared calendar feature in Laravel where users can create events. Each user has their own timezone, and I want to store events in the database based on the user’s timezone. When displaying the calendar to other users, I’d like it to adjust to their timezone.

I’m planning to use JavaScript on the frontend to handle the user’s current timezone. Any suggestions on how I can implement this in Laravel? How do I store and retrieve events considering different timezones? Any advice or code snippets would be greatly appreciated.

Thanks in advance

Discrepancy when rounding the answer of a division where the answer is .5 remainder [duplicate]

I have a script removing the remainder of a value. But due to a difference in the way JS rounds the decimal places the result is incorrect.
I have since changed the script to use Math.floor() which returns the desired result but would still like an explanation as to why this is happening.

Is this issue the same as what is discussed in this thread:
Rounding up or down when 0.5

The equation I am using is
(138 / 54 ) – ( ( 138 % 54 ) / 54 )

When done in a calculator this returns 2
but through JS is returning 1.9999999999999998

When broken down
(138 / 54 )
returns 2.5555555555555554

( ( 138 % 54 ) / 54 )
returns 0.5555555555555556

ExcelJs not writing to excel

I’m having an issue with ExcelJS, here is my code:

ipcMain.on('sendTimeData', async (event, { username, client, activity, startTime, finishTime }) => { try { const workbook = new ExcelJS.Workbook(); await workbook.xlsx.readFile('excel.xlsx');
    let worksheet = workbook.getWorksheet(username);
    
    
    if (!worksheet) {
      worksheet = workbook.addWorksheet(username);
     
      worksheet.columns = [
        { header: 'Day', key: 'Day', width: 10 },
        { header: 'Starting_time', key: 'Starting_time', width: 18 },
        { header: 'Finishing_time', key: 'Finishing_time', width: 18 },
        { header: 'Client', key: 'Client', width: 15 },
        { header: 'Activity', key: 'Activity', width: 30 },
        { header: 'User', key: 'User', width: 15 },
      ];
    }
    
    
  
    worksheet.addRow({
      Day: startTime.toString(),
      Starting_time: startTime.toString(),
      Finishing_time: finishTime.toString(),
      Client: client,
      Activity: activity,
      User: username,
    });
    
    await workbook.xlsx.writeFile('excel.xlsx');
    console.log('Data added to Excel file.');
    } catch (error) { console.error('Error:', error); event.reply('sendTimeDataError', error.message); }); 

I want to add all the the variables definied like Day, Starting_time … etc.
So it even creates a new worksheet if a user doesn’t exist but my code doesn’t add anything. I have preformatted as all the headers as a table just like referenced, but it never adds a row. Please assist.

timeout when trying to scrape with puppeteer

I’m trying to run this code, but it keeps me sending a timeout error. Wonder what the problem is. Tried already to set Page.setDefaultTimeout(0) but it shows that it exceeds this default timeout(30000ms if I’m not mistaken). Now I’m trying with waitForSelector to click on it but it keeps failing. Here is the code. I’m using a fake url for posting here, but the element exists:

import { ScrapperContract, Common } from "@sssss/rpacore";
import { saveToCSV } from "@ssss/rpacore/dist/common/Files";
import { makeName, stripTags } from "@ssss/rpacore/dist/common/string";
import { delay } from "@sssss/rpacore/dist/common/timer";
import { PageResult } from "@ssss/rpacore/dist/types";
import { SearchParams } from "@ssss/rpacore/dist/types/SearchParams";
import { SearchResult } from "@ssss/rpacore/dist/types/SearchResult";
import PageDetailCase from "./usecase/PageDetailCase";
import { Searching } from "./usecase/SearchingCase";

export class MainApplication implements ScrapperContract {
  readonly name = "ssss";
  readonly url = "https://www.goveeo.br/sssss/pt-br/assuntos/noticias?form.submitted=1&";

  static browser?: any;

  async open(params: {[key:string]:any}) {
    MainApplication.browser = await Common.Browser.initialize(params);
  }
  async close() {
    await MainApplication.browser.close();
     
  }

  async search(params: SearchParams): Promise<SearchResult> {
    return new Promise(async (resolve) => {
      const browser = MainApplication.browser;
      
  
      const url = `${this.url}texto=${params.query}&dt_inicio=01/03/2022&dt_fim=21/06/2022&categoria=&b_size=20`
      console.log(`scrapper ${url}`);
      const page = await browser.newPage();
      await page.waitForSelector('body');
      await page.click('body');
      await page.waitForSelector('body > div.dsgov > div > div > div > div > button.br-button secondary small btn-accept');
      await page.click('body > div.dsgov > div > div > div > div > button.br-button secondary small btn-accep');
      const items = await Searching.execute(page);
      resolve({items, page, query: params.query});
    });
  }
  toPage({ items, page, query }: SearchResult): Promise<PageResult|any> {
    return new Promise(async (resolve) => {
      const listOfData: any[] = [];
      if (items.length > 0) {
        for (const i in items) {
          await delay(500);
          const row = items[i];
          await page?.goto(row.link);
          const onPage = await PageDetailCase.execute(page);
          listOfData.push({ ...row, ...onPage });
        }
      }
      resolve({ items: listOfData, page, query });
    });
  }
  toSaveFile({ items, query }: PageResult | any): Promise<any> {
    return new Promise(async (resolve) => {
      if (items.length > 0) {
        await saveToCSV(
          items.map((row: any) => {
            row.titulo = stripTags(row.titulo);
            row.ementa = String(row.ementa).replace(/s+/gi, " ");
            row.integra = String(row.integra).replace(/s+/gi, " ");
            return row;
          }),
          `./csv/${makeName(query)}`
        );
      }
      resolve(true);
    });
  }
}

it sends this error:

/home/yyy/rpas/sss/s25-sss-search/node_modules/puppeteer-core/src/common/WaitTask.ts:92
      this.#timeoutError = new TimeoutError(
                           ^
TimeoutError: Waiting for selector `body > div.dsgov > div > div > div > div > button.br-button secondary small btn-accept` failed: Waiting failed: 30000ms exceeded
    at new WaitTask (/home/yyy/rpas/ssss/s25-sssss-search/node_modules/puppeteer-core/src/common/WaitTask.ts:92:28)
    at IsolatedWorld.waitForFunction (/home/ssss/rpas/ssss/s25-ssss-search/node_modules/puppeteer-core/src/api/Realm.ts:84:22)
    at Function.waitFor (/home/ssss/rpas/sssss/s25-ssss-search/node_modules/puppeteer-core/src/common/QueryHandler.ts:169:50)
    at processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async CdpFrame.waitForSelector (/home/yyy/rpas/ssss/s25-sss-search/node_modules/puppeteer-core/src/api/Frame.ts:696:13)
    at async CdpPage.waitForSelector (/home/yyy/rpas/sss/s25-sssss-search/node_modules/puppeteer-core/src/api/Page.ts:2907:12)
[nodemon] app crashed - waiting for file changes before starting...

how to deal with it?

How do I prevent an audio file from replaying onmouseup?

I’m simulating a piano that plays a corresponding audio file when the appropriate key is clicked.

If I allow the length of the file to run as if the piano key was sustained, and if I long-press the click, it plays the file, and then it plays again when I release the mouse. It’s not noticeable if I simply click. If I instruct the audio to stop and reset its currentTime attribute on release of the mouse it doesn’t do this. I wondered if there was something amiss in propagation, but I couldn’t seem to pinpoint it.

const keysObj = {
  'c-key': new Audio(dir + 'key08-middleC.mp3'), 
  'd-key': new Audio(dir + 'key10.mp3'), 
...
}

let keyPlay = (key) => {
  keysObj[key.target.id].play();
}

let keyReturn = (key) => {
  const isSustained = document.querySelector("input[name='sustain']:checked");

  if (!isSustained) {
    keysObj[key.target.id].pause();
  }
  
  keysObj[key.target.id].currentTime = 0;
}

let keyPress = (note) => {
  note.onmousedown = keyPlay;
  note.onmouseup = keyReturn;
}

When the length of a page changes, is there a way to scroll up or down smoothly instead of jumping?

I am trying to create a component where there are two tabs, one is a table that displays data, and the other lets the user view more in depth information on specific entries in the table. The issue I am having is that the component is at the bottom of a page, and the info tab is shorter than the table tab, so when I switch between them it shortens the page and jumps instead of scrolling smoothly.

Is there a way to have the page scroll instead of jumping like this, and if that is impossible, is there at least a way to have it scroll before rendering the change?

I tried using useLayoutEffect to scroll before switching, but it only works when going from the larger table tab to the shorter info tab. This is what I have so far:

import React, { useState, useRef, useLayoutEffect } from "react";
import { Button } from "react-bootstrap";
import '../.css'

export default function Example(props) {
    const fields = ["ID", "A count", "B count", "diff"]

    const data = [{ id: 1, aCount: "data", bCount: "data", diff: "difference" },
    { id: 2, aCount: "data", bCount: "data", diff: "difference" },
    { id: 3, aCount: "data", bCount: "data", diff: "difference" },
    { id: 4, aCount: "data", bCount: "data", diff: "difference" },
    { id: 5, aCount: "data", bCount: "data", diff: "difference" },
    { id: 6, aCount: "data", bCount: "data", diff: "difference" },
    { id: 7, aCount: "data", bCount: "data", diff: "difference" },
    { id: 8, aCount: "data", bCount: "data", diff: "difference" },
    { id: 9, aCount: "data", bCount: "data", diff: "difference" },]

    const [isTableVisible, setIsTableVisible] = useState(true)
    const [infoData, setInfoData] = useState(data[0])

    const tabRef = useRef()
    const isMounted = useRef(false);

    useLayoutEffect(() => {
        if (isMounted.current) {
            tabRef.current.scrollIntoView()
        } else {
            isMounted.current = true;
        }
    }, [isTableVisible]);

    function handleTabClick() {
        setIsTableVisible(!isTableVisible)
    }
    function handleViewClick(index) {
        setIsTableVisible(false)
        setInfoData(data[index])
    }

    return (
        <div>
            <div className="ref" id="table" ref={tabRef} />

            {isTableVisible ?
                <div>
                    <span className="tab-active"> Table </span><span className="tab" onClick={handleTabClick}> Info </span>
                </div>
                : <div>
                    <span className="tab" onClick={handleTabClick}> Table </span><span className="tab-active"> Info </span>
                </div>}
                
            {isTableVisible ?
                <div>
                    <table className="data-table">
                        <thead>
                            <tr>
                                {fields.map((field, i) => <th key={field}>{field}</th>)}
                            </tr>
                        </thead>
                        <tbody>
                            {data.map((currData, i) =>
                                <tr key={i}>
                                    <td>{currData.id}
                                        <br />
                                        <Button
                                            variant="btn btn-outline-primary"
                                            onClick={(e => handleViewClick(i))}>
                                            View
                                        </Button>
                                    </td>
                                    <td>
                                        {currData.aCount}
                                    </td>
                                    <td>
                                        {currData.bCount}
                                    </td>
                                    <td >
                                        {currData.diff}
                                    </td>
                                </tr>
                            )}
                        </tbody>
                    </table>

                </div>
                : <div className="info-section">
                        Box for Data    
                </div>
            }
        </div>
    )
}

Gravity in P5.JS using rectangles

At this point, I will be frank. I’m stupid I’ve been sitting here for 2 hours watching YT videos and trying over and over but nothing will work

I’ve tried decreasing the X and quickly increasing it could someone help? I would appreciate any help

Should I be using the useState hook or just standard variables for my game’s values?

I’m building a game in react with electron.js and it’s going pretty well, but I can’t decide if I should be using states for all of the action I’m doing, or if it’s overkill for what I need to do. Especially as I’m going to be running the same function multiple times and taking the result that shows up twice in three attempts in a “best two out of three” format.

The game is called QB Simulator. In the next update, the wide receiver and the cornerback will do battle with three separate options for the user to choose:

  1. Short Route: If the user chooses a short route, then the CB and WR do battle once, and if the WR wins, they’re wide open for the QB to make the throw. If the CB wins, that receiver is covered and throwing the ball towards them will result in another roll to see if the throw is caught, intercepted, or batted down.
  2. Medium Route: Same basic principle as short route, but in a best two out of three format.
  3. Deep Route: Same principle as short route, but in a best three out of five format.

The mechanics for the QB’s throwing aren’t in place yet, so right now I”m trying to nail down how exactly the CB Receiver Battles should function. Because I’m using so many states, I wonder how I can do anything similar to a best two out of three format with updating states. Is it even possible, or would I be better served just using standard variables in a single source of truth?

Here’s the page that currently holds all the states:

import React, { useState } from "react";
import { shortRoute, midRoute, deepRoute } from "../../functions";
import { QBCreator, WRCreator, CBCreator } from "../playerCreator";

export default function GameCanvas() {
  // These don't need to be states? At least the win/battle functions shouldn't
  // QB States
  let [firstName, setFirstName] = useState("");
  let [lastName, setLastName] = useState("");
  let [accuracy, setAccuracy] = useState(60);
  let [armStr, setArmStr] = useState(60);
  let [speed, setSpeed] = useState(60);
  let [accel, setAccel] = useState(60);
  let [decMak, setDecMak] = useState(60);
  let [upgradePoints, setUpgradePoints] = useState(25);

  // WR States
  const [wrSpeed, setWrSpeed] = useState(60);
  const [wrAccel, setWrAccel] = useState(60);
  const [routeR, setRouteR] = useState(60);
  const [wrCatch, setWrCatch] = useState(60);

  // CB States
  const [cbSpeed, setCbSpeed] = useState(60);
  const [cbAccel, setCbAccel] = useState(60);
  const [coverage, setCoverage] = useState(60);
  const [cbCatch, setCbCatch] = useState(60);

  // Battle States, may convert the wins into objects with the name and win diff (with crit as the value in the event of a crit)
  // as opposed to seperating win and crit into different states.
  const [accelWin, setAccelWin] = useState("");
  const [speedWin, setSpeedWin] = useState("");
  const [coverWin, setCoverWin] = useState("");
  const [accelCrit, setAccelCrit] = useState({ "": false });
  const [speedCrit, setSpeedCrit] = useState({ "": false });
  const [coverCrit, setCoverCrit] = useState({ "": false });

  // Final deterministic states
  const [wrOpen, setWrOpen] = useState(false);

  // We create an object to hold the states of both combatants so that they can easily go into the
  // battle function.
  const wrObj = {
    speed: wrSpeed,
    accel: wrAccel,
    routeR,
    catching: wrCatch,
  };

  const cbObj = {
    speed: cbSpeed,
    accel: cbAccel,
    coverage,
    catching: cbCatch,
  };

  // Last but not least, for concision's sake we have an object that contains all the states and variables
  // we need for a fair fight.

  const battleObj = {
    wrObj,
    cbObj,
    accelWin,
    setAccelWin,
    accelCrit,
    setAccelCrit,
    speedWin,
    setSpeedWin,
    speedCrit,
    setSpeedCrit,
    coverWin,
    setCoverWin,
    coverCrit,
    setCoverCrit,
    wrOpen,
    setWrOpen,
  };

  return (
    <div
      style={{
        backgroundColor: "red",
        alignContent: "center",
        display: "flex",
        flexBasis: 2,
        flexDirection: "column",
        justifyContent: "center",
        alignItems: "center",
        textAlign: "center",
      }}
    >
      <div>
        <h1>Let's Start with Your QB</h1>
        <QBCreator
          firstName={firstName}
          setFirstName={setFirstName}
          lastName={lastName}
          setLastName={setLastName}
          accuracy={accuracy}
          setAccuracy={setAccuracy}
          armStr={armStr}
          setArmStr={setArmStr}
          speed={speed}
          setSpeed={setSpeed}
          accel={accel}
          setAccel={setAccel}
          decMak={decMak}
          setDecMak={setDecMak}
          upgradePoints={upgradePoints}
          setUpgradePoints={setUpgradePoints}
        />
      </div>
      <div>
        <h1>Now Let's Make Your WR and their Opponent</h1>
        <WRCreator
          wrSpeed={wrSpeed}
          setWrSpeed={setWrSpeed}
          wrAccel={wrAccel}
          setWrAccel={setWrAccel}
          routeR={routeR}
          setRouteR={setRouteR}
          wrCatch={wrCatch}
          setWrCatch={setWrCatch}
        />
        <CBCreator
          cbSpeed={cbSpeed}
          setCbSpeed={setCbSpeed}
          cbAccel={cbAccel}
          setCbAccel={setCbAccel}
          coverage={coverage}
          setCoverage={setCoverage}
          cbCatch={cbCatch}
          setCbCatch={setCbCatch}
        />
      </div>
      <div>
        <h1>Rock and Roll! Let's play!</h1>
        <button
          onClick={() => {
            shortRoute(battleObj);
          }}
        >
          Short route
        </button>
        <button
          onClick={() => {
            midRoute(battleObj);
          }}
        >
          Medium route
        </button>
        <button
          onClick={() => {
            deepRoute(battleObj);
          }}
        >
          Deep route
        </button>
      </div>
    </div>
  );
}

The QBCreator, etc. functional components just set the basic states and hold that information so the user can see them as the battles happen.

Here are the functions that currently affect the game:

// Here's the dice roll function
function battleRoll(wrStat, cbStat) {
  // We create two variables, one hold the result of a WR skill check up to 100,
  // the other holds the result of a CB skill check up to 100.
  // The WR/CB's stat in question serves as the possible minimum for the roll.
  let wrRoll = Math.floor(Math.random() * (100 - wrStat) + wrStat);
  let cbRoll = Math.floor(Math.random() * (100 - cbStat) + cbStat);

  if (wrRoll > cbRoll) {
    return {
      wrWins: true,
      wrWinDiff: wrRoll - cbRoll,
      cbWinDiff: null,
    };
  } else if (cbRoll > wrRoll) {
    return {
      wrWins: false,
      cbWinDiff: cbRoll - wrRoll,
      wrWinDiff: null,
    };
  } else if (wrRoll === cbRoll) {
    return "Push";
  }
}

// This is the speed battle subfunction of the larger full battle function.
// Obj 1 is the result of the accelFight, obj2 is WR, obj3 is CB.
function speedBattle(
  win,
  obj1,
  obj2,
  obj3,
  setSpeedWin,
  setSpeedCrit,
  setWrOpen
) {
  let speedFight = battleRoll(obj2.speed, obj3.speed);
  // We need implement the states for the wins, the result of speedfight, and the crit bools.

  // This is what happens if there's an accel crit. Should this be moved to the larger battle function?
  if (win == "wr" && obj1.wrWinDiff > 10) {
    console.log("CRITICAL WR WIN, speedfight result: ", speedFight);
    setSpeedWin("wr");
    setWrOpen(true);
  } else if (win == "cb" && obj1.cbWinDiff > 10) {
    console.log("CRITICAL CB WIN, speedfight result: ", speedFight);
    setSpeedCrit({ cb: true });
    setSpeedWin("cb");
    // This is what happens if there's an accel win, but no crit.
  } else if (win == "wr") {
    console.log("WR accel win, speedfight result: ", speedFight);
    setWrOpen(true);
    setSpeedWin("wr");
  } else if (win == "cb") {
    console.log("CB accel win, speedfight result: ", speedFight);
    setWrOpen(false);
    setSpeedWin("cb");
  }
}

// This is the route running v coverage battle subfunction of the larger full battle function.
// Obj 1 is the result of the speedFight, obj2 is WR, obj3 is CB.
function routeVCover(
  win,
  obj1,
  obj2,
  obj3,
  speedWin,
  setCoverWin,
  setCoverCrit,
  setWrOpen
) {
  if (speedWin) {
    let coverFight = battleRoll(obj2.routeR, obj3.coverage);

    if (obj1.wrWins === true && obj1.wrWinDiff < 10) {
      console.log("WR speed win, coverfight result: ", coverFight);
    } else if (obj1.wrWins === false && obj1.cbWinDiff < 10) {
      console.log("CB speed win, coverfight result: ", coverFight);
    } else if (obj1.wrWinDiff >= 10) {
      console.log("CRITICAL WR WIN, coverfight result: ", coverFight);
    } else if (obj1.cbWinDiff >= 10) {
      console.log("CRITICAL CB WIN, coverfight result: ", coverFight);
    }
  }
}

// These three functions define the different route lengths. Short Routes see a single CB Receiver War
// Mid Routes are best 2 out of 3, deep routes are best 3 out of 5.
export function shortRoute({
  wrObj,
  cbObj,
  accelWin,
  setAccelWin,
  accelCrit,
  setAccelCrit,
  speedWin,
  setSpeedWin,
  speedCrit,
  setSpeedCrit,
  coverWin,
  setCoverWin,
  coverCrit,
  setCoverCrit,
  wrOpen,
  setWrOpen,
}) {
  //
  cbReceiverWar(
    wrObj,
    cbObj,
    accelWin,
    setAccelWin,
    accelCrit,
    setAccelCrit,
    speedWin,
    setSpeedWin,
    speedCrit,
    setSpeedCrit,
    coverWin,
    setCoverWin,
    coverCrit,
    setCoverCrit,
    wrOpen,
    setWrOpen
  );

  if (wrOpen === true) {
    console.log("Mailbox!");
  } else {
    console.log("Strapped!");
  }
}

export function midRoute({
  wrObj,
  cbObj,
  accelWin,
  setAccelWin,
  accelCrit,
  setAccelCrit,
  speedWin,
  setSpeedWin,
  speedCrit,
  setSpeedCrit,
  coverWin,
  setCoverWin,
  coverCrit,
  setCoverCrit,
  wrOpen,
  setWrOpen,
}) {
  let battleOne = cbReceiverWar(
    wrObj,
    cbObj,
    accelWin,
    setAccelWin,
    accelCrit,
    setAccelCrit,
    speedWin,
    setSpeedWin,
    speedCrit,
    setSpeedCrit,
    coverWin,
    setCoverWin,
    coverCrit,
    setCoverCrit,
    wrOpen,
    setWrOpen
  );

  let battleTwo = cbReceiverWar(
    wrObj,
    cbObj,
    accelWin,
    setAccelWin,
    accelCrit,
    setAccelCrit,
    speedWin,
    setSpeedWin,
    speedCrit,
    setSpeedCrit,
    coverWin,
    setCoverWin,
    coverCrit,
    setCoverCrit,
    wrOpen,
    setWrOpen
  );

  let battleThree = cbReceiverWar(
    wrObj,
    cbObj,
    accelWin,
    setAccelWin,
    accelCrit,
    setAccelCrit,
    speedWin,
    setSpeedWin,
    speedCrit,
    setSpeedCrit,
    coverWin,
    setCoverWin,
    coverCrit,
    setCoverCrit,
    wrOpen,
    setWrOpen
  );

  
}

export function deepRoute({
  wrObj,
  cbObj,
  accelWin,
  setAccelWin,
  accelCrit,
  setAccelCrit,
  speedWin,
  setSpeedWin,
  speedCrit,
  setSpeedCrit,
  coverWin,
  setCoverWin,
  coverCrit,
  setCoverCrit,
  wrOpen,
  setWrOpen,
}) {}

// This function is the big bad battle. Acceleration determines who wins off the line, so that counts for the first
// 1 seconds of the route. Speed determines who's more likely to win after that.
// Unless the speed win is above 10 or more, you have three coverage vs. route running rolls,
// best two out of three wins, unless one has a roll that's a 95+, then that's an automatic win.
// Whoever wins has a +10 advantage to a catch, but if they lost on a 95+ critical, or if they lose by 20 or more,
// they don't even get a catch roll. Later we'll add a yardage estimation (for short, medium, and long)
// to progress down the field.

// We need this function to return a win state or a crit state. Should we really be tracking all of these states?

export function cbReceiverWar(
  wrObj,
  cbObj,
  accelWin,
  setAccelWin,
  accelCrit,
  setAccelCrit,
  speedWin,
  setSpeedWin,
  speedCrit,
  setSpeedCrit,
  coverWin,
  setCoverWin,
  coverCrit,
  setCoverCrit,
  wrOpen,
  setWrOpen
) {
  // Accel war kicks off the fight. If we land a crit here, the battle is pretty much over.
  // After 1.5 seconds, we move to the speed battle.
  // If that battle ends up in a crit, then it's over.
  // During the speed battle, we have the coverage vs route running battle.
  // If there's a coverage crit, it's the same deal. Either the receiver is locked up,
  // or the CB is juked out of their shoes. The catch battle is the last line of defense.
  let accelFight = battleRoll(wrObj.accel, cbObj.accel);
  // Don't forget to add accelCrits here, and account for a "Push" result.
  if (accelFight.wrWins == true && accelFight.wrWinDiff <= 10) {
    console.log("WR Win Diff", accelFight.wrWinDiff);
    setAccelWin("wr");
    setWrOpen(true);
    setTimeout(() => {
      console.log("speed battle triggered wr win");
      speedBattle(
        accelWin,
        accelFight,
        wrObj,
        cbObj,
        setSpeedWin,
        setSpeedCrit,
        setWrOpen
      );
      routeVCover(speedWin, wrObj, cbObj);
    }, 1500);
  } else if (accelFight.wrWins == false && accelFight.cbWinDiff <= 10) {
    console.log("CB Win Diff", accelFight.cbWinDiff);
    setAccelWin("cb");
    setTimeout(() => {
      console.log("speed battle triggered cb win");
      speedBattle(
        accelWin,
        accelFight,
        wrObj,
        cbObj,
        setSpeedWin,
        setSpeedCrit,
        setWrOpen
      );
      routeVCover(speedWin, wrObj, cbObj);
    }, 1500);
    // Critical accel win for WR
  } else if (accelFight.wrWins == true && accelFight.wrWinDiff > 10) {
    setAccelWin("wr");
    setAccelCrit({ wr: true });
    setWrOpen(true);
  } else if (accelFight.wrWins == false && accelFight.cbWinDiff > 10) {
    setAccelWin("cb");
    setAccelCrit({ cb: true });
  }
}

The functions work as intended, but I’m hitting a wall when it comes to implementing the medium and deep route functions. How can I keep track of states constantly changing?

Vue Router: How to Dynamically Load Components in a Layout Based on Child Route in Nested Structure?

I have a layout page:

<template>
  <div class="flex h-full w-full items-center justify-center">
    <side-navbar></side-navbar>
    <hello-user-overview></hello-user-overview>
    <component :is="selectedCmp"></component>
  </div>
</template>

<script setup>
// components
import sideNavbar from '../components/UserDashboardCmp/sideNavbar.vue'
import HelloUserOverview from '../components/UserDashboardCmp/HelloUserOverview.vue'
// import UserFeed from '../components/UserDashboardCmp/UserFeed.vue'
// import TheResources from '../components/UserDashboardCmp/TheResources.vue'
// vue relaated
import { onMounted, onBeforeUnmount } from 'vue'
// stores
import { useDashboardStore } from '../stores/UIStore/userDashboardStore'
// import { useUserStore } from '../stores/Users/userStore'
// stores variables
const userStore = useDashboardStore()
// const userDataStore = useUserStore()
// variables
const selectedCmp = userStore.cmp

onMounted(() => {
  // userStore.setUserFeed(UserFeed)
})

onBeforeUnmount(() => {
  // userStore.setComponent('')
})
</script>

<style scoped></style>

On the left is navbar, and on the right there are components, that are choosen by the user in the navbar through the menu- navbar on the left. Everything is in the router ‘/HelloUser’.
I want to make work so if the user go to the route ‘/HelloUser/UserFeed’, the user is in the layout and the UserFeed component is loaded.

    <component :is="UserFeed"></component>

and on the route ‘/HelloUser/TheResources’

    <component :is="TheResources"></component>

I made the router:

import UserFeed from '../components/UserDashboardCmp/UserFeed.vue'
import TheResources from '../components/UserDashboardCmp/TheResources.vue'

 {
      path: '/HelloUser',
      component: HelloUser,
      children: [
        {
          path: '',
          name: 'UserFeed',
          component: UserFeed
        },
        {
          path: 'TheResources',
          name: 'TheResources',
          component: TheResources
        }
      ]
    },

but it doesnt work- the console is empty and no component is loaded.
How to make it work?

I switched:

<component :is="selectedCmp"></component>

with:

<router-view></router-view> 

but it made no diffrenace.

Getting (TypeError: Cannot read properties of undefined (reading ‘map’)) [duplicate]

I“m using a headless umbraco cms as an API for my react app
And I do not know why im getting undefined (reading ‘map’) even tho everything should be right

I have this Spots.jsx code:

const Spots = ({ spots }) => (
  <div>
    {spots.map((spot) => (
      <div key={uuidv4()}>
        <h2>{spot.heading}</h2>
        <div >{spot.url}</div>
      </div>
    ))}
  </div>
);

export default Spots;

Spots are rendered in Home.jsx:

    const Home = ({ hero, spots, products }) => (
  <>
    <Hero heading={hero?.heading} message={hero?.message} />
    <Spots spots={spots} />
    <ProductGrid products={products} />
  </>
);

and this is my App.jsx:

    const App = () => {

  const [page, setPage] = useState(null);

  useEffect(() => {
    fetch("/api/pages/init")
      .then((resp) => resp.json())
      .then((data) => {
        setPage(data);
      });
  }, []);

  return page ? (
    <Router>
          <Routes> 
            <Route 
            index 
            element={
              <Home
                  hero={page.hero}
                  spots={page.spots}
                  products={page.products}
              />
            } 
            />   
                </Route>
          </Routes>
    </Router>
  ) : (
    "Laddar sidan..."
  );
};

This is my PagesController (API) code:

[HttpGet("init")]
    public object GetInit()
    {
        var home = umbracoHelper.ContentAtRoot().OfType<HomePage>().First();

        var response = new
        {
            global = new
            {
                hero = new
                {
                    heading = home.Heading,
                    message = home.Message
                },

                spots = home.Spots.Select(x =>
                    new
                    {
                        heading = x.Content.Value("heading"),
                        url = x.Content.Value("url")
                    }
                ),
            }
        };

        return response;
    }

My `HomePage“ has these property names:

public virtual string Heading => global::Umbraco.Cms.Web.Common.PublishedModels.HeroCompostion.GetHeading(this,_publishedValueFallback);

public virtual string Message => global::Umbraco.Cms.Web.Common.PublishedModels.HeroCompostion.GetMessage(this, _publishedValueFallback);

public virtualglobal::Umbraco.Cms.Core.Models.Blocks.BlockListModel Spots => global::Umbraco.Cms.Web.Common.PublishedModels.SpotsCompostions.GetSpots(this, _publishedValueFallback);

Iam getting

Uncaught TypeError: Cannot read properties of undefined (reading
‘map’)
at Spots (Spots.jsx:5:1)

Ofcourse i got that error for my other components, and I checked everything but couldnt find the mistake i made

This is what the response is from my browsing debuging tools:

{
"global": {
    "siteHeader": {
        "menu": [
            {
                "text": "Start",
                "link": "/"
            },
            {
                "text": "Admin",
                "link": "/admin"
            }
        ]
    },
    "hero": {
        "heading": "Freaky Fashion",
        "message": "Lorem Ipsum Dolor"
    },
    "spots": [
        {
            "heading": "Lorem Ipsum Dolor",
            "url": "https://google.com"
        },
        {
            "heading": "Lorem Ipsum Dolor",
            "url": "https://google.com"
        },
        {
            "heading": "Lorem Ipsum Dolor",
            "url": "https://google.com"
        }
    ],
    "products": [
        {
            "name": "Vit T-shirt",
            "description": "Lorem ipsum dolor ",
            "image": "/media/nnwf1atk/placeholder_view_vectorsvg.png",
            "link": "/products/vit-t-shirt/"
        },
        {
            "name": "Svart T-shirt",
            "description": "Lorem Ipsum Dolor",
            "image": "/media/nnwf1atk/placeholder_view_vectorsvg.png",
            "link": "/products/svart-t-shirt/"
        },
        {
            "name": "Vinter Jacka",
            "description": "Lorem Ipsum Dolor",
            "image": "/media/nnwf1atk/placeholder_view_vectorsvg.png",
            "link": "/products/vinter-jacka/"
        }
    ]
}
}

JS does not get value of [element].style.animationPlayState

I am trying to change the value of sun.style.animationPlayState for the “sun” html element when a button is clicked.

JS:

window.onload = function(){
  let btn = document.getElementById("button");
  let sun = document.getElementById("sun");
  let sky = document.getElementById("animation-stage");
  btn.addEventListener("click", function(){
    //let playState = window.getComputedStyle(sun).animationPlayState;
    //console.log(playState);
    if (sun.style.animationPlayState === "paused"){
      sun.style.animationPlayState = "running";
      sky.style.animationPlayState = "running";
    } else {
      sun.style.animationPlayState = "paused";
      sky.style.animationPlayState = "paused";
    }
  } )
}

I noticed that the first time this function is called, sun.style.animationPlayState is set to empty string, when it should be set to ‘running’. Why is this the case?

I tried to check if sun.style.animationPlayState was “running” but it was set to empty string in JS.

Advanced Markers Google Maps Icon Customisation

I am trying to customize my google maps icons with Advanced Markers Class, however it doesnt work. Here is my js code :

function addMarker(id, location) {
// remove old marker if exists
let oldMarker = document.getElementById(id);
if (oldMarker) {
oldMarker.remove();
}

const pinView = new google.maps.marker.PinElement({
background: '#0000ff'
})

let position = "" + location.latitude + "," + location.longitude;
let marker = createGmpAdvancedMarker(id, position, location.name, pinView);
let gmp = document.getElementById("gmp-map");
gmp.appendChild(marker);
}

function createGmpAdvancedMarker(id, position, title, content) {
let marker = document.createElement("gmp-advanced-marker");
marker.setAttribute("content", content);
marker.setAttribute("id", id);
console.log("position for marker:", position);
marker.setAttribute("position", position);
marker.setAttribute("title", title);
return marker;
}

Failed to fetch when using react-doc-viewer

I want to use https://github.com/cyntler/react-doc-viewer to view files in the browser. The problem is that I’m getting failed to fetch error for some links. For example, the following src works fine and doc is properly displated:

‘https://www.mtsac.edu/webdesign/accessible-docs/word/example03.docx’

but the following doesnt
‘https://freetestdata.com/wp-content/uploads/2021/09/Free_Test_Data_100KB_XLSX.xlsx’ and I m getting an error. What might be the reason and how to fix that?

Is there a way to play audio from the web API audioContext.createBufferSource() on an Iphone through the speakers as opposed to the receiver?

On Iphone 13 ios 16.6.1

Chrome browser running the following Javascript to be played on a button click after
navigator.mediaDevices.getUserMedia({ audio: true }) is called and allowed.

    const response = await fetch(filePath);
    const arrayBuffer = await response.arrayBuffer();
    const audioBuffer = await this.audioContext.decodeAudioData(arrayBuffer);
    
    const source = this.audioContext.createBufferSource();
    source.buffer = audioBuffer;
    source.connect(this.audioContext.destination);
    source.start(0);

The audio output is from the ear receiver and very low. Is there a way to have the output to the speaker on an iphone chrome browser or is this just not possible on a web application?

I’ve checked out other web apps that use audioContext such as https://thesession.org/ and they seem to output audio from the ear receiver as well rather than the speakers.

I tried using gainNode.gain.volume to increase sound, but it’s still too quiet for my use case and the quality of the audio degrades if set too high.

I tried to see if I could find the sinkId of output devices using navigator.mediaDevices.enumerateDevices(), but I could only find input devices, and audioContext.setSinkId() doesn’t seem to be supported on ios.