JavaScript Array Search for Partial Strings

I’m trying to find a fast way to search for partial strings in array elements and put them into a new array if the input value is greater than 2 characters.

Ultimately, this array will be used to create a list as results are found, a local data search.

This works okay but the arrays can be quite large (thousands of entries) and was looking for the best way to approach this that won’t end up a performance problem.
 

<html>
    <body>
        <input id="test">
    </body>
    <script>

        let test = ['Fruits: Apples', 'Fruits: Oranges', 'Fruits: Banannas', 'Fruits: Lemons', 'Vegetables: Corn', 'Vegetables: Potatoes']
        let found = []

        document.querySelector('#test').addEventListener('keyup', e => {
            let value = e.currentTarget.value
            if (value.length > 2) {
                let index = test.findIndex(i => i.includes(value))
                test.forEach(v => {
                    if(v.includes(value) && !found.includes(v))
                        found.push(v)
                })
            } else {
                found = []
            }
            console.log(found)
        })
    </script>
</html>

Passport js Error 401: invalid_client The Google OAuth client was not found

I am using Passport js in Express for authenticating users with Google. I am using Passport for oauth servicing and passport-google-oauth20 for GoogleStrategy and I am using Express for the server side. So following is my code ….

const express = require("express");
const passport = require("passport");
const keys = require("./config/keys");
const GoogleStrategy = require("passport-google-oauth20").Strategy;

const app = express();

passport.use(
  new GoogleStrategy(
    {
      clientID: keys.googleClientID,
      clientSecret: keys.googleClientSecret,
      callbackURL: "/auth/google/callback",
    },
    (accessToken) => {
      console.log(accessToken);
    }
  )
);

app.get(
  "/auth/google",
  passport.authenticate("google", {
    scope: ["profile", "email"],
  })
);

const PORT = process.env.PORT || 3005;

app.listen(PORT);

i am using nodemon for auto running server. And i have also create project in google.developers.console for client_id and client_secret. But when i run the server it just redirect me to the following url and show the following error.

https://accounts.google.com/signin/oauth/error/v2?authError=Cg5pbnZhbGlkX2NsaWVudBIfVGhlIE9BdXRoIGNsaWVudCB3YXMgbm90IGZvdW5kLiCRAw%3D%3D&client_id=http%3A%2F%2F776441197185-ifgipq9v3inocgmdj8it7gs5mm4t3i9s.apps.googleusercontent.com

How can I TinyFaceDetector error in face-api.js

I am trying to create an app that takes a good picture of you, worth for analyzing your skin.
I have 3 main conditions:

  1. The face should be in specific coordinates (I have them hardcoded)
  2. I wanna detect if the person is looking straight, not up, down, etc.
  3. Have good lighting.
    They are not important for this question, just wanted to give you the big picture.

The feature is gonna work only on mobile devices via the browser (not mobile application).

I am getting this weird error, when I am running my detectFace function:

Box.constructor - expected box to be IBoundingBox | IRect, instead have {"x": null, "y": null, "width": null, "height": null}

The weird this is, this thing only happens whenever I am using TinyFaceDetector, this is how I am using it:

 useEffect(() => {
    const loadModel = async () => {
      try {
        await Promise.all([
          faceapi.nets.tinyFaceDetector.loadFromUri("/models"),
          faceapi.nets.faceLandmark68TinyNet.loadFromUri("/models"),
        ]);
        initializeCamera();
        setIsModelLoaded(true);
      } catch (error) {
        console.error("Error loading models:", error);
      }
    };

    const detectFace = async () => {
        if (isModelLoaded && webcamRef.current) {
          const video = webcamRef.current.video as HTMLVideoElement;
          const detections = await faceapi
            .detectAllFaces(
              video,
              new faceapi.TinyFaceDetectorOptions({
                scoreThreshold: 0.1,
                inputSize: 128,
              })
            )
            .withFaceLandmarks(true);

          if (detections.length > 0) {
            const minX = 0;
            const maxX = 75;
            const minY = 165;
            const maxY = 230;

            if (
              detections[0].detection.box.x !== null &&
              detections[0].detection.box.x >= minX &&
              detections[0].detection.box.x <= maxX &&
              detections[0].detection.box.y >= minY &&
              detections[0].detection.box.y <= maxY
            ) {
              setIsFaceInShape(true);
            } else {
              setIsFaceInShape(false);
            }

            const brightness = await calculateAverageBrightness(video);

            if (brightness < 150) {
              setIsLightGood(true);
            } else {
              setIsLightGood(false);
            }
          }
        }
     
    };

    loadModel();

    const intervalId = setInterval(detectFace, 200);

    return () => {
      clearInterval(intervalId);
    };
  }, [isModelLoaded]);


useEffect(() => {
    if (isFaceInShape && isLightGood) {
      capture();
    }
  }, [isFaceInShape, isLightGood]);

The weird thing is that when the function capture goes through, I see the error on my screen, but in the background I can see the image perfectly taken and the rest of the logic in capture is working great, which means that error doesn’t do anything, it doesn’t stop the app from working, where is it coming from ?

What I tried:
I noticed that when I lower the timeout interval, the errors happen less often, but I need it to scan fast so the app works as intended.

What worked:
When I am using ssdMobilenetv1 it works without any errors, but its a very heavy model especially for mobile and the camera starts lagging so much, because it makes those large scans every 0.2 seconds. The error happens mainly with TinyFaceDetector, which I am trying to use, because for mobile, it works perfectly, but I need the withFaceLandmarks prop.

Let me know if you need more code from my app.

why is await not working in the second syntax?

the following code results into the expected output

function toppings_choice() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(console.log("which topping would you love?"));
      reject("not working");
    }, 3000);
  });
}

async function kitchen() {
  console.log("A");
  console.log("B");
  console.log("C");

  await toppings_choice();

  console.log("D");
  console.log("E");
}

kitchen();
/* Stackoverflow: show only console */
.as-console-wrapper {
  max-height: 100% !important;
  top: 0;
}

output:
A
B
C
which topping would you love?
D
E

but for some reason await in the following syntax does not work

async function toppingChoice() {
  setTimeout(() => {
    if (true) {
      return console.log("which topping would you love?");
    } else {
      throw "not working";
    }
  }, 3000);
}

async function kitchenTwo() {
  console.log("A");
  console.log("B");
  console.log("C");

  await toppingChoice();

  console.log("D");
  console.log("E");
}

kitchenTwo();
/* Stackoverflow: show only console */
.as-console-wrapper {
  max-height: 100% !important;
  top: 0;
}

output:
A
B
C
D
E
which topping would you love?

both functions return a promise, so why is the await keyword working in the first code and indeed stopped the code until the promise was resolved but did not work in the second code?

I need to know if I could use the syntactic sugar of sync/await without having to use the promise constructor

Add Slashes (” – “) in input

how to add – slashes auto on onchange function in cnic or other input type=”number” in js

function countWords(inputString) {
  // Remove leading and trailing whitespaces
  const trimmedString = inputString.trim();

  // If the string is empty, return 0 words
  if (trimmedString === "") {
    return 0;
  }

  // Split the string into an array of words using whitespace as the separator
  const wordsArray = trimmedString.split(/s+/);

  // Count the number of elements in the array, which represents the number of words
  const wordCount = wordsArray.length;

  return wordCount;
}

Order of callbacks: setTimeout and ResizeObserver

With the following code I sometimes get timeout, then RO output, sometimes the reverse. Are both valid browser behaviours? Or just one?

const div = document.createElement("div")
document.body.append(div)
new ResizeObserver(() => console.log("RO")).observe(div)
setTimeout(() => console.log("timeout"))

It happens in Firefox. In Midori, which also uses Gecko, it seems to be always timeout first.

EDIT:
Simpler code also showing this:

new ResizeObserver(() => console.log("RO")).observe(document.body)
setTimeout(() => console.log("timeout"))

Button js stops working when I create it dynamically

The click event does not work when I generate the input dynamically.

This works ok

<div class="btn-group" id="cobradores">
      <button type="button" class="btn btn-secondary" data-dismiss="modal" id="cobrador1" name="cobrador">Uno</button>
</div>

<script>
$(document).ready(function() {
    $('#cobrador1').click(function() {
  
  console.log("Ok");

});
});
<script>

But when I try it this way I get an error

<div class="btn-group" id="cobradores">

</div>

<script>
$(document).ready(function() {
    document.getElementById("cobradores").innerHTML = '' + '<button type="button" class="btn btn-secondary" data-dismiss="modal" id="cobrador1">Cobrador</button>';

$('#cobrador1').click(function() {
  
  console.log("Ok");

});
});
<script>

How can I correct it? Thanks!

I am having issues with displaying my herocard when clicking on the button to scroll through a list of cards

import React, { useState, useEffect } from 'react'
import data from "../data"

const Hero = () => {

    const [cards, setCards] = useState(data.data.pages);
    const [activeIndex, setActiveIndex] = useState(0);
    const [heroCard, setHeroCard] = useState(cards[0]);
    const [isDisabled, setIsDisabled] = useState(false);


    const addHeroCards = () => {
        setActiveIndex(prev => activeIndex + 1);
        setHeroCard(prev => cards[activeIndex]);;
        if(activeIndex >= 3) {
            setHeroCard(prev => cards[3]);
        } 
    }

    const subtractHeroCards = () => {
        setActiveIndex(prev => activeIndex -1);
        setHeroCard(prev => cards[activeIndex]);
        if(activeIndex <= 0) {
            setHeroCard(prev => cards[0])
        }
    }

    return (
        <div className="hero">
            <button className="btn one" onClick={subtractHeroCards} disabled={isDisabled}>&lt;</button>
            <div className="hero-title">
                    <h2>{heroCard.title}</h2>
                </div>
            <div className="hero-text">
                <p>
                    {heroCard.document}
                </p>
            </div>
            <button className="btn two" onClick={addHeroCards} disabled={isDisabled}>&gt;</button>
        </div>
    )
  }
  
  export default Hero;

I want to be able to click the button and display the next card or click a button and display the previous card but not go past the array of objects as it is currently doing.
I have created a disabled state but when it gets disabled I can’t click on the button anymore and the active index goes past the intended index. or it doesn’t display correctly.

I tried creating a disabled state

const addHeroCards = () => {
        setActiveIndex(prev => activeIndex + 1);
        setHeroCard(prev => cards[activeIndex]);;
        if(activeIndex >= 3) {
            setIsDisabled(true)
            setHeroCard(prev => cards[3]);
        } 
        setIsDisabled(false);
    }

    const subtractHeroCards = () => {
        setActiveIndex(prev => activeIndex -1);
        setHeroCard(prev => cards[activeIndex]);
        if(activeIndex <= 0) {
            setIsDisabled(true);
            setHeroCard(prev => cards[0])
        }
        setIsDisabled(false);
    }

and set it as false or true depending on the index but after it gets disabled the whole entire button doesn’t act right. Plus I have to click on the button more than once the first time in order to get it to get to the next index.

table height adjustment for tablet phone and computer

When I look at the site I created on the computer, the table height is set to full height, but when I look at it from mobile, there is a gap at the bottom of the table. When I look at it from the tablet, this gap is larger. Additionally, when I turn the phone or tablet sideways, this remaining space becomes even larger. I want to automatically adjust the table height according to the device entered on the site. how can I do that.

Set is only returning a partially unique array

I am trying to return a unique set of job types that I am mapping from a list of jobs

const jobs = Array.from(new Set(jobData.map((job)=>job.type)));

It is taking as input a list

["ADS","ESTG","NPA", "Comp", "Comp", "Comp", "ITR", "Comp", "ADS", "EBP", "EBP", "BTR", "Comp", "BTR", "Review", "Comp", "ESTG", "Comp", "BTR", "ESTG", "ADS", "ADS", "NPA", "ESTG", "NPA", "EBP", "Review", "BTR", "Review", "EBP", "ITR", "ITR", "Review", "Comp", "NPA", "ITR" ]

It is giving me a nearly unique set of types, except for the list has two “Review” items.

They are all strings if type checked and in if the two instances of “Review” are compared i.e. jobs[0] === jobs[1] it returns true. I think it has something to do with how the data is coming in but I am at a loss when the two instances of Review are exactly the same. Wanted to see if anybody had any insight into what could cause such a situation.

GET Error: MongoParseError: option useunifedtopology is not supported | When I starting my project

My code:

import express from 'express'
import mongoose from 'mongoose'

const PORT = 5000;
const DB_URL = `mongodb+srv://<iwritedmyusername>:<iwritedmypassword>@cluster0.ql2kiob.mongodb.net/?retryWrites=true&w=majority`;

const app = express()

app.use(express.json())

app.post('/', (req, res) => {
    res.status(200).json('Server is cool!!')
})

async function startApp() {
    try {
        await mongoose.connect(DB_URL, {useUnifedTopology: true, useNewUrlParser: true})
        app.listen(PORT, () => console.log('SERVER STARTED ON PORT: ' + PORT))
    } catch(e) {
        console.log(e);
    }
}

startApp()

Although I installed everything correctly via npm

Plz help me with my problem

P.S. If suddenly there are grammatical errors in the text, then know that I am not a native English speaker and am now writing through Google translator.

get the value of select without submitting php

I have php page with select control … I want to select any item (which it is customers ID) then Get this customer balance without submitting

<form method="post">  
<label>Cust. ID</label>
<select name="list1" id="options1" onchange="myFunction()" >
    <?php
        include "dbConn.php"; 
        $query = "SELECT * FROM cust";
        $result2 = mysqli_query($conn, $query);
        $options = "    ";
        while($row2 = mysqli_fetch_array($result2))
        {
            $options = $options."<option> $row2[0]</option>";
        }
            echo $options;
    ?>
</select>

javascript code like below

 
function myFunction() { 
<?php 
     $id = $_POST['list1'];
     $sql = "select SUM(income) - SUM(outgoing) as balance from trans where id= '$id'";
     $res_data = mysqli_query($conn,$sql);
     foreach($res_data AS $row) 
    {             
     $balance = $row['balance'] ; 
    } 
?> ;
  document.getElementById("balance").value = <?php echo json_encode($balance);  ?>
}
 

How to shorten the closest method for multiple classes that have the same names

The following process works for me, in regards to finding the correct parent. It is out of my control on the duplicated class names as shown below. But is there a shorter way to write the following in raw javascript?

var mvalues = document.querySelectorAll("[id*='undefinedundefined']");
mvalues.forEach((item) => {

//is there a shorter way to write this?
item.closest(".input-group").closest(".combobox-container").closest(".input-group").closest(".combobox-container").remove();

});


The html looks like this…


<div class="combobox-container">
  <div class="input-group">
    <div class="combobox-container">
      <div class="input-group">
        <span id="itemundefinedundefined"></span>
      </div>
     </div>
   </div>
</div>

Improving performance of HTML5 canvas with thousands of rectangles drawn per frame

I am creating a waterfall graph based on live spectrum data pulled from a server. The canvas is set currently to render 100 rows of time data with 64 points per line (maximum of 64,000 rectangles rendered per frame). Within a web worker, the following snippet controls rendering:

context.clearRect(0, 0, canvas.width, canvas.height);

// ...
// map points to colors using d3.scaleSequential(...)
// (little impact on performance)
// ...

for (let [color, points] of Object.entries(colorCoordinates)) {
  context.fillStyle = color;
  for (let point of points) {
    context.fillRect(...point);
  }
}

This is already an upgrade over a previous approach which involved setting colors in a linear fashion (context.fillStyle was modified thousands of times; very slow). The approach above performs somewhat adequately, but is sluggish approaching 30fps.

Another approach I tried, based on other questions, was to use beginPath + rect + fill:

for (let [color, points] of Object.entries(colorCoordinates)) {
  context.fillStyle = color;
  context.beginPath();
  for (let point of points) {
    context.rect(...point);
  }
  context.fill();
}

However, tested in three browsers, this approach was approximately half as slow each time, which surprised me.

Please give me some tips on other techniques I can use to optimize my graph.