What are some good approach to convert a customer list with name, product, cost to a unique customer list with user, total product and spent?

Asking for feedback on my approach, no code required. Given a customer list – id, name, product, cost. I am trying to convert this list into a new list that is sorted in a way that it returns unique user, the user’s total number of products bought, and total spent.

My initial thought: Create a new object array, run a loop on each object and append user name, product, and cost, to the new array if user is not already in it. If user is already in the new array, find the user and increment the user’s total product by 1. Total spent will be added to the existing amount.

Language: JavaScript/React

I read that I could create an Object Array and push each Object (user) to it, and each user would have those 3 properties (excluding id because I assume its auto generated).

var sample = new Array();
sample.push(new Object());

Draft pseudo code for the the process:

let usersArr = new Array();
ogSet.forEach(userData=> {
   if (!(userData.name in usersArr[any].name)) {
      usersArr.push(userData)
   } else {
      usersArr[matchedUser].totalNumberOfProduct++;
      usersArr[matchedUser].totalSpent+= userData.cost
   }
}
...
// print out 
usersArr.map(user => {
   console.log(user.name)
   console.log(user.totalNumberOfProduct)
   console.log(user.totalSpent)
}

Original JSON array:

[
  {
    "id": "1",
    "name": "Bill",
    "product": "chair",
    "cost": "222"
  }.
  {
    "id": "2",
    "name": "Bill",
    "product": "sofa",
    "cost": "9999"
  },
  {
    "id": "3",
    "name": "Steve",
    "Product": "Monitor",
    "Cost": "555"
  }
]
...

Result:

[
  {
    "id": "1",
    "name": "Bill",
    "totalNumberOfProduct": "2",
    "totalSpent": "10221"
  }
]
...

Any feedback/suggestions on the way I tackle this? What are some ways to optimize speed and time? Algorithms and React specific methods are welcome.

Adding Google Ads Code in NextJS for Automatic Units

I’m working on a nextjs project and I have to implement the google AdSense code that is for automatic ads.

So, my google ad code is just this:

<script
  async
  src={`https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=${process.env.NEXT_PUBLIC_GOOGLE_ADSENSE}`}
  crossOrigin="anonymous"
/>

There is no specific ad unit code. Based on this script load, Google will automatically add the ads.

In such a case, how will I implement this in my NextJS project ensuring that the ads will continue to work with the route change?

Currently, the problem I see is that if I just place this in the _document.js head, the ads will load only on full reload. There are some tutorials describing how to implement google Adsense in NextJS, but they all describe the case when you have specific ad units created for Adsense, but not the case of automatic ads based on this script alone.

Will really appreciate any input on this.

ERORR after upgrading to Expo SDK 43 – Unable to resolve module @unimodules/core

After I upgraded from Expo SDK 40 to SDK 43 and did npm start I got this error "Unable to resolve module @unimodules/core".

I then checked my package.json and I didn’t have this package installed.

Any help will be greatly appreciated.

Full Error Stack Trace:

Warning: https://github.com/expo/react-native/archive/sdk-43.0.0.tar.gz is not a valid version. Version must be in the form of sdk-x.y.z. Please update your package.json file.
info Launching Dev Tools...
iOS Bundling failed 4235ms
Unable to resolve module @unimodules/core from /Users/user/path/to/project/node_modules/expo-linking/build/Linking.js: @unimodules/core could not be found within the project or in these directories:
  node_modules
  ../../../../node_modules

If you are sure the module exists, try these steps:
 1. Clear watchman watches: watchman watch-del-all
 2. Delete node_modules and run yarn install
 3. Reset Metro's cache: yarn start --reset-cache
 4. Remove the cache: rm -rf /tmp/metro-*
> 1 | import { Platform, UnavailabilityError } from '@unimodules/core';
    |                                                ^
  2 | import Constants from 'expo-constants';
  3 | import invariant from 'invariant';
  4 | import qs from 'qs';

Here is my package.json:

{
    "main": "node_modules/expo/AppEntry.js",
    "scripts": {
        "start": "expo start",
        "android": "expo start --android",
        "ios": "expo start --ios",
        "web": "expo start --web",
        "eject": "expo eject",
        "test": "jest"
    },
    "jest": {
        "preset": "jest-expo"
    },
    "dependencies": {
        "@react-native-async-storage/async-storage": "^1.13.3",
        "@react-native-community/art": "^1.2.0",
        "@react-native-community/datetimepicker": "3.0.4",
        "@react-native-community/masked-view": "0.1.10",
        "@react-native-community/netinfo": "5.9.7",
        "@react-native-community/push-notification-ios": "^1.2.2",
        "@react-native-community/slider": "3.0.3",
        "@react-navigation/native": "^5.1.4",
        "aws-amplify": "^3.3.1",
        "aws-amplify-react-native": "^4.2.6",
        "axios": "^0.19.2",
        "expo": "^43.0.0",
        "expo-app-loading": "^1.0.1",
        "expo-barcode-scanner": "~9.1.0",
        "expo-camera": "~9.1.0",
        "expo-constants": "~9.3.3",
        "expo-font": "~8.4.0",
        "expo-linking": "~2.0.1",
        "expo-mail-composer": "~9.0.0",
        "expo-notifications": "~0.8.2",
        "expo-permissions": "~10.0.0",
        "expo-secure-store": "~9.3.0",
        "expo-sqlite": "~8.5.0",
        "expo-updates": "~0.4.1",
        "expo-web-browser": "~8.6.0",
        "file-saver": "^2.0.2",
        "jsbarcode": "^3.11.3",
        "link": "^0.1.5",
        "qs": "^6.9.4",
        "react": "16.13.1",
        "react-dom": "16.13.1",
        "react-native": "https://github.com/expo/react-native/archive/sdk-43.0.0.tar.gz",
        "react-native-barcode-expo": "^1.1.1",
        "react-native-elements": "^3.2.0",
        "react-native-fs": "^2.16.6",
        "react-native-gesture-handler": "~1.8.0",
        "react-native-modal": "^11.5.6",
        "react-native-modal-datetime-picker": "^8.6.0",
        "react-native-paper": "^3.10.1",
        "react-native-push-notification": "^3.5.2",
        "react-native-reanimated": "~1.13.0",
        "react-native-router-flux": "^4.2.0",
        "react-native-safe-area-context": "3.1.9",
        "react-native-screens": "~2.15.2",
        "react-native-snap-carousel": "^3.9.1",
        "react-native-svg": "12.1.0",
        "react-native-web": "~0.13.12",
        "react-navigation-animated-switch": "^0.6.4",
        "react-navigation-drawer": "^2.4.11",
        "react-navigation-header-buttons": "^3.0.5",
        "react-router-dom": "^6.0.0-alpha.3"
    },
    "devDependencies": {
        "@babel/core": "^7.12.9",
        "@babel/runtime": "^7.9.2",
        "@react-native-community/eslint-config": "^0.0.7",
        "babel-jest": "^25.1.0",
        "babel-preset-expo": "8.5.1",
        "eslint": "^6.8.0",
        "expo-cli": "^4.12.8",
        "jest": "^25.5.4",
        "jest-expo": "~43.0.1",
        "metro-react-native-babel-preset": "^0.59.0",
        "react-test-renderer": "^16.13.1"
    },
    "private": true
}

I am facing this problem while running react application. how to solve this issue?

Error: Cannot find module ‘E:10th semesteroop2(C#)After_Semesterreact6my-appdemonode_modulesbabel-loaderlibindex.js’
Require stack:

  • E:10th semesteroop2(C#)After_Semesterreact6my-appdemonode_modulesloader-runnerlibloadLoader.js
  • E:10th semesteroop2(C#)After_Semesterreact6my-appdemonode_modulesloader-runnerlibLoaderRunner.js
  • E:10th semesteroop2(C#)After_Semesterreact6my-appdemonode_moduleswebpacklibNormalModule.js
  • E:10th semesteroop2(C#)After_Semesterreact6my-appdemonode_moduleswebpack-manifest-plugindistindex.js
  • E:10th semesteroop2(C#)After_Semesterreact6my-appdemonode_modulesreact-scriptsconfigwebpack.config.js
  • E:10th semesteroop2(C#)After_Semesterreact6my-appdemonode_modulesreact-scriptsscriptsbuild.js

Accessing iframe context with Electron

I have an Electron app where I load external sites into a BrowswerView hosted in a BrowserWindow. Invariably each site has a video player on it using a <video> tag. Normally you can access the DOM using executeJavaScript and do things like this:

document.querySelectorAll('video').forEach(input => { input.pause() })

This would pause all the playing video on the site.
Problem is, one particular pesky site loads the video player into an iframe that is in a different sub domain.

Enter CORS. I cannot get to the video container without hitting the dreaded Blocked a frame with origin "https://www.whatever.com" from accessing a cross-origin frame.

Here is my question: In the chrome dev tools you can select the context from a drop down so clearly it is possible to choose the context from the client. As I am running this in Electron I would like to believe that there is a way to switch contexts. I am not looking to run the code cross origin but directly in the frame I just need a way to choose it.

I looked at mainFrame.frames but I don’t see how you get to the sub frame’s webContents.

Any clues on this?

Is there a way to do speech recognition using p5.js or javascript?

There are many ways you can check the volume of the microphone in p5.js and there is a .AudioIn function to receive data from the mic, but can I use p5.js to do speech recognition(speech-to-text and text-to-speech).

Why am I asking

I am asking this because I need a way to access the client’s microphone using javascript and then convert it using javascript to text and then transfer that to a python flask app server to use that client’s speech recognition to do different things and give prompts(which would also use the speaker, which is text-to-speech) on the flask website. So, is there a way to do that using p5.js or do I need another piece of javascript code?

I am having problemas with responsive design on iPhone XR

So, I have this website: https://projeto-jogo-memoria.vercel.app/

I asked some friends to test it and one of them has an iPhone XR. According to the internet iPhone XR’s screen width is 414 pixels.

If I open it on dev tools, it works fine: https://i.imgur.com/NWBND0c.png

But this is how it shows up on the phone: https://i.imgur.com/YVZU2gw.jpg

I noticed the margin between circles is a lot bigger, but I don’t know why this is happening. Could you guys help me?

This is the code:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- displays site properly based on user's device -->

<link rel="icon" type="image/png" sizes="32x32" href="/images/3286079.png">

<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/styles.css" rel="stylesheet">
<link href="css/all.css" rel="stylesheet">

<title>Jogo da Memória</title>


</head>
<!--navbar principal-->
<nav class="pse-xs p-3 ps-5 pe-5 navbar navbar-light">
    <span style="font-size: 1.2em;" class="pb-1">
        <p class="text-darkgray m-0">memory</p>
    </span>
    <span class="m-0">
        <button class="btn-custom btn-restart display-xs me-3 mb-2"
            style="font-size: 0.8em; width: calc(60px + 10vw)" type="button" onclick="reiniciarJogo()">
            Reiniciar
        </button>
        <button class="btn-custom btn-playagain display-xs" style="font-size: 0.8em; width: calc(60px + 10vw)"
            type="button" onclick="redefinirPreferencias()">
            Novo Jogo
        </button>
    </span>

</nav>

<!--modal que impede cliques quando necessário-->
<div id="impedir_click" class="modal-impedir-click">

</div>



<!--modal das configurações do jogo-->
<div id="modal_iniciar" class="modal-iniciar">

    <div class="modal-iniciar-content p-4 p-sm-5 p-md-5 p-lg-5 p-xl-5">

        <p style="position: absolute; bottom: 105%; left: calc(50% - 31.5px)" class="text-lightgray text-center">
            memory</p>

        <form action="" method="POST">

            <p class="mb-2 mb-sm-4 text-darkgray">Selecionar Tema</p>
            <div class="mb-3 mb-sm-3 mb-md-3 mb-lg-4 mb-xl-4 mb-xxl-5 text-center">
                <input class="input-radio btn-check" type="radio" id="temas_1" name="tema" value="1">
                <label style="width: 40%;" class="btn-radiobox" for="temas_1">Números</label>

                <input class="input-radio btn-check" type="radio" id="temas_2" name="tema" value="2">
                <label style="width: 40%;" class="btn-radiobox" for="temas_2">Icones</label>
            </div>


            <p class="mb-2 mb-sm-4 text-darkgray">Selecionar Quantidade de Jogadores</p>
            <div class="mb-3 mb-sm-3 mb-md-3 mb-lg-4 mb-xl-4 mb-xxl-5 text-center">
                <input class="input-radio btn-check" type="radio" id="jogadores_1" name="qtd_jogadores" value="1">
                <label class="btn-radiobox" for="jogadores_1">1</label>

                <input class="input-radio btn-check" type="radio" id="jogadores_2" name="qtd_jogadores" value="2">
                <label class="btn-radiobox" for="jogadores_2">2</label>

                <input class="input-radio btn-check" type="radio" id="jogadores_3" name="qtd_jogadores" value="3">
                <label class="btn-radiobox" for="jogadores_3">3</label>

                <input class="input-radio btn-check" type="radio" id="jogadores_4" name="qtd_jogadores" value="4">
                <label class="btn-radiobox" for="jogadores_4">4</label>
            </div>


            <p class="mb-2 mb-sm-4 text-darkgray">Selecionar Tamanho do Tabuleiro</p>
            <div class="mb-3 mb-sm-3 mb-md-3 mb-lg-4 mb-xl-4 mb-xxl-5 text-center">
                <input class="input-radio btn-check" type="radio" id="tamanho_1" name="tamanho_tabuleiro" value="4">
                <label style="width: 40%;" class="btn-radiobox" for="tamanho_1">4x4</label>

                <input class="input-radio btn-check" type="radio" id="tamanho_2" name="tamanho_tabuleiro" value="6">
                <label style="width: 40%;" class="btn-radiobox" for="tamanho_2">6x6</label>
            </div>

            <div class="text-center">
                <button type="button" onclick="novoJogo()" class="btn-custom btn-start">
                    Jogar
                </button>
            </div>

        </form>

    </div>
</div>

<!--campo dos cartões e jogadores-->
<div class="container">
    <!--cartões-->
    <div id="tabuleiro" class="row mb-3 mb-sm-4 mb-xl-3 mb-xll-5">
    </div>

    <!--jogadores-->
    <div class="row">
        <div id="jogadores" class="players-container mb-2 col-12 ps-4 pe-4">
            <div id="jogador_1" class="player-container p-2 p-sm-3">
                <p class="m-0 d-inline-block d-md-none">P1</p>
                <p class="m-0 d-none d-md-inline-block">Jogador1</p>
                <p class="m-0 ms-2 d-inline-block">0</p>
            </div>


        </div>
    </div>
</div>

<!--campo de fim de jogo-->
<div style="display: none; background-color: #ffffff77;" id="modal_vencedor" class="modal-impedir-click">
    <div class="modal-iniciar-content modal-fim d-flex justify-content-center p-5">

        <div class="modal-fim-content text-center" style="width: 80vw;">
            <div class="mb-5">
                <span style="font-size: 1.8em;">
                    <p class="text-darkgray m-0">VENCEDOR</p>
                </span>
                <span style="font-size: 1.8em;">
                    <p id="vencedor" class="text-darkgray m-0">NOME</p>
                </span>
            </div>

            <div>
                <button class="btn-custom btn-restart d-inline-block mb-2" style="width: calc(100px + 10vw)"
                    type="button" onclick="reiniciarJogo()">
                    Reiniciar
                </button>
                <button class="btn-custom btn-playagain d-inline-block" style="width: calc(100px + 10vw)"
                    type="button" onclick="redefinirPreferencias()">
                    Novo Jogo
                </button>
            </div>
        </div>

    </div>
</div>









<div class="attribution">
    Challenge by <a href="https://www.frontendmentor.io?ref=challenge" target="_blank">Frontend Mentor</a>.
    Coded by <a href="#">Luan Peixoto Jardim</a>.
</div>


<script src="js/jquery-3.6.0.js"></script>
<script src="js/bootstrap.bundle.js"></script>
<script src="js/script.js"></script>
</body>

path.js:25 Uncaught ReferenceError: process is not defined (React APP Error)

i hope that you all are well. Im having this issue: after trying to fix a previous error (Uncaught Error: Module build failed (from ./node_modules/source-map-loader/dist/cjs.js)) i finally handle it using npm install. But after that I see this error in the console: path.js:25 Uncaught ReferenceError: process is not defined
enter image description here

The error is located here:
enter image description here

My dependencies are:

enter image description here

enter image description here

Console errors:

[1] WARNING in ./node_modules/express/lib/view.js 74:13-25
[1] Critical dependency: the request of a dependency is an expression
[1]  @ ./node_modules/express/lib/application.js 26:11-28
[1]  @ ./node_modules/express/lib/express.js 19:12-36
[1]  @ ./node_modules/express/index.js 10:0-41
[1]  @ ./src/pages/LogIn.js 6:0-35
[1]  @ ./src/App.js 8:0-34 34:40-45
[1]  @ ./src/index.js 9:0-24 15:35-38
[1]
[1] 1 warning has detailed information that is not shown.
[1] Use 'stats.errorDetails: true' resp. '--stats-error-details' to show it.
[1]
[1] ERROR in ./node_modules/cookie-signature/index.js 4:13-30
[1] Module not found: Error: Can't resolve 'crypto' in 'C:UserstatupDesktopGrowAppfrontendnode_modulescookie-signature'
[1] 
[1] BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
[1] This is no longer the case. Verify if you need this module and configure a polyfill for it.
[1]
[1] If you want to include a polyfill, you need to:
[1]     - add a fallback 'resolve.fallback: { "crypto": require.resolve("crypto-browserify") }'
[1]     - install 'crypto-browserify'
[1] If you don't want to include a polyfill, you can use an empty module like this:
[1]     resolve.fallback: { "crypto": false }
[1]  @ ./node_modules/express/lib/response.js 35:11-43
[1]  @ ./node_modules/express/lib/express.js 27:10-31
[1]  @ ./node_modules/express/index.js 10:0-41
[1]  @ ./src/pages/LogIn.js 6:0-35
[1]  @ ./src/App.js 8:0-34 34:40-45
[1]  @ ./src/index.js 9:0-24 15:35-38
[1]
[1] ERROR in ./node_modules/destroy/index.js 12:17-41
[1] Module not found: Error: Can't resolve 'fs' in 'C:UserstatupDesktopGrowAppfrontendnode_modulesdestroy'
[1]  @ ./node_modules/send/index.js 19:14-32
[1]  @ ./node_modules/express/lib/response.js 45:11-26
[1]  @ ./node_modules/express/lib/express.js 27:10-31
[1]  @ ./node_modules/express/index.js 10:0-41
[1]  @ ./src/pages/LogIn.js 6:0-35
[1]  @ ./src/App.js 8:0-34 34:40-45
[1]  @ ./src/index.js 9:0-24 15:35-38
[1]
[1] ERROR in ./node_modules/etag/index.js 18:13-30
[1] Module not found: Error: Can't resolve 'crypto' in 'C:UserstatupDesktopGrowAppfrontendnode_modulesetag'
[1] 
[1] BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
[1] This is no longer the case. Verify if you need this module and configure a polyfill for it.
[1]
[1] If you want to include a polyfill, you need to:
[1]     - add a fallback 'resolve.fallback: { "crypto": require.resolve("crypto-browserify") }'
[1]     - install 'crypto-browserify'
[1] If you don't want to include a polyfill, you can use an empty module like this:
[1]     resolve.fallback: { "crypto": false }
[1]  @ ./node_modules/express/lib/utils.js 25:11-26
[1]  @ ./node_modules/express/lib/application.js 30:18-48 32:25-62 34:19-50
[1]  @ ./node_modules/express/lib/express.js 19:12-36
[1]  @ ./node_modules/express/index.js 10:0-41
[1]  @ ./src/pages/LogIn.js 6:0-35
[1]  @ ./src/App.js 8:0-34 34:40-45
[1]  @ ./src/index.js 9:0-24 15:35-38
[1]
[1] ERROR in ./node_modules/etag/index.js 20:12-31
[1] Module not found: Error: Can't resolve 'fs' in 'C:UserstatupDesktopGrowAppfrontendnode_modulesetag' 
[1]  @ ./node_modules/express/lib/utils.js 25:11-26
[1]  @ ./node_modules/express/lib/application.js 30:18-48 32:25-62 34:19-50
[1]  @ ./node_modules/express/lib/express.js 19:12-36
[1]  @ ./node_modules/express/index.js 10:0-41
[1]  @ ./src/pages/LogIn.js 6:0-35
[1]  @ ./src/App.js 8:0-34 34:40-45
[1]  @ ./src/index.js 9:0-24 15:35-38
[1]
[1] ERROR in ./node_modules/express/lib/application.js 28:11-26
[1] Module not found: Error: Can't resolve 'http' in 'C:UserstatupDesktopGrowAppfrontendnode_modulesexpresslib'
[1] 
[1] BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
[1] This is no longer the case. Verify if you need this module and configure a polyfill for it.
[1]
[1] If you want to include a polyfill, you need to:
[1]     - add a fallback 'resolve.fallback: { "http": require.resolve("stream-http") }'
[1]     - install 'stream-http'
[1] If you don't want to include a polyfill, you can use an empty module like this:
[1]     resolve.fallback: { "http": false }
[1]  @ ./node_modules/express/lib/express.js 19:12-36
[1]  @ ./node_modules/express/index.js 10:0-41
[1]  @ ./src/pages/LogIn.js 6:0-35
[1]  @ ./src/App.js 8:0-34 34:40-45
[1]  @ ./src/index.js 9:0-24 15:35-38
[1]
[1] ERROR in ./node_modules/express/lib/request.js 18:11-30
[1] Module not found: Error: Can't resolve 'net' in 'C:UserstatupDesktopGrowAppfrontendnode_modulesexpresslib'
[1]  @ ./node_modules/express/lib/express.js 25:10-30
[1]  @ ./node_modules/express/index.js 10:0-41
[1]  @ ./src/pages/LogIn.js 6:0-35
[1]  @ ./src/App.js 8:0-34 34:40-45
[1]  @ ./src/index.js 9:0-24 15:35-38
[1]
[1] ERROR in ./node_modules/express/lib/request.js 22:11-26
[1] Module not found: Error: Can't resolve 'http' in 'C:UserstatupDesktopGrowAppfrontendnode_modulesexpresslib'
[1] 
[1] BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
[1] This is no longer the case. Verify if you need this module and configure a polyfill for it.
[1]
[1] If you want to include a polyfill, you need to:
[1]     - add a fallback 'resolve.fallback: { "http": require.resolve("stream-http") }'
[1]     - install 'stream-http'
[1] If you don't want to include a polyfill, you can use an empty module like this:
[1]     resolve.fallback: { "http": false }
[1]  @ ./node_modules/express/lib/express.js 25:10-30
[1]  @ ./node_modules/express/index.js 10:0-41
[1]  @ ./src/pages/LogIn.js 6:0-35
[1]  @ ./src/App.js 8:0-34 34:40-45
[1]  @ ./src/index.js 9:0-24 15:35-38
[1]
[1] ERROR in ./node_modules/express/lib/response.js 23:11-26
[1] Module not found: Error: Can't resolve 'http' in 'C:UserstatupDesktopGrowAppfrontendnode_modulesexpresslib'
[1] 
[1] BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
[1] This is no longer the case. Verify if you need this module and configure a polyfill for it.
[1]
[1] If you want to include a polyfill, you need to:
[1]     - add a fallback 'resolve.fallback: { "http": require.resolve("stream-http") }'
[1]     - install 'stream-http'
[1] If you don't want to include a polyfill, you can use an empty module like this:
[1]     resolve.fallback: { "http": false }
[1]  @ ./node_modules/express/lib/express.js 27:10-31
[1]  @ ./node_modules/express/index.js 10:0-41
[1]  @ ./src/pages/LogIn.js 6:0-35
[1]  @ ./src/App.js 8:0-34 34:40-45
[1]  @ ./src/index.js 9:0-24 15:35-38
[1]
[1] ERROR in ./node_modules/express/lib/view.js 18:9-22
[1] Module not found: Error: Can't resolve 'fs' in 'C:UserstatupDesktopGrowAppfrontendnode_modulesexpresslib'
[1]  @ ./node_modules/express/lib/application.js 26:11-28
[1]  @ ./node_modules/express/lib/express.js 19:12-36
[1]  @ ./node_modules/express/index.js 10:0-41
[1]  @ ./src/pages/LogIn.js 6:0-35
[1]  @ ./src/App.js 8:0-34 34:40-45
[1]  @ ./src/index.js 9:0-24 15:35-38
[1]
[1] ERROR in ./node_modules/mime/mime.js 3:9-22
[1] Module not found: Error: Can't resolve 'fs' in 'C:UserstatupDesktopGrowAppfrontendnode_modulesmime' 
[1]  @ ./node_modules/send/index.js 31:11-26
[1]  @ ./node_modules/express/lib/response.js 45:11-26
[1]  @ ./node_modules/express/lib/express.js 27:10-31
[1]  @ ./node_modules/express/index.js 10:0-41
[1]  @ ./src/pages/LogIn.js 6:0-35
[1]  @ ./src/App.js 8:0-34 34:40-45
[1]  @ ./src/index.js 9:0-24 15:35-38
[1]
[1] ERROR in ./node_modules/send/index.js 29:9-22
[1] Module not found: Error: Can't resolve 'fs' in 'C:UserstatupDesktopGrowAppfrontendnode_modulessend' 
[1]  @ ./node_modules/express/lib/response.js 45:11-26
[1]  @ ./node_modules/express/lib/express.js 27:10-31
[1]  @ ./node_modules/express/index.js 10:0-41
[1]  @ ./src/pages/LogIn.js 6:0-35
[1]  @ ./src/App.js 8:0-34 34:40-45
[1]  @ ./src/index.js 9:0-24 15:35-38
[1]
[1] ERROR in ./node_modules/zlib/lib/zlib.js
[1] Module build failed (from ./node_modules/source-map-loader/dist/cjs.js):
[1] Error: ENOENT: no such file or directory, open 'C:UserstatupDesktopGrowAppfrontendnode_moduleszliblibzlib.js'
[1]  @ ./node_modules/body-parser/lib/read.js 20:11-26
[1]  @ ./node_modules/body-parser/lib/types/json.js 21:11-29
[1]  @ ./node_modules/body-parser/index.js 134:15-42
[1]  @ ./node_modules/express/lib/express.js 13:17-39
[1]  @ ./node_modules/express/index.js 10:0-41
[1]  @ ./src/pages/LogIn.js 6:0-35
[1]  @ ./src/App.js 8:0-34 34:40-45
[1]  @ ./src/index.js 9:0-24 15:35-38
[1]
[1] 11 errors have detailed information that is not shown.
[1] Use 'stats.errorDetails: true' resp. '--stats-error-details' to show it.
[1]
[1] webpack 5.66.0 compiled with 12 errors and 1 warning in 277 ms

What I have tried:

  • Remove node_modules and package-lock and re-running npm install
  • Remove package path, dotenv
  • Downgrading react-script to v4.0.7 and adding to devdep “react-error-overlay”: “^6.0.9”
  • Installing some of the modules showed on console errors

If anyone can help me I would be very glad, I cant find a way to fix this or why this is happening.

Autoplay next video for page inertia js & vue

How can I keep the Player component (vue-plyr), reactive page?

autoplay similar to youtube/netflix, advance the video to the next by changing the page, in fullscreen too.

Show.vue

methods: {
    nextVideo() {
      console.log("next video");
      Inertia.visit("/videos/" + this.plyr.next, {
        preserveScroll: false,
        preserveState: true,
      });
    },
  },

I added setInterval and clearInterval, but advancing the video works 1 first time, the second time it works, but after that it doesn’t work anymore

it only works the first time

Player.vue

<template>
  <vue-plyr ref="plyr">
    <video crossorigin playsinline data-poster=""></video>
  </vue-plyr>
</template>

<script>
import Ply from "plyr";
export default {
  name: "Player",
  props: {
    src: {
      type: String,
    },
    poster: {
      type: String,
    },
    markers: {
      type: Array,
    },
    title: {
      type: String,
    },
    subtitles: {
      type: Array,
    },
  },
  data() {
    return {
      player: null,
      isEnded: false,
      octopus: null,
      timerCircular: 0,
      timerLabel: 5,
    };
  },
  mounted() {
    this.player = this.$refs.plyr.player;
    this.player.source = {
      type: "video",
      sources: [
        {
          src: this.src,
          type: "video/mp4",
        },
      ],
    };

    this.player.on("playing", () => console.log("player started"));
    this.player.on("pause", () => console.log("player paused"));
    this.player.on("ended", this.ended);
  },
  beforeDestroy() {
    this.player.destroy();
  },
  watch: {
    src() {
      this.player.source = {
        type: "video",
        sources: [
          {
            src: this.src,
            type: "video/mp4",
          },
        ],
      };
      this.player.on("ready", () => {
        this.player.play();
      });
    },
  },
  methods: {
    ended() {
      this.isEnded = true;

      const timerLabel = setInterval(() => {
        console.log(this.timerLabel);
        this.timerLabel -= 1;
        if (this.timerLabel == 0) {
          clearInterval(timerLabel);
          clearInterval(timerCircular);
          this.$parent.$parent.nextVideo();
          this.isEnded = false;
          this.timerCircular = 0;
          this.timerLabel = 5;
        }
      }, 1000);

      const timerCircular = setInterval(() => {
        this.timerCircular += 5;
      }, 200);
    },
  },
};
</script>

<style lang="scss" scoped>
</style>

React Hook “useForecast” is called in function “getSearch” that is neither a React function component nor a custom React Hook function

React Newbie Here!

I have been running into the same issue over and over again with a React weather dashboard project I have been working on. I am focusing on connecting the submit functions and the forecast function I have created to retrieve the json data from the OpenWeatherMap API I am using. Upon utilizing a callback function I have created (to grab the searched city value from the child component), the error that is listed above is thrown. As I have not intended the callback function ‘getSearch’ to be a function component or a custom React Hook, I have no clue what else to try to fix this error. Below is all of my code for my Parent component ‘overview.js’ and the child component ‘recentSearches.js’:

overview.js

import React, {useState} from 'react';
import './overview.css';
import { RecentSearches } from '../Recent Searches/recentSearches';
import { Hourly } from '../Hourly/hourly';
import { Fiveday } from '../5 Day Forecast/fiveday';

require('dotenv').config(); 

const useForecast = async (city) => {

    // const api_key = process.env.API_KEY;
    const api_key = '2220f5a5d83243938f764759211310';
    var BASE_URL = `http://api.weatherapi.com/v1/forecast.json?key=${api_key}&q=${city}&days=3&aqi=no&alerts=no`;

    const response = await fetch(BASE_URL);
    const data = await response.json();
    console.log(data);
    // collects all of the current weather info for your search
    const currentTempInfo = {
        city: data.location.name, 
        state: data.location.region, 
        epochDate: data.location.localtime_epoch, 
        message: data.current.condition.text, 
        wicon: data.current.condition.icon, 
        currentTemp: data.current.temp_f,
        currentHighTemp: data.forecast.forecastday[0].day.maxtemp_f,
        currentLowTemp: data.forecast.forecastday[0].day.mintemp_f,
        feelsLike: data.current.feelslike_f,
        humidity: data.current.humidity,
        rainLevel: data.current.precip_in,
        // hourlyTemps is an array, starts from midnight(index 0) and goes every hour until 11 pm(index 23)
        hourlyTemps: data.forecast.forecastday[0].hour.map((entry) => {
            let epochTime, temp;
            [epochTime, temp] = [entry.time_epoch, entry.temp_f];
            return [epochTime, temp];
        })
    };
    const daycardInfo = [];

    // this for loop triggers and creates an array with all necessary values for the 
    for (var x in data) {
        const fcDayDates = data.forecast.forecastday[x].date_epoch;
        const dayInfo = data.forecast.forecastday[x].day; 
        const dayValues = {
            dates: fcDayDates, 
            message: dayInfo.condition.text, 
            wicon: dayInfo.condition.icon, 
            maxTemp: dayInfo.maxtemp_f, 
            minTemp: dayInfo.mintemp_f, 
            avgTemp: dayInfo.avgtemp_f
        };
        // pushes dayValues object into daycardInfor array
        daycardInfo.push(dayValues);    
    };

    // this updates the state with the forecast for the city entered
    data = {
        currentTempInfo: currentTempInfo,
        daycardInfo: daycardInfo
    };

    // this spits out the newly created forecast object
    return data;
};

export function Overview() {
    const [search, setSearch] = useState(null);

    // 
    const getSearch = (searchedCity) => {
        setSearch(searchedCity);
        useForecast(search);
    };

    return (
        <div>
            <div class='jumbotron' id='heading-title'>
                <h1>Welcome to <strong>Weathered</strong>!</h1>
                <h3>A Simple Weather Dashboard </h3>
            </div>

            <div class='container-fluid' id='homepage-skeleton'>
                <div class='d-flex' id='center-page'>
                    <RecentSearches callback={callback}/>
        
                    <Hourly />
                </div>
            </div>

            <Fiveday />        
        </div>
    )
};

recentSearches.js

import React, {useState} from 'react';
import './recentSearches.css';

export function RecentSearches({getSearch}) {
    const [city, setCity] = useState('');
    const [recents, setRecents] = useState([]);

    const onSubmit = e => {
        e.preventDefault();
        
        if (!city || city === '') {
            return;
        } else {
            addRecent(city);
            getSearch(city);
        }  
    }
 
    const onChange = (e) => {
        setCity(e.target.value);
    }; 

    // function which takes in searched entry and adds entry to recent searches array
    function addRecent(newSearch) {
        if (recents.includes(newSearch)) {
            return;
        } else {
            setRecents((prev) => [newSearch, ...prev]);
        }
        // clear our search bar entry
        setCity('');
    }; 

    const searchAgain = (e) => {
        const recent = e.target.innerHTML;
        setCity(recent);
    }
    
    return (
        <section id='search-bar-recents'>
            <h3 class='m-3'>Recents </h3>
            <div id='insert-recent-buttons'>{recents.map((entry, index) => <h5 key={index} onClick={searchAgain} value={entry}>{entry}</h5>)}</div>

            <form onSubmit={onSubmit} class="m-3">
                <label className="form-label" for="search-bar">Search A City</label><br/>
                <input className='form-text' id="search-bar" type='text' value={city} placeholder="Las Vegas, etc." onChange={onChange}/>
                <input className='form-button' id='search-button' type='submit' value='Search'/>
            </form>
        </section>
    )
};

Any help/tips/notes are appreciated! Thanks!

Cannot access ‘Agent’ before initialization [duplicate]

Hello its my frist time using canvas with this type of code… i don’t understand why the error happens, if you could help me know why this is not working… they say the agent could not be found on start of the read… anyway its trying all the time to have a solution . but it expend hours for me to nothing..

const randomRange = (min,max) => {
    return Math.random() * (max - min) + min;
}
//code
var c = document.getElementById("canvastarget");

var width  = c.offsetWidth
var height = c.offsetHeight

var context = c.getContext("2d");

//content

var numberofelements = 40
    const agents = []

    for (let index = 0; index < numberofelements; index++){

        const x = randomRange(0, width)
        const y = randomRange(0, height)

        agents.push(new Agent(x, y))
    }



//classes
class Point {
    constructor(x,y){
        this.x = x
        this.y = y
    }
}

class Agent{

    constructor(x, y) {

        this.pos = new Point(x,y)
        this.radius = 10
        
    }

    draw(context) {
        context.fillStyle = "black"
        
        context.beginPath()
        context.arc(this.pos.x,this.pos.y,this.radius,0,Match.PI * 2);
        context.fill();
    }
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <canvas id= canvastarget width = "1080px" height="1080px"></canvas>    
</body>

</html>

The error is not clear for me its my first time doing class!

How to access Vuex 4 store from from Vue 3 app?

I am building a frontend app using Vue, Vuex, and Vue Router. My goals is to access authentication module imported from the different JS file so that it can change logged in state and save JWT token on frontend. But the problem is I am getting an error ncaught TypeError: Cannot read properties of undefined (reading '$store') when submitting the user registration request and try to access the state store.

My project currently

My app’s dependencies section package.json are:


      "dependencies": {
        "@vuelidate/core": "^2.0.0-alpha.34",
        "@vuelidate/validators": "^2.0.0-alpha.26",
        "axios": "^0.25.0",
        "core-js": "^3.6.5",
        "primeflex": "^3.1.2",
        "primeicons": "^5.0.0",
        "primevue": "^3.10.0",
        "vue": "^3.0.0",
        "vue-router": "^4.0.0-0",
        "vuex": "^4.0.0-0"
      },

My project structure so far is:

Project frontend structure

My main.js:


    import { createApp } from 'vue'
    import App from './App.vue'
    import PrimeVue from 'primevue/config';
    import router from './router'
    import store from './store'
    
    import "primevue/resources/themes/saga-blue/theme.css";
    import "primevue/resources/primevue.min.css";
    import "primeicons/primeicons.css";
    import Button from "primevue/button";
    import Dialog from 'primevue/dialog';
    import InputText from 'primevue/inputtext';
    import Password from 'primevue/password';
    import Divider from 'primevue/divider';
    
    const app = createApp(App);
    app.use(store)
    app.use(router)
    app.use(PrimeVue)
    app.component("Button", Button)
    app.component("Dialog", Dialog)
    app.component("InputText", InputText)
    app.component("Password", Password)
    app.component("Divider", Divider)
    
    app.mount('#app')

My store/index.js


    import { createStore } from 'vuex'
    import { auth } from "./auth.module";
    
    export default createStore({
        state: {
        },
        mutations: {
        },
        actions: {
        },
        modules: {
            auth
        }
    })

My auth.module.js:


    import AuthService from '../services/auth.service';
    
    const user = JSON.parse(localStorage.getItem('user'));
    const initialState = user
        ? { status: { loggedIn: true }, user }
        : { status: { loggedIn: false }, user: null };
    
    export const auth = {
        namespaced: true,
        state: initialState,
        actions: {
            login({ commit }, user) {
                return AuthService.login(user).then(
                    user => {
                        commit('loginSuccess', user);
                        return Promise.resolve(user);
                    },
                    error => {
                        commit('loginFailure');
                        return Promise.reject(error);
                    }
                );
            },
            logout({ commit }) {
                AuthService.logout();
                commit('logout');
            },
            register({ commit }, user) {
                return AuthService.register(user).then(
                    response => {
                        commit('registerSuccess');
                        return Promise.resolve(response.data);
                    },
                    error => {
                        commit('registerFailure');
                        return Promise.reject(error);
                    }
                );
            }
        },
        mutations: {
            loginSuccess(state, user) {
                state.status.loggedIn = true;
                state.user = user;
            },
            loginFailure(state) {
                state.status.loggedIn = false;
                state.user = null;
            },
            logout(state) {
                state.status.loggedIn = false;
                state.user = null;
            },
            registerSuccess(state) {
                state.status.loggedIn = false;
            },
            registerFailure(state) {
                state.status.loggedIn = false;
            }
        }
    };

My Register.vue component:


    <template>
        <div >
            <div class="form-demo">
                <Dialog v-model:visible="showMessage" :breakpoints="{ '960px': '80vw' }" :style="{ width: '30vw' }" position="top">
                    <div class="flex align-items-center flex-column pt-6 px-3">
                        <i class="pi pi-check-circle" :style="{fontSize: '5rem', color: 'var(--green-500)' }"></i>
                        <h5>Registration Successful!</h5>
                        <p :style="{lineHeight: 1.5, textIndent: '1rem'}">
                            Your account is registered under name <b>{{state.name}}</b>
                        </p>
                    </div>
                    <template #footer>
                        <div class="flex justify-content-center">
                            <Button label="OK" @click="toggleDialog" class="p-button-text" />
                        </div>
                    </template>
                </Dialog>
    
                <div class="flex justify-content-center">
                    <div class="card">
                        <h5 class="text-center">Register</h5>
                        <form @submit.prevent="handleSubmit(!v$.$invalid)" class="p-fluid">
                            <div class="field">
                                <div class="p-float-label">
                                    <InputText id="name" v-model="v$.name.$model" :class="{'p-invalid':v$.name.$invalid && submitted}" />
                                    <label for="name" :class="{'p-error':v$.name.$invalid && submitted}">Name*</label>
                                </div>
                                <small v-if="(v$.name.$invalid && submitted) || v$.name.$pending.$response" class="p-error">{{v$.name.required.$message.replace('Value', 'Name')}}</small>
                            </div>
    
                            <div class="field">
                                <div class="p-float-label">
                                    <Password id="password" v-model="v$.password.$model" :class="{'p-invalid':v$.password.$invalid && submitted}" toggleMask>
                                        <template #header>
                                            <h6>Pick a password</h6>
                                        </template>
                                        <template #footer="sp">
                                            {{sp.level}}
                                            <Divider />
                                            <p class="mt-2">Suggestions</p>
                                            <ul class="pl-2 ml-2 mt-0" style="line-height: 1.5">
                                                <li>At least one lowercase</li>
                                                <li>At least one uppercase</li>
                                                <li>At least one numeric</li>
                                                <li>Minimum 8 characters</li>
                                            </ul>
                                        </template>
                                    </Password>
                                    <label for="password" :class="{'p-error':v$.password.$invalid && submitted}">Password*</label>
                                </div>
                                <small v-if="(v$.password.$invalid && submitted) || v$.password.$pending.$response" class="p-error">{{v$.password.required.$message.replace('Value', 'Password')}}</small>
                            </div>
                            <Button type="submit" label="Submit" class="mt-2" />
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </template>
    
    <script>
    import { reactive, ref } from 'vue';
    import { required } from "@vuelidate/validators";
    import { useVuelidate } from "@vuelidate/core";
    import '/node_modules/primeflex/primeflex.css';
    import User from '../models/user';
    
    export default {
        name: "Register",
        setup() {
    
            const state = reactive({
                name: '',
                password: '',
            });
    
            const rules = {
                name: { required },
                password: { required },
            };
    
            const submitted = ref(false);
            const showMessage = ref(false);
    
            const v$ = useVuelidate(rules, state);
    
            const handleSubmit = (isFormValid) => {
                submitted.value = true;
    
                if (!isFormValid) {
                    return;
                } else {
                    let user = new User('', '');
                    user.username = state.name;
                    user.password = state.password;
                    this.$store.dispatch('auth/register', this.user).then(
                            data => {
                                this.message = data.message;
                                // this.successful = true;
                            },
                            error => {
                                this.message =
                                        (error.response && error.response.data) ||
                                        error.message ||
                                        error.toString();
                                // this.successful = false;
                            }
                    );
                }
    
                toggleDialog();
            }
            const toggleDialog = () => {
                showMessage.value = !showMessage.value;
    
                if(!showMessage.value) {
                    resetForm();
                }
            }
            const resetForm = () => {
                state.name = '';
                state.password = '';
                submitted.value = false;
            }
    
            return { state, v$, handleSubmit, toggleDialog, submitted, showMessage }
        }
    }
    </script>

I followed this JWT with Vue and Spring tutorial for authentication logic and PrimeVue validation for Register component but tweaked to fit my project API spec.

Problem

When I hit submit user registration button, I get an error from runtime-core.esm-bundler.js?5c40:218:


    Uncaught TypeError: Cannot read properties of undefined (reading '$store')
    at Proxy.handleSubmit (Register.vue?73cf:105:1)
    at eval (Register.vue?73cf:22:1)
    at eval (runtime-dom.esm-bundler.js?830f:1463:1)
    at callWithErrorHandling (runtime-core.esm-bundler.js?5c40:155:1)
    at callWithAsyncErrorHandling (runtime-core.esm-bundler.js?5c40:164:1)
    at HTMLFormElement.invoker (runtime-dom.esm-bundler.js?830f:363:1)

I created my project using Vue CLI command vue create frontend with manual setting. I included Vuex and Vue Router in the initial setup.

Attempt tried so far

I rolled back my store directory to initial version which is almost the same as what vue cli vue create command initialised for me. I deleted my store/auth.module.js and just inserted one line in store/index.js:


    import { createStore } from 'vuex'
    import { auth } from "./auth.module";
    
    export default createStore({
      state: {
        count: 0
      },
      mutations: {
      },
      actions: {
      },
      modules: {
      }
    })

Then, inside handleSubmit function in Register.vue script, I called console.log(this.$store.state.count). I still got the same error I stated in the Problem section above.

Can anyone help me fix this? Thank you.

I have a script that downloads a urls.txt with a list of urls to images on google. How do i execute this from a .js file

if i paste this into the browser console, it works 100% – as long as i am on google images in my browser. How can i execute this from just a .js file alone and using a variable as the term to search for?

I would ideally like to call this script from the cli in vscode and pass in an argument with the search term, the script then opens google in the background and downloads images related to the search term for the first x amount of search result pages.

This is for a TensorFlow dataset – i am trying to automate the process of collecting relevant image data.

function simulateRightClick(element) {
  var event1 = new MouseEvent('mousedown', {
    bubbles: true,
    cancelable: false,
    view: window,
    button: 2,
    buttons: 2,
    clientX: element.getBoundingClientRect().x,
    clientY: element.getBoundingClientRect().y,
  })
  element.dispatchEvent(event1)
  var event2 = new MouseEvent('mouseup', {
    bubbles: true,
    cancelable: false,
    view: window,
    button: 2,
    buttons: 0,
    clientX: element.getBoundingClientRect().x,
    clientY: element.getBoundingClientRect().y,
  })
  element.dispatchEvent(event2)
  var event3 = new MouseEvent('contextmenu', {
    bubbles: true,
    cancelable: false,
    view: window,
    button: 2,
    buttons: 0,
    clientX: element.getBoundingClientRect().x,
    clientY: element.getBoundingClientRect().y,
  })
  element.dispatchEvent(event3)
}

function getURLParam(queryString, key) {
  var vars = queryString.replace(/^?/, '').split('&')
  for (let i = 0; i < vars.length; i++) {
    let pair = vars[i].split('=')
    if (pair[0] == key) {
      return pair[1]
    }
  }
  return false
}

function createDownload(contents) {
  var hiddenElement = document.createElement('a')
  hiddenElement.href = 'data:attachment/text,' + encodeURI(contents)
  hiddenElement.target = '_blank'
  hiddenElement.download = 'urls.txt'
  hiddenElement.click()
}

function grabUrls() {
  var urls = []
  return new Promise(function (resolve, reject) {
    var count = document.querySelectorAll('.isv-r a:first-of-type').length,
      index = 0
    Array.prototype.forEach.call(
      document.querySelectorAll('.isv-r a:first-of-type'),
      function (element) {
        // using the right click menu Google will generate the
        // full-size URL; won't work in Internet Explorer
        // (http://pyimg.co/byukr)
        simulateRightClick(element.querySelector(':scope img'))
        // Wait for it to appear on the <a> element
        var interval = setInterval(function () {
          if (element.href.trim() !== '') {
            clearInterval(interval)
            // extract the full-size version of the image
            let googleUrl = element.href.replace(/.*(?)/, '$1'),
              fullImageUrl = decodeURIComponent(
                getURLParam(googleUrl, 'imgurl'),
              )
            if (fullImageUrl !== 'false') {
              urls.push(fullImageUrl)
            }
            // sometimes the URL returns a "false" string and
            // we still want to count those so our Promise
            // resolves
            index++
            if (index == count - 1) {
              resolve(urls)
            }
          }
        }, 10)
      },
    )
  })
}

grabUrls().then(function (urls) {
  urls = urls.join('n')
  createDownload(urls)
})