Autocomplete bug in material ui

I am creating a single page application with React and i have a shipment page where more than one product and product quantity will be add. I create some function for my case. My functions are working but i think the autocomplate displayed values ​​are getting into the bug. How can i fix it?

Like example:
enter image description here
after:
enter image description here

My code:

 const [productList, setProductList] = useState([{ name: "", quantity:  1}]); 
    const [product, setProduct] = useState([""]);//fetch ilie çekilen 

  const handleQuantityChange = (e, index) => {
        const { name, value } = e.target;
        const list = [...productList];
        list[index][name] = value;
        setProductList(list);
      };
 const handleLabelChange = (name, index, value) => {
        const list = [...productList];
        list[index][name] = value;
        setProductList(list);
      };
    
     const handleServiceAdd = () => {
        setProductList([...productList, { name: "", quantity: 0 }]);
      };
         
    return(
    <div>
  {productList.map((p, index) => (
      <Autocomplete
       isOptionEqualToValue={(option, value) => option.name === value.name}
       value={p.name}
       disablePortal
       onChange={(e, newValue) => {
       handleLabelChange("name", index, newValue);
                        }}
       id="controllable-states-demo"
       options={product.map((option) => option.name?option.name:"loading...")}
       renderInput={(params) => (

        <TextField
          {...register('productNameV')}
             error={errors.productNameV ? true : false}
           helperText={errors.productNameV?.message}
           {...params}
                          label={ "Product"+ (index + 1) }
                          InputProps={{
                            ...params.InputProps,
                            endAdornment: (
                              <React.Fragment>
                                {loading ? <CircularProgress color="inherit" size={20} /> : null}
                                {params.InputProps.endAdornment}
                              </React.Fragment>
                            ),
                          }}
                        />                        
                        )}                  
                      />
    </div>           
    ))}
    <div>)

Array remains unchanged when using sort on it

I want to sort an array of days, I found using a pre-defined array reference is better than the JS Date class method.

My array on which sort is called upon doesn’t get sorted, even if I always return 1 in the callback, the array never changes.

const days = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"];

const toSort = ["monday", "tuesday", "thursday", "friday", "wednesday"];

toSort.sort((a, b) => {
  a = days.indexOf(a);
  b = days.indexOf(b);

  return a < b ? 0 : 1;

  // No matter what I return, the source array remains unchanged
  return a < b ? 1 : 0;
  return 1;
});

console.log(toSort);

Something so out of order (haha get it) from using a basic JS function must mean the answer is stupidly obvious, but I can’t figure it out.

Is there a way to pass an object as a lambda function so the dependent class accesses through this function?

I have a manager class which initializes child classes with some dependencies. The problem with the dependencies is that in some instances a new object for them is created. This particular part is out of my control and cannot be updated to reuse the same reference.

My manager class receives an event which contains the new object and I update my manager to use that. The same dependency is used in the child classes as well and now I have to update them there as well. I want to check if there’s a way through which I can write a lambda function in my manager class and pass that function to the child classes such that the reference to the object in child classes is always the latest one? Something that can prevent the hassle of maintaining/updating references in all the classes.

I tried adding a lambda function and passing it to the child classes but its not allowing me to call the functions of the value returned by the lambda function.

I have Query with LIKE clause in Node JS MySQL. working fine when LIKE clause matches database but working properly when LIKE clause doesn’t matches


const search = req.query.search ? `concat_ws(city.city,state.state,country.country) LIKE '%${req.query.search}%' AND ` : ""const sqlQuery = `SELECT * FROM city   JOIN state ON city.state_id = state.state_id JOIN country ON state.country_id = country.country_id WHERE ${search} city.status = 'true' `; db.query(sqlQuery, function (err, results1, fields) {if (err) {console.log(err)}else {res.status(200).json({issuccess: true,status: 200,massage: "Successfully Save",Data: results1,});}

When I hit this route with search query and true value via postman. it is working properly. but when I query with wrong value , it keeps running . does not throw any error neither any results.

How to Pass React State to Normal Function (External Function)

I am Trying the Achieve Passing the React States to External Function Here is the Example Which I Tried

In Tsx File


const [Toggle,setToggle] = useState(false);
const ToggleHandler = () => {
setToggle(!Toggle);
};

useEffect(() => {
GetToggleValue(Toggle);
},[Toggle])

In ts File


External Function

const GetToggleValue = (toggle:boolean) => {
console.log(toggle);

As You Seen I have Passed toggle as Params to GetToggleValue But it Prints Only the Initial State if State Changes in Tsx File its not Updated in External Function
Would Anyone have the Solution for this to fix it

Not able to get the id of the generated firebase document

I’m trying to get the id of the generated firebase document, and I’m using addDoc to create a new doc.

I’m generating a new document on button click and that button calls the initializeCodeEditor function.

Anyone please help me with this!

Button Code:

import { useNavigate } from "react-router-dom"

import { useAuthContext } from "../../hooks/useAuthContext"
import { useFirestore } from "../../hooks/useFirestore"

import Button from "./Button"

const StartCodingButton = ({ document, setIsOpen }) => {
  const { user } = useAuthContext()
  const { addDocument, response } = useFirestore("solutions")
  const navigate = useNavigate()

  const initializeCodeEditor = async () => {
      await addDocument({
        ...document,
        author: user.name,
        userID: user.uid,
      })

      if (!response.error) {
        console.log(response.document) // null
        const id = response?.document?.id; // undefined
        navigate(`/solution/${id}`, { state: true })
      }
  }

  return (
    <Button
      className="font-medium"
      variant="primary"
      size="medium"
      onClick={initializeCodeEditor}
      loading={response.isPending}
    >
      Start coding online
    </Button>
  )
}

export default StartCodingButton

addDocument code

import { useReducer } from "react"
import {
  addDoc,
  collection,
  doc,
  Timestamp,
} from "firebase/firestore"

import { db } from "../firebase/config"
import { firestoreReducer } from "../reducers/firestoreReducer"

const initialState = {
  document: null,
  isPending: false,
  error: null,
  success: null,
}

export const useFirestore = (c) => {
  const [response, dispatch] = useReducer(firestoreReducer, initialState)

  // add a document
  const addDocument = async (doc) => {
    dispatch({ type: "IS_PENDING" })

    try {
      const createdAt = Timestamp.now()
      const addedDocument = await addDoc(collection(db, c), {
        ...doc,
        createdAt,
      })
      dispatch({ type: "ADDED_DOCUMENT", payload: addedDocument })
    } catch (error) {
      dispatch({ type: "ERROR", payload: error.message })
    }
  }

  return {
    addDocument,
    response,
  }
}

firestoreReducer

export const firestoreReducer = (state, action) => {
  switch (action.type) {
    case "IS_PENDING":
      return { isPending: true, document: null, success: false, error: null }
    case "ADDED_DOCUMENT":
      return { isPending: false, document: action.payload, success: true, error: null }
  }
  throw Error("Unknown action: " + action.type)
}

How do I decrypt a Nostr message?

Here’s how to send a private message to a Nostr Pubkey:

const crypto = require("crypto");
const secp = require("noble-secp256k1");

const ourPrivateKey = "";
const ourPubKey = "";
const theirPublicKey = "";
const text = "Hello World";

let sharedPoint = secp.getSharedSecret(ourPrivateKey, "02" + theirPublicKey);
let sharedX = sharedPoint.substr(2, 64);

let iv = crypto.randomFillSync(new Uint8Array(16));
var cipher = crypto.createCipheriv(
  "aes-256-cbc",
  Buffer.from(sharedX, "hex"),
  iv
);
let encryptedMessage = cipher.update(text, "utf8", "base64");
encryptedMessage += cipher.final("base64");
let ivBase64 = Buffer.from(iv.buffer).toString("base64");

let event = {
  pubkey: ourPubKey,
  created_at: Math.floor(Date.now() / 1000),
  kind: 4,
  tags: [["p", theirPublicKey]],
  content: encryptedMessage + "?iv=" + ivBase64,
};

console.log(event.content);

How would the receiver be able decrypt this once they receive it?

TypeError: _crypto.randomBytes is not a function in electron

I am trying to use node-forge library for salt generation in electron , node-forge internally uses native ‘crypto’ , but i keep getting this error

I am using react with electron , the code is in a .jsx file and not in main.js (main process) of electron

TypeError: _crypto.randomBytes is not a function
```'

This happens only in electron , in browser it works fine .

The error occurs when i run this 

let a=forge.random.getBytesSync(128 / 8);

[forge internally calls]
ctx.seedFileSync = function(needed) {
return _crypto.randomBytes(needed).toString();
};



tried doing this in render process 

window.require('crypto')  : It worked,but stopped working.Cannot remember if i changed something


The last nested array is lost when an object is created accordingly mongoose model

I’m trying to create an object according to my model in mongoose using a controller, but I’m running into a problem that the last array nesting with prize patterns is not being written. Theoretically it is, but it is empty. I do not understand what the problem is, since I cannot add the necessary value to it even after creating the object through the constructor and after that doing something like: newGame.prizes = prizes;
With this behavior, all other properties within the prize property appear in the object, but the pattern array is empty.

Here is what my model looks like:

const GameSchema = mongoose.Schema({
  type: String,
  roundId: String,
  userId: String,
  calloutNumbersCount: Number,
  tickets: [
    {
      id: String,
      columns: [[Number]],
    },
  ],
  prizes: [
    {
      id: String,
      name: String,
      nameLocaleKey: String,
      winAmount: Number,
      patterns: [
        {
          type: String,
          count: Number,
        },
      ],
    },
  ],
  ticketPrice: Number,
  boughtTicketIds: [String],
  ended: Boolean,
});

Controller:

function createGame(gameType, userId) {
  const currentGameConfig = config[gameType];
  console.log("Controller");
  currentGameConfig.prizes.map((el) => console.log(el.patterns));
  const roundId = nanoid(LENGTH_OF_ROUND_ID);
  const game = new Game({
    type: currentGameConfig.type,
    roundId,
    userId,
    calloutNumbersCount: currentGameConfig.callout.numbersCount,
    tickets: [
      {
        id: 123, // temp
        columns: [[0]], // temp
      },
    ],
    prizes: currentGameConfig.prizes,
    ticketPrice: currentGameConfig.tickets.price,
    boughtTicketIds: ["1", "2"], // temp
    ended: false,
  });

  return game;
}

Place of creation and modification of the object in the route:

if (!game) {
      const newGame = gameController.createGame(type, userId);
      // newGame.prizes = currentGameConfig.prizes;

      Game.addGame(newGame, (err, game) => {

        if (err) {
          res.json({ success: false, message: err.message });
          throw err;
        }
        return res.json({
          roundId: newGame.roundId,
        });
      });
    }

Expected result:

enter image description here

The result:
enter image description here

How to clear the localStorage by hitting the button?

So here in my form. There are two button which is submit and reset button. If the user answer the question correctly, the score will increasing but if not the scoring will reducing. So when I try to reset the score to 0, the users’ score will deducting. I have tried many possible answer but its not working.

    <body>
        <form action="" class="from" id="form">
            <h3 class="score" id="score">
                Score : 0 
            </h3>
            <h1 class="question" id="question">1 + 1</h1>
            <input type="text" class="input" id="input" 
            placeholder="Enter Your Answer" autofocus autocomplete="off"
            >
            <button class="button">Submit</button>
            <button class="reset" id="resetScore">Reset</button>
        </form>
        
        <script>
    const a = Math.round(Math.random() * 5);
    const b = Math.round(Math.random() * 5);

    // question declared
    const questionDisp = document.getElementById("question");
    // form declared
    const form = document.getElementById("form");
    // input declared
    const input = document.getElementById("input");
    // score declared
    const score1 = document.getElementById("score");
    // reset declared
    const reset = document.getElementById("resetScore");

    let score = JSON.parse(sessionStorage.getItem("score"));//JSON.parse to convert the string to number

    if (!score){
        score = 0;
    }

    score1.innerText = `Score : ${score}`;
    questionDisp.innerText = `What is ${a} + ${b} = `;

    // answer for question declared
    const answer = a + b;

    form.addEventListener("submit", ()=>{
        const userAns = +input.value //plus to convert string to number
        if (userAns === answer ){
            score++;
            ScoreUpdate()
        } else {
            score--;
            ScoreUpdate()
            showAlert()
        }
    });

    document.getElementById("resetScore").addEventListener("click", myFunction);
    function myFunction() {
    document.getElementById("resetScore").innerHTML = "YOU CLICKED ME!";
    }

    function ScoreUpdate(){
        sessionStorage.setItem("score", JSON.stringify(score))
    }

    function showAlert() {
        alert ("WRONG ANSWER");
    }

    function deleteScore(){
        sessionStorage.clear();
    }
        </script>
    </body>
    </html>

how do browsers runs javascript? can i get a direct dissassembly to understand the underlining mechinism, how every line is parsed and compiled?

how do browsers runs javascript? can i get a direct dissassembly to understand the underlining mechinism, how every line is parsed and compiled?

Good day everyone!! I have been playing around with Javascript for some time and then i got curious on exactly how Does the java script runs in the browser. Is there like a GDB(a debuggers which shows every step of execution, states and also show assembly for c/c++ programs) for java script that would show the fundamental mechanism, states and steps browsers take to run Javascript at run time. I wish to develop a deeper understanding of web technologies and Javascript by understanding there underlining mechanism of there interpreters.

I am kinda expecting a debugger like interface that is showing us the execution of each line and i can interact with each of the variables and look there states.

Why I cannot change the left attribute value for my html element?

I am trying change the left value for my img-list when clicking on the pointer I have made. After changing the left value, I can switch to another img.

I have state the absolute position for my img-list. And, when I click on the pointer, the left value has changed, the image has indeed changed to another image, but only for a sec. After a sec, it just changed back to the original image, and when I alert to see the current value of img_list.style.left, it is showing the correct value. But the left value still remains the same 0 value. I am not sure what’s wrong in here, can someone give me some hints plz.

<!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>
    <link rel="stylesheet" href="../reset.css">
    <style>
        .wrapper{
            width: 370px;
            height: 350px;
            background-color: #bfa;
            margin: 50px auto;
            padding:10px 0;
            overflow: hidden;
            position: relative;
        }
        .img-list{
            position: absolute;
            left: 0;
        }
        .img-list li{
            float:left; 
            margin:0 10px;
        }
        img{
            width:350px;
            height: 350px;
        }
        .pointer{
            position: absolute;
            bottom: 10px;
            left: 50%;
            transform: translateX(-50%);
        }
        .pointer a{
            float: left; 
            width: 15px;
            height: 15px;
            background-color: red;
            opacity: 0.5;
        }
        .pointer a:hover{
            background-color: grey;
        }
        .pointer a:not(:first-child){
            margin-left: 10px;
        }
    </style>
    <script type="text/javascript">
        window.onload = function () {
            var img_list = document.getElementById("imglist");
            var img = img_list.getElementsByTagName("img");
            img_list.style.width = 370 * img.length + "px";
            console.log(img_list.style.width);

            var pointer = document.getElementsByClassName("pointer")[0];
            var allA = pointer.getElementsByTagName("a");

            for (var i = 0; i < allA.length; i++) {
                allA[i].index = i;
                allA[i].onclick = function () {
                    var value = this.index * (-370) + "px";
                    img_list.style.left = value;
                    alert(img_list.style.left);
                };
            }
        }
    </script>
</head>
<body>
    <div class="wrapper">
        <ul class="img-list" id = "imglist">
        
            <li><a href=""><img src="./pics/01/d56283cb25574af8.jpg!cc_320x320.webp" alt=""></a></li>
        
            <li><a href=""><img src="./pics/03/eb1b74d5j00rmlivy000jc000go00b4c.jpeg" alt=""></a></li>
            <li><a href=""><img src="./pics/01/fef85dc4d0992e62.jpg!cc_320x320.webp" alt=""></a></li>
            <li><a href=""><img src="./pics/01/3bc798a7387a216d.jpg!cc_320x320.webp" alt=""></a></li>
        </ul>
        <div class="pointer">
            <a href=""></a>
            <a href=""></a>
            <a href=""></a>
            <a href=""></a>
        </div>
    </div>
</body>
</html>

206. Reverse Linked List

I know this problem is very well discussed in StackOverflow’s other posts, and I am here unable to figure out why I am getting this output.

This is the problem:

[206. Reverse Linked List][1]

This is my solution

 /**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var reverseList = function(head) {
     let lastOne = head
     if(!(lastOne && lastOne.next)){
         return head
     }
     head.next = null
     let newNode = lastOne.next
     const reverse = (node)=>{
         if(node == null){
             return lastOne
         }
         let newNode = node.next
         node.next = lastOne
         lastOne = node
         return reverse(newNode)
     }
     return reverse(newNode)
};

I am getting this output:
[![enter image description here][2]][2]

head =
[1,2,3,4,5]

Output
[1]

Expected
[5,4,3,2,1]

can anyone help me, please !!

how do browsers runs javascript? can i get a direct dissassembly to understand the underlining mechinism, how every line is parsed and compiled?

Good day everyone!!
I have been playing around with Javascript for some time and then i got curious on exactly how Does the java script runs in the browser. Is there like a GDB(a debuggers which shows every step of execution, states and also show assembly for c/c++ programs) for java script that would show the fundamental mechanism, states and steps browsers take to run Javascript at run time. I wish to develop a deeper understanding of web technologies and Javascript by understanding there underlining mechanism of there interpreters.

I am kinda expecting a debugger like interface that is showing us the execution of each line and i can interact with each of the variables and look there states.