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.

The value is not changed. in tampermonkey+javascript

https://www.upbit.com/exchange?code=CRIX.UPBIT.KRW-BTC

If you enter it as a keyboard in the order quantity, the value changes.

order quantity=주문수량

In the Chrome console,

document.querySelector(“#UpbitLayout > div:nth-child(4) > div > section.ty01 > div > div.rightB > article:nth-child(1) > span.orderB > div > dl > dd:nth-child(8) > input”).value = 1;

is not used.

What should I do to enter it?

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)
})

Should I render to an image to draw onto a , and how would I go about doing it?

Hard to fit all of the relevant information in the title, so here’s the gist of it:

I’m working on a sprite editor that will hopefully be able to spit out usable tile sheets/palettes for the GameBoy Advance for another project I’m working on (and thus, I have committed the cardinal sin of programming). Since I’m already going to be keeping track of the tile data, palettes, and sprites separately, I figured it might be more efficient to render the tile sheet to an image, then have a <canvas> context draw sections of the tile sheet into the editing frame, rather than using context.fillRect or similar to draw directly to the canvas. Part of the reason I had this idea was because I was concerned about zooming in/out in the editor, which would expand/shrink the sprite. Instead of having to write my own aliasing code, I could draw the tile sheet to an image buffer at a known size, then use context.drawImage to actually display the required tiles and reaping the benefits of the already-existing aliasing algorithm.

As such, my question is two-fold: should I actually write the tile sheet to an image then draw parts of the image to a canvas or should I just fillRect the “””pixels”””? And if I should generate an image, how would I go about doing such?

Note: I’m preferring not to use jQuery here. It seems like a pretty hefty library that wouldn’t gain me much in this context.

Javascript console.log on the same line

I need to print results on the same line of code without using .innerHTML(“”).
I could do it by overwriting original console.log function. This code bellow does it. However, this code prints every console.log text to next line.

(function () {
if (!console) {
    console = {};
}
var old = console.log;
var logger = document.getElementById('log');
console.log = function (message) {
    if (typeof message == 'object') {
        logger.innerHTML += (String(message)) + '<br>';
    } else {
        logger.innerHTML += message + '<br>';
    }
}
})();

Do you know how could I modify this to print text of console.log to next line only if user writes command console.log(“textn”);, and if it’s written console.log(“text”); the default should be to write inline text. (like function printf in C for example)

setInterval Not Repeating Function using Discord.js

I’m trying to make a discord bot that gives you weekly reminders. Im using momentjs to get the time. As well as using discord.js-commando. I found the best way to call a function multiple times is to use setInterval.

const moment = require('moment');
const Commando = require('discord.js-commando');
const bot = new Commando.Client();

bot.on('ready', function () {
  var day = moment().format('dddd');
  var time = moment().format('h:mm a');

  function Tuesday() {
    if (day == 'Tuesday' && time == '6:30 pm') {
      const channel = bot.channels.get('933047404645724234');
      console.log('Sending Message');
      channel.send('Reminder: You have a week to complete your To-Do List!');
    } else {
      console.log('Not Sending Message');
    }
  }

  console.log('Bot is now ready!');
  setInterval(Tuesday, 100);
});

I noticed the problem with the setInterval is that it is only called once. I also tried using an async function but that failed as well.

Set an inline style with javascript click [duplicate]

I’m trying to change the position of an element with some simple javascript. This isn’t working and I’ve no idea what I’ve got wrong or if what I expect is not possible. This doesn’t need to be pretty, it’s for internal use only.COT

<div id="container">
    <div id="maps"> 
        <div class="frida">CONTENT</div> 
        <div class="dolores">CONTENT</div>
    </div>
    <a href="" onclick = document.getElementById("maps").style.left = "0"; >FRIDA</a> 
    <a href="" onclick = document.getElementById("maps").style.left = "-100vw"; >DOLORES</a>
</div>