Listen/detect the Location URL change in React application

I have a requirement to listen/detect the Location URL change in React application.

I have tried using below code but it changes the location and then gets called.

const location = useLocation();

useEffect(() => {
debugger;
console.log(‘Location changed’);
}, [location]);

Is there a way to listen a URL change before actually changing the location?

Also, Is it possible to find “fromLocation” and “ToLocation”?

I am using “react-router-dom”: “^5.2.0”.

Please help.

Thanks & Regards,
Jyoti

3D Array output in GPU.JS

Hello I’m really new with using GPU.js and I am having trouble understanding createKernel and its output. I want to have a 3D array that stores the outputs from my current function. For example, below, is a gpu matrix multiplication that multiplies matrix a and b, and the result of this function is a 2D array. There are more than one matrix that I want to multiply to a and I want to store all their output in one 3D array.

  const gpu = new GPU();
  const multiplyMatrix = gpu.createKernel(function(a, b) {
    let sum = 0;
    for (let i = 0; i < 10; i++) {
      sum += a[this.thread.y][i] * b[i][this.thread.x];
    }
    return sum;
  }).setOutput([10, 10])

Can anyone please help me. I tried using for loop but it’s so slow and I read because it is expensive to keep using createKernel?

let big3Dmatrix = []
for(let i=0; i<matrices.length; i++){
    big3Dmatrix.push(multiplyMatrix(a,matrices[i]))
}

I would appreciate any help. Thank you!

vue.js ReferenceError (when using resize event)

I’m trying to get the height of the window on resize, but I keep getting the error ReferenceError: calcOfSliderHeight is not defined.

Could anyone let me know what’s going on? Here’s my code

let example = new Vue({
    el: '#example',
    data() {
        return {
            pageIndex: 2,
            posTop: 0,
            posTop2: 0,
        }
    },
    methods: {
        calcOfSliderHeight() {
            let _this = this;
            _this.posTop = (_this.pageIndex - 1) * window.innerHeight
        },
        calcOfSliderHeight2() {
            let _this = this;
            _this.posTop2 = (_this.pageIndex - 3) * window.innerHeight
        },
    },
    mounted: function() {
        let _this = this;

        window.addEventListener('resize', function() {
            calcOfSliderHeight()
            calcOfSliderHeight2()
        });

        _this.posTop = calcOfSliderHeight();
        _this.posTop2 = calcOfSliderHeight2();
    }
});

Multiple image change on click (similar to Cargo image gallery scrub)

I am trying to replicate Cargo’s image gallery scrub using my own HTML/CSS and/or Java. Example of what I want here on image click: https://sage-smith.com/. It is similar to this stack thread (which worked in my code): how to change image onclick javascript function?

However, this solution only offers to click between 2 images. I am trying to do it with multiple images (like an image gallery).

This is what I have so far:

HTML

 <a><img src="collage3.jpg" id="changer" onclick="changeImage(this)"/></a>

Javascript

  function changeImage(element) {
     element.src = element.bln ? "collage3.jpg" : "asset-2.png";
     element.bln = !element.bln;  /* assigns opposite boolean value always */
 }

How to get updated DOM element in javascript code

I am trying to better understand the relationship between how JavaScript updates DOM object.
Here is my html file index.html:

<!DOCTYPE html>
<html lang="en">
  <head>
  </head>
  <body>
    <div id="container">old</div>
  </body>
  <script src="script.js"></script>
</html>

and here is my JavaScript file script.js,

const container = document.getElementById("container");
console.log(container, container.innerHTML);
container.innerHTML = "new";
console.log(container, container.innerHTML);

The console logs the same <div> tag but with different innerHTML which is quiet unexpected:

<div id="container">new</div> 'old'
<div id="container">new</div> 'new'

Therefore my 1st question is, what makes it possible for the console to print the same div elements but different innerHTML?


Secondly I made a small change to my script with setTimeout,

let timeout = 30;
setTimeout(() => {
  container.innerHTML = "new";
  console.log(container, container.innerHTML);
}, timeout);

Though container.innerHTML are always printed with different value, as expected, I found out that if the timeout value is above 35. The div tag is almost certainly printed differently with,

<div id="container">old</div> 'old'
<div id="container">new</div> 'new'

Then something I don’t understand happens. When timeout is set below 10, it is almost certain that div tag are printed as,

<div id="container">new</div> 'old'
<div id="container">new</div> 'new'

When timeout is set somewhere between 10 and 30ish, the result toggles, meaning sometimes

<div id="container">new</div> 'old'
<div id="container">new</div> 'new'

and sometimes

<div id="container">old</div> 'old'
<div id="container">new</div> 'new'

Therefore my second question is, what causes this difference?

Much Appreciated.

‘await’ has no effect on this type of expression, but it does

I am trying to use useRef to auto focus on the mui textfield in the app. However, the textfield only apper after I clicked a button, so it is not initially mounted when the app is rendered. Therefore, the inputRef.current alway return undefined to me when I am using the useEffect hook, because the inputRef is hooked only after the textfield is appeared.

So instead I hook my inputRef.current?.focus() on the buttonlike this:
<Button onClick={() => {toggleCreateWindow(); useInput.current?.focus();}}>

But it won’t work either, until I put it like an inline async function like this:
<Button onClick={ async () => { await toggleCreateWindow(); useInput.current?.focus();}}>

Now it is working properly, but the vscode always remind me 'await' has no effect on this type of expression

Do anybody know why the async function works? I mean the function should not be asynchronous because it is only a setState & toggle window function: const toggleCreateWindow = () => {setOpenCreate(!openCreate);}; Also, why the vscode is giving me this warning?

Much appreicated

How do I filter my web scraping result to not have /n or tab

I am scraping data from a job market website. My scrape return the result that I want but it is full of /n, /t or a lot of spacing. How do I filter the result to get just the contents?

This is my code:

async function start() {

    const browser = await puppeteer.launch({
        headless: true,
        defaultViewport: null,
        args: ['--ignore-certificate-errors']
    });

    var name = ["Job Name"];
    var country = ["Country"];
    var company = ["Company Name"];
    var type = ["Job Type"];
    var salary = ["Salary"];
    var skills = ["Skills Require"];
    var desc = ["Job Description"];
    var req = ["Job Requirements"];
    var resp = ["Job Responsibility"];
    var industry = ["Industry"];

    for (var j = 1; j < 2; j++) {

        const page = await browser.newPage();
        page.setDefaultNavigationTimeout(0);

        await page.goto('https://startupjobs.asia/job/search?q=&job-list-dpl-page=' + j, {
            waitUntil: "networkidle2",
            timeout: 3000000
        });

        console.log('browsing page ' + j);

        for (var i = 1; i < 31; i++) {

            await page.waitForXPath("/html/body/div[1]/div[3]/div[1]/div/div[1]/ul/li[" + i + "]/div/div[1]/div/h5/a")
            var b = await page.$x("/html/body/div[1]/div[3]/div[1]/div/div[1]/ul/li[" + i + "]/div/div[1]/div/h5/a")
            await b[0].click();

            const elementsToFind = [
                { xpath: "/html/body/div[1]/div[3]/div[1]/div/div[1]/ul/li[" + i + "]/div/div[1]/div/h5/a", propName: 'job_name' },
                { xpath: '/html/body/div[1]/div[3]/div[2]/div[1]/div[2]/div/h6[2]/a', propName: 'country' },
                { xpath: "/html/body/div[1]/div[3]/div[1]/div/div[1]/ul/li[" + i + "]/div/div[1]/div/p[1]/a", propName: 'company' },
                { xpath: '/html/body/div[1]/div[3]/div[2]/div[2]/div[1]/div[2]/div[1]/div[3]/p', propName: 'job_type' },
                { xpath: '/html/body/div[1]/div[3]/div[2]/div[2]/div[1]/div[2]/div[1]/div[1]/p', propName: 'salary' },
                { xpath: '/html/body/div[1]/div[3]/div[2]/div[2]/div[1]/div[2]/div[1]/div[4]/p', propName: 'skills' },
                { xpath: '/html/body/div[1]/div[3]/div[2]/div[2]/div[1]/div[2]/div[2]/div[1]/div', propName: 'job_description' },
                { xpath: '/html/body/div[1]/div[3]/div[2]/div[2]/div[1]/div[2]/div[2]/div[3]/div', propName: 'job_requirement' },
                { xpath: '/html/body/div[1]/div[3]/div[2]/div[2]/div[1]/div[2]/div[2]/div[2]/div', propName: 'job_responsibility' },
                { xpath: '/html/body/div[1]/div[3]/div[2]/div[2]/div[1]/div[2]/div[1]/div[2]/p', propName: 'industry' },
                // ...
            ];
            /*const elementsToFind2 = [
                { xpath: '/html/body/div[1]/div[3]/div[2]/div[2]/div[1]/div[3]/div[1]/div[1]/p/a',      propName2: 'website' },
                { xpath: '/html/body/div[1]/div[3]/div[2]/div[2]/div[1]/div[3]/div[2]/div[1]/div',      propName2: 'about' },
                // ...
            ];*/

            var results = {};

            for (var { xpath, propName } of elementsToFind) {
                await page.waitForXPath(xpath);
                var [el] = await page.$x(xpath);
                results[propName] = !el ? 'Not Found' : await (await el.getProperty('textContent')).jsonValue();
            }

            name.push(results['job_name']);
            country.push(results['country']);
            company.push(results['company']);
            type.push(results['job_type']);
            salary.push(results['salary']);
            skills.push(results['skills']);
            desc.push(results['job_description']);
            req.push(results['job_requirement']);
            resp.push(results['job_responsibility']);
            industry.push(results['industry']);

            //await page.evaluate(() => document.querySelector("#suj-single-jobdetail-wrapper > div.detail-body > div.row > div.col.s12.tabs-wrapper.suj-company-review-tabs-wrapper > ul > li:nth-child(2) > a").click())            
        }
        await page.close();
    }

    await browser.close();

The result that I get is this:

‘n’ +
‘ n’ +
‘ Part-Time n’ +
‘ | n’ +
‘ n’ +
‘ Temporary n’ +
‘ | n’ +
‘ n’ +
‘ Contract n’ +

I want it to be just Part time, temporary and contract.

Using Mantine UI .tsx file within a javascript based react project

I currently am building a fitness website and am looking to use Mantine UI accordion component which is based off Typescript. I built my react project with javascript. Is there a way to create a .tsx file and call it into my app.js file?

Here’s the error I am currently receiving. Am I missing the export on the Accordian code?

Module not found: Error: Can't resolve './components/Faq' in '/Users/rodriguezmedia/Desktop/blended/src'


    import { Group, Avatar, Text, Accordion } from '@mantine/core';
import React from 'react';

const charactersList = [
  {
    image: 'https://img.icons8.com/clouds/256/000000/futurama-bender.png',
    label: 'Bender Bending Rodríguez',
    description: 'Fascinated with cooking, though has no sense of taste',
    content: "Bender Bending Rodríguez, (born September 4, 2996), designated Bending Unit 22, and commonly known as Bender, is a bending unit created by a division of MomCorp in Tijuana, Mexico, and his serial number is 2716057. His mugshot id number is 01473. He is Fry's best friend.",
  },

  {
    image: 'https://img.icons8.com/clouds/256/000000/futurama-mom.png',
    label: 'Carol Miller',
    description: 'One of the richest people on Earth',
    content: "Carol Miller (born January 30, 2880), better known as Mom, is the evil chief executive officer and shareholder of 99.7% of Momcorp, one of the largest industrial conglomerates in the universe and the source of most of Earth's robots. She is also one of the main antagonists of the Futurama series.",
  },
  {
    image: 'https://img.icons8.com/clouds/256/000000/homer-simpson.png',
    label: 'Homer Simpson',
    description: 'Overweight, lazy, and often ignorant',
    content: 'Homer Jay Simpson (born May 12) is the main protagonist and one of the five main characters of The Simpsons series(or show). He is the spouse of Marge Simpson and father of Bart, Lisa and Maggie Simpson.',
  },
  {
    image: 'https://img.icons8.com/clouds/256/000000/spongebob-squarepants.png',
    label: 'Spongebob Squarepants',
    description: 'Not just a sponge',
    content: 'SpongeBob is a childish and joyful sea sponge who lives in a pineapple with his pet snail Gary in the underwater city of Bikini Bottom. He works as a fry cook at the Krusty Krab, a job which he is exceptionally skilled at and enjoys thoroughly. ',
  },
]

interface AccordionLabelProps {
  label: string;
  image: string;
  description: string;
}

function AccordionLabel({ label, image, description }: AccordionLabelProps) {
  return (
    <Group noWrap>
      <Avatar src={image} radius="xl" size="lg" />
      <div>
        <Text>{label}</Text>
        <Text size="sm" color="dimmed" weight={400}>
          {description}
        </Text>
      </div>
    </Group>
  );
}

function Demo() {
  const items = charactersList.map((item) => (
    <Accordion.Item label={<AccordionLabel {...item} />} key={item.label}>
      <Text size="sm">{item.content}</Text>
    </Accordion.Item>
  ));

  return (
    <Accordion initialItem={-1} iconPosition="right">
      {items}
    </Accordion>
  );
}

How would I fix this camera mouse glitch in ThreeJS

I’ve been working with ThreeJS for a couple of days now and i’ve come across a problem that i’ve seen happen in other online games. When I turn my camera using the PointerLockControls, it makes the camera go to a previous or random rotation. How would I fix this?

Here is the code that I am using for the camera:

import {PointerLockControls} from "three/examples/jsm/controls/PointerLockControls";
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const controls = new PointerLockControls( camera, renderer.domElement );
document.addEventListener('click', () => {
    document.querySelector("#bg").requestPointerLock();
});

It looks like this: https://youtu.be/RjcVDSZSvfg

How do I fix this?

Liquid Script based on Conditional JQuery

Let’s suppose we have a dropdown toggle:

<label for="num-of-records">Rows per Page: </label>
<select name="num-of-records" id="num-of-records">
  <option value="" selected>default</option>
  <option value="25">25</option>
  <option value="50">50</option>
</select>

And we also have a liquid code:

{% include 'page' key: 'table' %}

For key, I have provide some options table,table25, and table50 for each dropdown options value.

I am new to liquid, but I want to create a jquery which select the key value based on the dropdown.

<script>
$.(this).append("{% include 'page' key: 'table"+ $.(#num-of-records).val()+"' %}"
</script>

So let’s say I choose option 25, so it will (maybe reopen the page) append liquid script of:

{% include 'page' key: 'table25' %}

JQuery Datatables Ajax Datasource Error – Requested unknown parameter

I’m pretty stuck as to why I’m receiving this error from JQuery Datatables “DataTables warning: table id=myTable – Requested unknown parameter ‘0’ for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4″. I’ve tried to review the website info but it didn’t make much sense to me. My only guess is that it has something to do with the way the data may be formatted. If so, I’m unsure how to resolve the issue.

This chunk of code is getting the API so I can view it in the console and then again for the datatable data.

      var apiKey = "0ca80ddc-63f6-476e-b548-e5fb0934fc4b";
      $.ajax({
          type: "GET",
          url: "http://brew-roster-svc.us-e2.cloudhub.io/api/teams",
          headers: { "api-key": apiKey },
          success: function(result){
            console.log(result)
            console.log(JSON.stringify(result));
          }
      });
      $(document).ready( function () {
        $('#myTable').dataTable({          
          "ajax": {
            "url": "http://brew-roster-svc.us-e2.cloudhub.io/api/teams",
            "type": "get",
            "dataSrc": "",
            "beforeSend": function (request) {
              request.setRequestHeader("api-key", apiKey);
            },
            "columns": [
              { "data": "logo" },
              { "data": "name" },
              { "data": "league" },
              { "data": "division" },
            ],
          }
        });
      });

Here are the results from my debugging Ajax results in the console.

(30) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]

This portion is a snippet of what I see when expanded:

0: {id: 133, nickname: 'Athletics', name: 'Oakland Athletics', location: 'Oakland', abbreviation: 'OAK', …}
1: {id: 134, nickname: 'Pirates', name: 'Pittsburgh Pirates', location: 'Pittsburgh', abbreviation: 'PIT', …}
[[Prototype]]: Array(0)

Is there a 10MB upload issue with PHP or Javascript?

At the moment I am trying to upload “large” files to a webhosting server.
For this I use an input field with multiple=’multiple’. Maximum file size is not set for this input field.
The PHP version is 7.4.
The maximum upload size is set to 256MB by the hoster.

The files are processed by js in a simple loop ( files[ x ] ).
The issue is that files larger than 10MB do not get any payload on upload. I generate formdata with file-chunks or full files appended which is only sent when files/chunks are below 10MB or when I let bigger files being sliced via Javascript to chunks under 10MB. The PHP $_FILES- array stays empty on 10MB+ files and the formdata is not available nor shown on upload in chrome/ff dev tools. The requests are sent via jquery $.ajax() after trying fetch and jquery $.POST(). All show the same behaviour. No errors are shown.

By the fact that I can upload 10MB+ files when slicing them to anything under 10MB via javascript slice() and any file below 10MB seems to show me that it is not a script- issue. Files under 10MB work, too when I set the chunk- size to something like 100MB or 200MB which is within the maximum upload size limitation.

Is there any known Apache/nginx server limitation that I might have missed?

Why is the property “dadType” being set to all the options avalable and staying with the last one, rather than the one selected?

It’s basicaly a text based adventure game i thought would be a fun first project.

Game.js

const textElement = document.getElementById('text')
const optionButtonsElement = document.getElementById('option-buttons')

let factions =["Grill Dad","Sports Dad","Car Dad","Vacation Dad","Drama Dad","The Craft Dad"]
let state = {
  dadType : '',
  items : ''
}
//variables
function startGame() {
  state = {}
  showTextNode(1)
}
//make a function to show the first prompt and reset "state"
function showTextNode(textNodeIndex) {
  const textNode = textNodes.find(textNode => textNode.id === textNodeIndex)
  textElement.innerText = textNode.text
  while (optionButtonsElement.firstChild) {
    optionButtonsElement.removeChild(optionButtonsElement.firstChild)
  }
//function to remove options with no text
  textNode.options.forEach(option => {
    if (showOption(option)) {
      const button = document.createElement('button')
      button.innerText = option.text
      button.classList.add('btn')
      button.addEventListener('click', () => selectOption(option))
      optionButtonsElement.appendChild(button)
    }
  })
}
//function to add options till you run out
function showOption(option) {
  return option.requiredState == null || option.requiredState(state)
}
//function to check for "state"
function selectOption(option) {
  const nextTextNodeId = option.nextText
  if (nextTextNodeId <= 0) {
    return startGame()
  }
  state = Object.assign(state, option.setState)
  showTextNode(nextTextNodeId)
}
//function to advance to the next prompt and assign "state"
/*function randNum() {
let rand = Math.floor(Math.random() * 5)
}
//random generator
function getDadType(state){
  return state.dadType
}
//get dad type (not working)
*/
const textNodes = [
  {
    id: 1,
    text: 'Insert adventure description here pick a faction of dad to play as.',
    options: [
      {
        text: factions[0],
        setState: state = {dadType: 'grill dad'} ,
        nextText: 2
      },
      {
        text: factions[1],
        setState: state = {dadType: 'sports dad'},
        nextText: 2
      },
      {
        text: factions[2],
        setState: state = {dadType: 'car dad'},
        nextText: 2
      },
      {
        text: factions[3],
        setState: state = {dadType: 'vacation dad'},
        nextText: 2
      },
      {
        text: factions[4],
        setState: state = {dadType: 'drama dad'},
        nextText: 2
      },
      {
        text: factions[5],
        setState: state = {dadType: 'craft dad'},
        nextText: 2
      },
      {
        text: 'Placeholder for Random',
        setState: {},
        nextText: 2
      },
      {
        text: 'Placeholder for Back',
        nextText: 2
      }
     ]
  },
  {
    id: 2,
    text: "First part of backstory "+state.dadType,
    options:[
    {
      text: 'some things you could say',
      nextText: 1
    }
startGame()

The property “dadType” is supposed to be set to whatever dadtype you selected in the first text node, but rather than setting it, and then ignoring the rest of the option buttons, it seems to run through all the options. I want it to just set the last ones property. It will still go to the correct next window, but the correct property is not set.

Access to XMLHttpRequest at “SOME-URL” from origin ‘localhost’ has been blocked by CORS policy. Redirect is not allowed for a preflight request

I am coding a Vue.js application. I created an API using python and hosted it using Heroku. But whenever I try to fetch JSON from this API, there is an error. I tried it on another API (Google Dictionary API: ‘https://api.dictionaryapi.dev/api/v2/entries/en/hello’), and it works just fine.

Here is the code:

methods: {
    calculate() {
      // Use this API call:
      // http://gpt3-model.herokuapp.com/api/type=text-ada-001/prompt=<code>/
      const url = 'https://gpt3-model.herokuapp.com/api/type=text-ada-001/prompt=' + this.code;
      axios.get(url, {
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
          'Access-Control-Allow-Origin': 'http://localhost:8080/',
        }
      })
        .then(response => {
          console.log(response.data);
          this.complexity = response.data;
        })
        .catch(error => {
          console.log(error);
        });
    }
  }

This is the error that I get: Access to XMLHttpRequest at ‘https://gpt3-model.herokuapp.com/api/type=text-ada-001/prompt=hi,%20how%20are%20you?/’ from origin ‘http://localhost:8080’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: Redirect is not allowed for a preflight request.

I want to directly call the result value by arithmetic operation on two state values

I want to display (salePrice + manualSettlementAmount), (salePrice -manualSettlementAmount), values ​​according to the operation of sale state ‘+’, ‘-‘. And these result values ​​are put in settlementAmount.

And the arithmetic operation values ​​are calculated in onBlurSettlementAmount.

  const [form, setForm] = useState({
    sign: "+",
    salePrice: "",
    manualSettlementAmount: "",
    settlementAmount: 0,
  })

  const onChangeSign = (event: React.ChangeEvent<HTMLSelectElement>) => {
    setForm({...form, sign: event.target.value}); 
  } 

  const onChangeSalePrice = (event: React.ChangeEvent<HTMLInputElement> | any) => {
  setForm({...form, salePrice: event.target.value});
  }

  const onChangeManualSettlementAmount = (event: React.ChangeEvent<HTMLInputElement> | any) => {
    setForm({...form, manualSettlementAmount: event.target.value });

  }

  const onBlurSettlementAmount = (event: React.ChangeEvent<HTMLInputElement> | any) => {

    if (form.sign == '+') {
      setForm({ ...form, settlementAmount: (Number(form.salePrice) + Number(form.manualSettlementAmount ))})
    } 
  
    if (form.sign == '-') {
      setForm({ ...form, settlementAmount: (Number(form.salePrice) - Number(form.manualSettlementAmount ))})
    }
    
  }

return (
 <>
       <select value={form.sign} onChange={onChangeSign}>
                  <option label="+" value={"+"}>+</option>
                  <option label="-" value={"-"}>-</option>
       </select>

      <input type="text" value={form.manualSettlementAmount} onChange={onChangeManualSettlementAmount} />
      
      <input type="text" value={form.salePrice} onChange={onChangeSalePrice} />      

      <input type="number" disabled={true} value={form.settlementAmount} onBlur={onBlurSettlementAmount} />
 </>
)

However, the value of settlementAmount in input continues to appear as an initial value of 0, and the arithmetic operation value is not displayed. I don’t know why.

After inputting both sign and salePrice, whenever I input the manualSettlementAmount value, I want the settlementAmount value to be displayed as well.. How should I handle it?

Is it not possible to do arithmetic operations in onBlur?