Check duplicate value in localstorage

I want to check if a id exist in database it will just simply replace it. When i try to do that it is adding the same id.

     addEntry = (e,id) => {
  
  e.preventDefault()

  let product_list = []
  let productCost = document.getElementById('projectcost').value;
  let productQty = document.getElementById('productQty'+id).value;
  let productId = id;

  if(localStorage.getItem('myItems')){
  
    product_list = JSON.parse(localStorage.getItem('myItems'))
    product_list.push({productId,productCost,productQty})
    localStorage.setItem('myItems',JSON.stringify(product_list))

   }else{
   
    product_list.push({productId,productCost,productQty})
    localStorage.setItem('myItems',JSON.stringify([{productId,productCost,productQty}]))
   }
}

Output

[{"productId":44,"productName":"Cleansing milk with Toner","productCost":"140","productQty":"1"},{"productId":44,"productName":"Cleansing milk with Toner","productCost":"280","productQty":"2"},{"productId":44,"productName":"Cleansing milk with Toner","productCost":"420","productQty":"3"}]

output I want

[{"productId":44,"productName":"Cleansing milk with Toner","productCost":"280","productQty":"2"},{"productId":43,"productName":"Hair Spa 100 gm","productCost":"160","productQty":"1"}]

Return json response in ajax request laravel

I have the following ajax code in my frontend.

var formData = $('#application-information-step-one').serialize();
var actionUrl = $('#application-information-step-one').attr('action');
$.ajax({
      url: actionUrl,
      type: 'POST',
      data: formData,
      success: function(data) {
        var resp = JSON.stringify(data);
        console.log(resp);
      },
      error: function(data) {

      }

And following code to return json response from my controller if the request is ajax:

        if ($request->ajax()) {
            return response()->json([
                'message' => 'Information saved sucessfully !'
            ],200)->headers('Content-Type', 'application/json');
        }

But with the above code setup. Laravel returns HTML code of same page from where the request was made.

HTML page is rendered in preview section of network tab .

Can anyone suggest what am I missing here ?

Error when starting discord bot with mutiple shards

const config = require('./config.json');
const logger = require('./utils/logger');
const Discord = require('discord.js');
const Statcord = require("statcord.js");
const { token } = require('./utils/variables.js');


const manager = new Discord.ShardingManager('./index.js', {
  token: token,
  autoSpawn: false,
  totalShards: 5,
  respawn: true,
  spawnTimeout: -1
});

manager.on('shardCreate', shard => logger.info(`Launching Shard ${shard.id + 1}`, { label: `Neo Shard` }));

manager.spawn(manager.totalShards, 5500, -1);

Thats My Code of My Shard File
And I Run A Dashboard On The Same Instance

This Is The Error
2022-05-07 10:42:48 [info] [Neo Shard] Launching Shard 1
node:internal/process/promises:279
triggerUncaughtException(err, true /* fromPromise */);
^

Error [SHARDING_IN_PROCESS]: Shards are still being spawned.
    at ShardingManager._performOnShards (C:TeunNeoSecuritynode_modulesdiscord.jssrcshardingShardingManager.js:258:75)
    at ShardingManager.fetchClientValues (C:TeunNeoSecuritynode_modulesdiscord.jssrcshardingShardingManager.js:245:17)
    at Shard._handleMessage (C:TeunNeoSecuritynode_modulesdiscord.jssrcshardingShard.js:338:22)
    at ChildProcess.emit (node:events:527:28)
    at emit (node:internal/child_process:938:14)
    at processTicksAndRejections (node:internal/process/task_queues:84:21)

(process:5992): GLib-GIO-WARNING **: 10:42:53.218: Unexpectedly, UWP app `Clipchamp.Clipchamp_2.2.12.0_neutral__yxz26nhyzhsrt' (AUMId `Clipchamp.Clipchamp_yxz26nhyzhsrt!App') supports 46 extensions but has no verbs    
2022-05-07 10:42:54 [info] [Neo Shard] Launching Shard 2
Dashboard is up and running on port 5003.
node:internal/process/promises:279
            triggerUncaughtException(err, true /* fromPromise */);
            ^

Error [SHARDING_IN_PROCESS]: Shards are still being spawned.
    at ShardingManager._performOnShards (C:TeunNeoSecuritynode_modulesdiscord.jssrcshardingShardingManager.js:258:75)
    at ShardingManager.fetchClientValues (C:TeunNeoSecuritynode_modulesdiscord.jssrcshardingShardingManager.js:245:17)
    at Shard._handleMessage (C:TeunNeoSecuritynode_modulesdiscord.jssrcshardingShard.js:338:22)
    at ChildProcess.emit (node:events:527:28)
    at emit (node:internal/child_process:938:14)
    at processTicksAndRejections (node:internal/process/task_queues:84:21)

(process:20872): GLib-GIO-WARNING **: 10:42:58.757: Unexpectedly, UWP app `Clipchamp.Clipchamp_2.2.12.0_neutral__yxz26nhyzhsrt' (AUMId `Clipchamp.Clipchamp_yxz26nhyzhsrt!App') supports 46 extensions but has no verbs   
2022-05-07 10:42:59 [info] [Neo Shard] Launching Shard 3
node:events:505
      throw er; // Unhandled 'error' event
      ^

Error: listen EADDRINUSE: address already in use :::5003
    at Server.setupListenHandle [as _listen2] (node:net:1372:16)
    at listenInCluster (node:net:1420:12)
    at Server.listen (node:net:1508:7)
    at Function.listen (C:TeunNeoSecuritynode_modulesexpresslibapplication.js:618:24)
    at module.exports (C:TeunNeoSecuritydashboarddashboard.js:5243:9)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
Emitted 'error' event on Server instance at:
    at emitErrorNT (node:net:1399:8)
    at processTicksAndRejections (node:internal/process/task_queues:83:21) {
  code: 'EADDRINUSE',
  errno: -4091,
  syscall: 'listen',
  address: '::',
  port: 5003
}
C:TeunNeoSecuritynode_modulesdiscord.jssrcshardingShard.js:158
        reject(new Error('SHARDING_READY_DIED', this.id));
               ^

Error [SHARDING_READY_DIED]: Shard 1's process exited before its Client became ready.
    at Shard.onDeath (C:TeunNeoSecuritynode_modulesdiscord.jssrcshardingShard.js:158:16)
    at Object.onceWrapper (node:events:642:26)
    at Shard.emit (node:events:527:28)
    at Shard._handleExit (C:TeunNeoSecuritynode_modulesdiscord.jssrcshardingShard.js:384:10)
    at ChildProcess.emit (node:events:527:28)
    at Process.ChildProcess._handle.onexit (node:internal/child_process:291:12)
Emitted 'error' event on Shard instance at:
    at C:TeunNeoSecuritynode_modulesdiscord.jssrcshardingShard.js:392:49
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {
  [Symbol(code)]: 'SHARDING_READY_DIED'
}  

I dont know how i can fix this i not that advanced
My dashboard is also in js en ejs.

Adding Additional information to dropdown box options

I am wanting to add hidden/additional information to a dropdown box. Currently, it works using

javascript

function myFunction() {
  var copyText1 = document.getElementById("ID");
  

  var value = copyText1.value;
  navigator.clipboard.writeText(value);

}  

and html

<select id="ID">
     <option>Call James</option>
     <option>Call Bob</option>
     <option>Call Jane</option>
</select>


<button onclick="myFunction()">Copy number</button>

however, I would like when ‘Call James’ is selected, the copy number will copy a phone number (eg – ‘5551234’) to the clipboard instead of the text ‘Call James’

Any assistance would be much appreciated.

(MUI v5) (Nested Modal) Both parent and child modal die at the same time

I have simulate my issue in codesandbox: https://codesandbox.io/s/trusting-babbage-ovj2we?file=/src/App.js

I have create a nested modal, when the parent modal is opened, there is a button lead to the child modal. I have passed the useState of the parent modal to the child modal as a prop, I want to close the parent model when the child modal is opened, however, both die when the button was clicked.

I have reviewed my code many times but have no idea what is causing this.

Error: “Module build failed (from ./node_modules/happypack/loader.js):”

This is the theme I am using for a dashboard project (I am under serious timeline pressure).

https://themeforest.net/item/enlite-prime-reactjs-fullstack-website-template/23803960

But getting the following error after installing node modules and executing npm start.

ERROR in ./app/app.js
Module build failed (from ./node_modules/happypack/loader.js):
Error: error:0308010C:digital envelope routines::unsupported
    at new Hash (node:internal/crypto/hash:67:19)
    at Object.createHash (node:crypto:135:10)
    at filename (/mnt/d/Work/Web Development/Websites/enlite-prime_v19/enlite-prime/node_modules/babel-loader/lib/cache.js:94:23)
    at /mnt/d/Work/Web Development/Websites/enlite-prime_v19/enlite-prime/node_modules/babel-loader/lib/cache.js:122:39
    at Generator.next (<anonymous>)
    at asyncGeneratorStep (/mnt/d/Work/Web Development/Websites/enlite-prime_v19/enlite-prime/node_modules/babel-loader/lib/cache.js:3:103)
    at _next (/mnt/d/Work/Web Development/Websites/enlite-prime_v19/enlite-prime/node_modules/babel-loader/lib/cache.js:5:194)
    at /mnt/d/Work/Web Development/Websites/enlite-prime_v19/enlite-prime/node_modules/babel-loader/lib/cache.js:5:364
    at new Promise (<anonymous>)
    at /mnt/d/Work/Web Development/Websites/enlite-prime_v19/enlite-prime/node_modules/babel-loader/lib/cache.js:5:97

How to filter without using the filter method in javascript?

I have to convert 2 functions, both using filter methods into something using for loops, how am i supposed to do that ? For some case, it makes sense, but using the push method is a bit confusing.

Thanks in advance

First function :

function filterWithInputValue(recipes) {
    filteredRecipes = recipes.filter(recipe => {
        const lowerCaseName = recipe.name.toLowerCase().includes(input.value.toLowerCase());
        const lowerCaseDescription = recipe.description.toLowerCase().includes(input.value.toLowerCase());
        const lowerCaseIngredients = recipe.ingredients.filter(({ ingredient }) => ingredient.toLowerCase().includes(input.value.toLowerCase())).length > 0
        return  lowerCaseIngredients | lowerCaseName | lowerCaseDescription;
    });
};

My current version of the function :

function filterWithInputValue(recipes) {
    for (let recipe of recipes) {
        const lowerCaseName = recipe.name.toLowerCase().includes(input.value.toLowerCase());
        const lowerCaseDescription = recipe.description.toLowerCase().includes(input.value.toLowerCase());
        
        for (let ingredient of recipe.ingredients) {
            //????
        }
        
        if (lowerCaseName | lowerCaseDescription | lowerCaseIngredient) {
            filteredRecipes.push(recipe)
        };
    };
};

Second function :

                if(tags.length >= 1) {
                    if(input.value.length >= 3) filterWithInputValue(recipes)
                    else filteredRecipes = recipes

                    const tagList = document.querySelectorAll(".tag");
                    
                    tagList.forEach((tag) => {
                        if(tag.classList.contains("tag0")) {
                            filteredRecipes = filteredRecipes.filter(recipe => recipe.ingredients.some(
                                ({ingredient}) => ingredient.includes(tag.innerText)))
                        }
                        if(tag.classList.contains("tag1")) filteredRecipes = filteredRecipes.filter(recipe => recipe.appliance.includes(tag.innerText))
                        if(tag.classList.contains("tag2")) filteredRecipes = filteredRecipes.filter(recipe => recipe.ustensils.includes(tag.innerText))
                    })
                    createRecipeCard(filteredRecipes)
                    mainInputFiltering(filteredRecipes)
                };

Example of a recipes/data :

{
        "id": 1,
        "name" : "Limonade de Coco",
        "servings" : 1,
        "ingredients": [
            {
                "ingredient" : "Lait de coco",
                "quantity" : 400,
                "unit" : "ml"
            },
            {
                "ingredient" : "Jus de citron",
                "quantity" : 2
            },
            {
                "ingredient" : "Crème de coco",
                "quantity" : 2,
                "unit" : "cuillères à soupe"
            },
            {
                "ingredient" : "Sucre",
                "quantity" : 30,
                "unit" : "grammes"
            },
            {
                "ingredient": "Glaçons"
            }
        ],
        "time": 10,
        "description": "Mettre les glaçons à votre goût dans le blender, ajouter le lait, la crème de coco, le jus de 2 citrons et le sucre. Mixer jusqu'à avoir la consistence désirée",
        "appliance": "Blender",
        "ustensils": ["cuillère à Soupe", "verres", "presse citron" ]
    }

Highlighting text (user input)

I’m trying to involve coding a simple component to highlight substrings of text provided by a user

but I’m getting errors when I’m trying to get the value from a text-area and compare it against a input area

import React from "react";

const Highlighted = ({ text = "", highlight = "" }) => {
  if (!highlight.trim()) {
    return <span>{text}</span>;
  }
  const regex = new RegExp(`(${highlight})`, "gi");
  const parts = text.split(regex);

  return (
    <span>
      {parts.filter(String).map((part, i) => {
        return regex.test(part) ? (
          <mark key={i}>{part}</mark>
        ) : (
          <span key={i}>{part}</span>
        );
      })}
    </span>
  );
};

const App = () => {
  const text = <textarea data-testid="source-text" />;
  const highlight = <input data-testid="search-term" />;
  return (
    <>
      <Highlighted
      text={text}
      highlight={highlight}
    />
    </>
  );
};

export default App;

How to Fix the TD elements of first column of the table body while the rows are scrolling?

The title is not clear, I know. Let me explain what I mean:

First column has td elements which have varying rowspans. What I want is to keep the td text in first column ‘fixed’ at the top while scrolling down.
But only as long as the rest of the td elements in the remaining columns are in scope.
Once all the rows (which the first column cell is spanning) is out of table view, the td element should scroll out of the view and the next td should now start fixing.

Initial Table

After Scrolling a bit:

Headers are already fixed, but no the td in first column which as rowspan=9 is also fixed

And after All the animal rows are scrolled out, the fixed ‘Animal’ td would also go up and then ‘Cars’ would be fixed and then Hats would be fixed like this:

enter image description here

Hide Textbox with parameter name completely when the checkbox is disabled in UI

When I enable the checkbox, I’ve written a js function to enable the textbox to be adjustable; otherwise, it must be greyed out.

Changes Made:

When I enable the checkbox, I’ve written a js function to enable the textbox to be adjustable; otherwise, it must be in a greyed out mode.

Achieved the following logic using JS changes.

Expectation to implement:

However, I want the text box along with the parameter to be hidden if I don’t enable the check box. How to modify the display_ReadOnly function to achieve that hiding functionality.Could someone please guide me on this?

jsp file changes:

<table>
                                               <tr>
                                                <th>
                                                  <b>InputSourceBackup</b>
                                                </th>
                                                <td>
                                                 <c:choose>
                                                   <c:when test="${isAddOperation and DefinitionForm.currentEntry.srcBackupInputs eq true}" >
                                                           <input type="checkbox" name="currentEntry.srcBackupInputs" value="${DefinitionForm.currentEntry.srcBackupInputs}"
                                                         checked="checked" onclick="proj_toggle('srcBackupInputs')"/>
                                                         </c:when>
                                                         <c:when test="${isAddOperation}" >
                                                           <input type="checkbox" name="currentEntry.srcBackupInputs" value="${DefinitionForm.currentEntry.srcBackupInputs}"
                                                        onclick="proj_toggle('srcBackupInputs')"/>
                                                         </c:when>
                                                         <c:otherwise>
                                                                <c:out value="${DefinitionForm.currentEntry.srcBackupInputs eq true ? 'Yes' : 'No'}"/>
                                                         </c:otherwise>
                                                       </c:choose>
                                                </td>
                                              </tr>
                                              <tr>
                                                    <th>Backup Source IP Address 1 (optional)</th>
                                                    <td>
                                                      <c:choose>
                                                                <c:when test="${isAddOperation}">
                                                                  <tags:ip name="currentEntry.SourceIP" type="default" value="${DefinitionForm.currentEntry.SourceIP}"
                                                         spreadsheet="false" size="15" maxlength="15" />
                                                                </c:when>
                                                                <c:otherwise>
                                                                  <c:out value="${DefinitionForm.currentEntry.SourceIP}"></c:out>
                                                                </c:otherwise>
                                                              </c:choose>
                                                    </td>
                                                   </tr>
                                                  </table>
            

js file changes:

    function displayBlock(element){
            if (element[0] === undefined || element[0] ===  null) {
                    return;
            }
            element[0].readOnly = false;
            element[0].style.background = "";
    }
    
    function displayReadOnly(element){
            if (element[0] === undefined || element[0] ===  null) {
                    return;
            }
    
            element[0].readOnly = true;
            element[0].style.background = "lightgrey";
    }
    
    
    
    
    function proj_toggle(type,clear) {
    
    if (type === 'srcBackupInputs'){
                    toggler = document.getElementsByName("currentEntry.srcBackupInputs");
    
                    if(toggler[0].checked ){
                            
                            toggleField1 = document.getElementsByName("currentEntry.SourceIP");
                            displayBlock(toggleField1);
                            
                    }else{
                            toggleField = document.getElementsByName("currentEntry.sourceIP");
                            displayReadOnly(toggleField);
                    }
    }

Java file changes:

class SessionEntry
{
     private boolean srcBackupInputs;
     public boolean isSrcBackupInputs() {
        return srcBackupInputs;
     }

     public void setSrcBackupInputs(boolean iSrcBackupInputs) {
        srcBackupInputs = iSrcBackupInputs;
    }
}

Most accurate way to synchronize backend timer with frontend?

I have a backend database that does a periodic update. I want the frontend to be able to have a live display “Last updated: N seconds ago”.

I considered just sending the UTC timestamp to the browser and letting it calculate the live difference, but this depends on the client machine doing some calculations against its own clock which may be wrong.

What is the most accurate way to do this?

(The best idea I have so far would be to just ignore the server/client latency and let the server send the initial value of N to the client, which is incremented by 1 every second in the client browser.)

How to play sounds correctly?

I need to run sounds automatically in React. In order to run sounds, I use a non-standard useSound hook. It creates a button and by clicking on this button the sound starts. I made a trigger to automatically start a click and made a delay between sounds.

Sounds come in view of the array. Therefore, I go through the array and create several buttons that should be clicked. Tell me how to create for each button const [play] = useSound(“/static/1.mp3”); and your unique id so that all buttons are automatically created and played?

import React, { useState, useEffect } from "react";

import useSound from "use-sound";

export default function Play(props) {

  const arr = ['./1.mp3', '/static/2.mp3', '/static/3.mp3']

  function Button() {
    return props.newResult.map(() => (
      <button className={styles.buttonPlay} id='button3'>
        {props.newResult}
      </button>
    ));
  }

  const Play = () => {
    const [play] = useSound("/static/1.mp3"); // Буква
    return (
      <>
        <button className={styles.buttonPlay} id='button' onClick={play}>
          Пациент
        </button>
      </>
    );
  };

  async function Auto() {
    await new Promise(function (s) {
      setTimeout(s, 1000);
    });
    document.querySelector("#button").click();

    await new Promise(function (s) {
      setTimeout(s, 1000);
    });
  }

  useEffect(() => {
    Auto();
  }, []);

  return (
    <>
      {Play()}
    </>
  );
}

Values are not set on time in Chrome Extension

I’m trying to simply log on to a webapi. Once fetch successful, it gives me bearer token, username, etc..

And then simply store those values in a variable and then username on the popup.

But when I click on the button, it doesn’t wait for the fetch call to succeed and sets page variable before that which turns to be shown value as undefined or blank.

Subsequently on 3rd or 4th try on clicking the login button it’s successful and display’s the username.

Also once the popup is closed those values are gone. How can I store token and other info to use it for subsequent next fetch calls.

    var respjson = "";
var token = "";
document.getElementById('btnLogin').onclick = function () {
    var robject = "";
    robject = Login();
    setTimeout(
        function () {
            //do something special
            if (robject == '0' || robject == '' || robject == 'undefined' || robject == null) {
                console.log("var not set: " + robject);
            }
            else {
                console.log(robject);
                $("#lbluname").html('<p>Set UName</p>');
                $("#lbluname").html('<p>' + robject.userName + '</p>');
                $("#lblToken").html('<p>Set Token</p>');
                $("#lblToken").html('<p>' + token + '</p>');
            }
        }, 5000);
};

function Login() {
    var credentials = {
        "username": $("#txtUName").val(),"password": $("#txtPass").val()
    }
    console.log(credentials);
    chrome.runtime.sendMessage({ greeting: "Login", cred: credentials },
        function (response) {
            respjson = JSON.parse(response.farewell);
            token = respjson.access_token;
        });
    return respjson;
}

why are javascript functions not outputting anything?

<!DOCTYPE html>
<html>
  
  <head>
    <title>todo</title>
  </head>
  
  <body>
    <script>
     
       function greeting(firstName) {
       console.log('hello ' + firstName);
       }
      
       greeting('Simon');
    //---------------------------------------------------------------
      function toUpper(str){
        console.log(str.toUpperCase());
      }

      toUpper('testing');
      
    </script>

  </body>
</html>

I am new to javascript and learning basic syntax.
These basic functions are not outputting anything. I am not sure what the problem is.

Making addon to look for specific url with information from table on other site

So recently I started to work as it admin and I’m looking for opportunities to make my job easier.
My job is to monitor specific sites. When new alert appear on site A(and every other) I need to go on site B and check if it didn’t appear recently. This information is always under this url
[url blabla]
%3DGOTO123TEXTQUERY321
%253d[INFORMATION IM LOOKING FOR]
%26sysparm_query_encoded
%3DGOTO123TEXTQUERY321
%253[INFORMATION IM LOOKING FOR]
%26sysparm_view
%3D

And there is table where I can look for specific row class with state open/progress/closed.

Now It’s time for my question can you guys provide me any helpful advices how can I start to do it,
what is the best way to do it(i was thinking about making chrome addon. programing language is not a problem I will find my way to use it),
Also sometimes i receive email about ignoring some alerts and I would like to attach this information and it will be shown instead of going to url

Thank you in advance for help