Run a function on multiple html elements having same class name

***Working
When i right click on the chat item then it run a function test_delete(e) for target element and context menu shows and store chat id in variable x.

when we click on delete then it shows the id of target chat.
works fine for now.

Problem
If i click on a chat 10 times or more than 1 time
and then i click on delete from context menu then the delete button function returns chat id per click on chat

but i want it return only single chat id

Example: if i click on chat 10 time but click delete button 1 time then it return chat id of last target chat 10 times
1 want it return chat id only 1 time

if You dont understant my question then run snippet and view console
How can i fix this problem….






<!--Context Menu-->    
 <div class="TestClass" id="m">
       <p  class="innerP0">
           <input id="dummy" type="text" value="">
       <a  class="context-item" id="Tex">Delete</a>
       <a class="context-item" id="EDIT">Edit...</a>
       <a class="context-item" id="forward">Forward</a>
       <a class="context-item" id="copy">Copy</a>
       <a class="context-item" id="copy">Select</a>
      </p>
    </div>
    <p id="dM"></p>




<!--Html Elements of same class name-->

<div class="to123f">
   <div class="from Text_chat" oncontextmenu="return false;">
        <input class="chatId" type="hidden" value="263">
        <span class="chatf_time">2022-01-16 21:32:37</span>
        <p id="message_detail" class="chat_text fromuser">fgdfg</p>
    </div>
</div>
<div class="to123f">
   <div class="from Text_chat" oncontextmenu="return false;">
        <input class="chatId" type="hidden" value="264">
        <span class="chatf_time">2022-01-16 21:32:37</span>
        <p id="message_detail" class="chat_text fromuser">dffdg</p>
    </div>
</div>
<div class="to123f">
   <div class="from Text_chat" oncontextmenu="return false;">
        <input class="chatId" type="hidden" value="266">
        <span class="chatf_time">2022-01-16 21:32:37</span>
        <p id="message_detail" class="chat_text fromuser">
asad
</p>
    </div>
</div>

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

    //CHAT CONTEXT MENU FOR Desktop

    function test_delete(e){
    let menu = document.getElementById('m');
    let mes = document.getElementById('dM');

        menu.style.display = "block";
     y = e.currentTarget;
        let check_user = e.currentTarget.className;
        if (check_user == 'to') {
          //  alert("You Click on " + check_user);
        }
       // console.log(e.currentTarget.className);
        x = y.querySelector('input').value;
         // console.log(e);
          if(e.pageX == undefined){
            var posX = e.changedTouches[0].pageX;
            var posY = e.changedTouches[0].pageY;
          }
          else{
            var posX = e.pageX;
            var posY = e.pageY;
          }
         
        

        var menuWidth = menu.offsetWidth;
        var menuHeight = menu.offsetHeight;
        var totalWidth = window.innerWidth;
        var totalHeight = window.innerHeight;

        if ((totalWidth - posX) < menuWidth) {
            menu.style.left = posX - menuWidth + "px";
            //console.log("ifX = ");
        } else {
            menu.style.left = posX + 5 + "px";
           //  console.log("elseX = ");
        }
        if ((totalHeight - posY) < menuHeight) {
            menu.style.top = posY - menuHeight + "px"
              //   console.log("ifY = ");
        } else {
            menu.style.top = posY + "px";
           //  console.log("elseY = ");
        }
        var contextItem = document.getElementsByClassName('context-item');
        var contextLength = contextItem.length;
        var i= 0;
        for(i;i<contextLength;i++){
            contextItem[i].addEventListener('click', function(){menu.style.display='none';
            
        })
            
        }
        window.onclick = function(e) {
            if(!e.target.matches.menu){
                menu.style.display = "none";
            }
           
          
            
    }
    //console.log(inner);
        menu.querySelector('#Tex').addEventListener("click", function() {
            
            let data = `id=${x}`;
            console.log(data);
        
        });


    }

    //CHAT CONTEXT MENU FOR TOUCH DEVICES
    function mobileContext(){
     var chatBody = document.getElementsByClassName('from');
    // console.log('ChatBody = '+chatBody);
    var chatBodyLength = chatBody.length;
    var i=0;
     var delay = 500;
     var holdStarter = null;
     var holdActive = false;
     for(i;i<chatBodyLength;i++){
        chatBody[i].addEventListener('touchstart' , TouchStart);
        chatBody[i].addEventListener('touchend' , TouchEnd);
        chatBody[i].addEventListener('auxclick' , test_delete);
     }

     

     function TouchStart(){
        holdStarter = setTimeout(function() {
            holdStarter = null;
            holdActive = true;
        }, delay);
     }

     function TouchEnd(e){
        if (holdStarter) {
            clearTimeout(holdStarter);
            // run click-only operation here
            // console.log('Clicked!');
        }else
        if(holdActive == true){
          //  console.log('Hold Active');
            
            holdActive = false;
            test_delete(e);
        }
     }
    }
    mobileContext();


<!-- language: lang-css -->

    .TestClass {
      /*  left: -89px; */
        position: absolute;
        width: 140px;
        
        background: #ffffff;
        z-index: 1000;
        /* border: 1px solid green; */
        box-shadow: 4px 4px 10px -3px #00000024;
        display: ;
        border: 1px solid #dbdee7;
    }

    p.innerP0 a:last-child {
        border: 0;
    }

    p.innerP0 a {
        text-decoration: none;
        color: gray;
        padding: 5px 15px;
        font-size: 11px;
        border:none; 
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
    p.innerP0 {
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        height: 100%;
        padding: 4px 0px !important;
    }

    p.innerP0 a:hover {
        background: #c9c9c9;
    }

    #dM {
        padding: 5px 15px;
        border-radius: 20px;
        background: #4849a1;
        color: #fff;
        font: 300 12px/1 'open sans';
        width: fit-content;
        text-align: center;
        position: fixed;
        left: 0;
        right: 0;
        bottom: -40px;
        margin: auto;
        transition: .5s ease;
    }
    .to123f {
        display: flex;
        justify-content: flex-end;
        position: relative;
    }
    .to123f p {
        padding: 12px 10px;
    }
    .to123f p {
            font-size: 13px;
            -webkit-user-select: none; -webkit-touch-callout: none; -moz-user-select: none; -ms-user-select: none; user-select: none;
            user-select: none;
        }
        .from{
        background:gray;
        margin-bottom:20px;
        }

<!-- language: lang-html -->

    <!--Context Menu-->    
     <div class="TestClass" id="m">
           <p  class="innerP0">
           <a  class="context-item" id="Tex">Delete</a>

           <a class="context-item" id="EDIT">Edit...</a>

           <a class="context-item" id="forward">Forward</a>

           <a class="context-item" id="copy">Copy</a>

           <a class="context-item" id="copy">Select</a>

          </p>

        </div>

        <p id="dM">
</p>

    <!--Html Elements of same class name-->

    <div class="to123f">
       <div class="from Text_chat" oncontextmenu="return false;">

            <input class="chatId" type="hidden" value="263">

            <span class="chatf_time">2022-01-16 21:32:37</span>

            <p id="message_detail" class="chat_text fromuser">fgdfg</p>

        </div>

    </div>

    <div class="to123f">

       <div class="from Text_chat" oncontextmenu="return false;">

            <input class="chatId" type="hidden" value="264">

            <span class="chatf_time">2022-01-16 21:32:37</span>

            <p id="message_detail" class="chat_text fromuser">dffdg</p>

        </div>
    </div>
    <div class="to123f">

       <div class="from Text_chat" oncontextmenu="return false;">

            <input class="chatId" type="hidden" value="266">
            <span class="chatf_time">2022-01-16 21:32:37</span>
            <p id="message_detail" class="chat_text fromuser">
asad
</p>
        </div>
    </div>









How to forward audio/video data from a user’s browser(client) to a server?

What I am Doing

I have a javascript file that uses getUserMedia() to get the audio and video from the client’s computer. How do I implement computer vision to video feed which was extracted from the camera using javascript getUserMedia() and speech recognition to audio feed which was extracted from the microphone using javascript getUserMedia() using python?

Why do I want to use Python?

I want to use python because I have already written all the code to run this locally on my machine, using flask but to run on other computers I have to use javascript to access the client’s mic and cam and can’t use python to do that or python would detect a mic and cam in the server instead of the client’s machine.

What I Tried

Attempt #1

I have tried using js2py to translate .js file to .py file using:

js2py.translate_file(static/sketch.js', 'sketch.py')
from sketch import sketch
# I use getUserMedia() function after that from the .py file

I got an error which I found out was a too large .js file error.

Attempt #2

I looked at MDN docs articles:

https://developer.mozilla.org/en-US/docs/Web/Guide/AJAX

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest

https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Fetching_data

I got really confused about how to use Ajax so didn’t even try because I didn’t know what to do. I am highly leaning towards thinking this could solve my problem but I could be wrong that’s is why I am asking this question.

Underlying Question

My question is how to deliver audio/video data from a user’s browser to a server?

Javascript, creating button that randomly selects links inside the page

I’m trying to make it so when people select the button on top of the page one of the three links, which are ids inside the page, will be selected (they look like tabs with the jquery ui attachment but I couldn’t get it on the pen), but despite my attemps I can’t make it work by using a function and if staments, any advice on what I’m doing wrong? I never made something more than basic in javascript

Full code here, since due to character limit i can’t put the full HTML and CSS on the post

Codepen: https://codepen.io/bladeranner5005/pen/GRMVGbR

HTML

<!doctype html>
<html lang="it" xmlns="http://www.w3.org/1999/html" xmlns="http://www.w3.org/1999/html">
<head>
    <!--Required meta tags-->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!--Font links-->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Josefin+Sans:wght@300;400&family=Libre+Franklin:wght@800&display=swap" rel="stylesheet">

    <!--Bootstrap CSS-->
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

    <!--Plugins -->
    <link href="../external-files/jquery-ui-1.13.1.custom/jquery-ui.min.css" rel="stylesheet" type="text/css">
    <link href="../external-files/jquery-ui-1.13.1.custom/jquery-ui.theme.min.css" rel="stylesheet" type="text/css">
    <script src="../external-files/jquery-ui-1.13.1.custom/external/jquery/jquery.js" type="text/javascript"></script>
    <script src="../external-files/jquery-ui-1.13.1.custom/jquery-ui.min.js" type="text/javascript"></script>

    <!--Custom css-->
    <link href="../css/index-css.css" rel="stylesheet" type="text/css">

    <link href="../css/content-css.css" rel="stylesheet" type="text/css">



    <title>Andrea D'Angelo-Portfolio</title>
</head>

<body>

<!-- NAVBAR ----------------------------------------------------------------------------------------------------------->
<!--Modified bootstrap NAVBAR, with different colors and positioning when in desktop----------------------------------->

<nav class="navbar navbar-expand-lg fixed-top navbar-dark background-black">
    <a class="navbar-brand" href="#"></a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
        <div class="navbar-nav mx-auto">
            <a class="nav-item nav-link nav-link-custom-1 nav-item-spacing" href="#">Home</a>
            <a class="nav-item nav-link nav-link-custom-1 nav-item-spacing" href="#">Curriculum</a>
            <a class="nav-item nav-link active nav-link-custom-1 nav-item-spacing" href="#">Portfolio</a>
            <a class="nav-item nav-link nav-link-custom-1 nav-item-spacing" href="#">Contatti</a>

            <!--Codice per il dropdown da: https://stackoverflow.com/questions/17904862/bootstrap-position-of-dropdown-menu-relative-to-navbar-item-->

            <!--<li class="nav-item dropdown">
                <a class="nav-link dropdown-toggle nav-link-custom-2 nav-item-spacing" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                    
            </li>-->
        </div>

        <!--Dropdown item end-->

    </div>
</nav>

<!--Main tag----------------------------------------------------------------------------------------------------------->

<main>

    <!--Name--------------------------------------------------------------------------------------------------------------->
    <section class="container-fluid">

        <div class="row">

            <div class="col-12 text-center background-black mb-5">
                <h1 class="page-title-font">PORTFOLIO</h1>
            </div>

        </div>

    </section>

    <!--Random selector------------------------------------------------------------------------------------------------>

    <!--Start container-->
    <footer class="container-fluid">

        <!--ROW 1-->
        <div class="row mb-5 mt-5">

            <!--ROW 1-A-->
                <div class="container-fluid">

                    <div class="row">

                        <div class="col-2 col-md-4"></div>

                            <div class="col-8 col-md-4">
                                <button type="button" class="link-btn-light btn btn-light w-100" id="random-select">Selezione</button>
                            </div>

                        <div class="col-2 col-md-4"></div>

                    </div>

                </div>

        </div>

    <!--CONTENT-------------------------------------------------------------------------------------------------------->

    <section class="container-fluid me-0 ms-0">

        <div class="row">

            <div id="tabs">

                <ul id="tab-id">

                    <li><a href="#heading1" id="pastichair">Pastichair</a></li>
                    <li><a href="#heading2" id="bella-e-brava">Bella e brava</a></li>
                    <li><a href="#heading3" id="personal-space">Personal space</a></li>

                </ul>

              

            <script type="text/javascript">

                $( "#tabs").tabs();

            </script>

        </div>

    </section>



    <!--Footer start------------------------------------------------------------------------------------------------------->

    <!--Red line-->
    <div class="border-top border-5 border-danger" style="width: 100%"></div>


    <!--Start container-->
    <footer class="container-fluid">

        <!--ROW 1-->
        <div class="row mb-5 mt-5">

            <!--ROW 1-A-->
            <div class="col-12 col-md-6 mb-5 mb-md-0">

                <div class="container-fluid">

                    <div class="row">

                        <div class="col-2 col-md-3"></div>

                        <div class="col-8 col-md-6">
                            <a href="#" class="link-btn-light btn btn-light w-100">Home<br>page</a>
                        </div>

                        <div class="col-2 col-md-3"></div>

                    </div>

                </div>

            </div>

            <!--ROW 1-B-->
            <div class="col-12 col-md-6">

                <div class="container-fluid">

                    <div class="row">

                        <div class="col-2 col-md-3"></div>

                        <div class="col-8 col-md-6">
                            <a href="#" class="link-btn-light btn btn-light w-100">Online<br>curriculum</a>
                        </div>

                        <div class="col-2 col-md-3"></div>

                    </div>

                </div>

            </div>

        </div>

        <!--ROW 2-->
        <div class="row mb-5 mt-5">

            <!--ROW 2-A-->
            <div class="col-12 col-md-6 mb-5 mb-md-0">

                <div class="container-fluid">

                    <div class="row">

                        <div class="col-2 col-md-3"></div>

                        <div class="col-8 col-md-6">
                            <a href="#" class="link-btn-light btn btn-light w-100">Online<br>portfolio</a>
                        </div>

                        <div class="col-2 col-md-3"></div>

                    </div>

                </div>

            </div>

            <!--ROW 2-B-->
            <div class="col-12 col-md-6">

                <div class="container-fluid">

                    <div class="row">

                        <div class="col-2 col-md-3"></div>

                        <div class="col-8 col-md-6">
                            <a href="#" class="link-btn-light btn btn-light w-100">Full contacts<br>and info</a>
                        </div>

                        <div class="col-2 col-md-3"></div>

                    </div>

                </div>

            </div>

        </div>

    </footer>

</main>

<!-- Javascript for Bootstrap --------------------->
<!-- Optional JavaScript; choose one of the two! -->

<!-- Option 1: Bootstrap Bundle with Popper -->
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
<!-- Javascript for Bootstrap END------------------>

<!-- My Javascript -->

<script src="../javascript/portfolio-javascript.js"></script>


</body>
</html>

Javascript

//Variable declaration

let button = document.getElementById("random-select");

let tab1 = document.getElementById("pastichair");

let tab2 = document.getElementById("bella-e-brava");

let tab3 = document.getElementById("personal-space");

//Array e function, così da creare un numero casuale tra 0 e 2

let array = ["headerA", "headerB", "headerC"];

button.addEventListener("click", tabRandom())

    function tabRandom () {
        let randomNumber = Math.floor(Math.random() * array.length);

        //If statement per selezionare tab casuale

        if (randomNumber === 0) {
            tab1.addEventListener("click", function (){
                document.getElementById("pastichair").click();
            });
        }

        if (randomNumber === 1) {
            tab2.addEventListener("click", function (){
                document.getElementById("bella-e-brava").click();
            });
        }

        if (randomNumber === 2) {
            tab3.addEventListener("click", function (){
                document.getElementById("personal-space").click();
            });
        }

    }

i have no idea how to fix this (php, javascript, mysql)

I have 3 spaces in a web page and through javascript I have to show the result of a query in each of them, the problem is that each result appears only in the last table and the other 2 remain empty.

This is a php page’s response when an action is performed:
{“result”:”1″,”testresult:{“nome”:”Marco,Matteo,Mattia”,”cognome”:”Rossi,Leone,Piero”,”tipo”:”3,14,44″}}

Then through javascript I would like to assign these values ​​to 3 empty spaces, like thi example:

|----------1----------|  |----------1----------|  |----------1----------|
| name:   Marco       |  | name:   Matteo      |  | name:   Mattia      |
| cognome:   rossi    |  | cognome:   Leone    |  | cognome:   Piero    |
| tipo: 3             |  | tipo: 14            |  | tipo: 44            |
|-----------------------------------------------------------------------|

but the result is this:

|----------1----------|  |----------1----------|  |----------1-------------------------|
| name:   undefined   |  | name:   undefined   |  | name:   Marco, Matteo, Mattia      |
| cognome:   undefined|  | cognome:   undefined|  | cognome:   Rossi, Leone, Piero     |
| tipo: undefined     |  | tipo: undefined     |  | tipo: 3, 14, 44                    |
|--------------------------------------------------------------------------------------|

here I leave you all my work.
PHP

$stmtcarte = $connection->prepare("SELECT GROUP_CONCAT(concat.nome) as nome, GROUP_CONCAT(concat.cognome) as cognome, GROUP_CONCAT(concat.tipo) as tipo FROM (SELECT nome, cognome, tipo FROM test WHERE categoria=? ORDER BY RAND() LIMIT 3 ) concat");

$categoria="test";
$stmtcarte->bind_param("s",$categoria);
$stmtcarte->execute();
$risultatocarte = $stmtcarte->get_result();
$numero_giocatori = $risultatocarte->num_rows;
$result=array("risultato"=>"1", "testresult"=>"");
while($rispostacarte=$risultatocarte->fetch_assoc()){
$result['risultato']="1";
$result['testresult']=$rispostacarte;

echo json_encode($result);

}
$stmtcarte->close();

JAVASCRIPT

    $(document).on("click",".test-btn", function(){
data = {'id':$(this).data('id')}
$.post("op2.php", data, function(response){
var Ogg = $.parseJSON(response);
    
    switch(Ogg.risultato){
        case "1":
            //
            //
            //
        $.each(Ogg,function(i,data){
                    
               
        if(data.tipo == "0"){
                          //
        }else{
                          //
        }

        setTimeout(function () {
        $(".Response").append("<div class='card-cont'><div id='cobr' class='pcdisplay center-block'> <div class='top-overlay'></div><div style='color:;' class='pcdisplay-nome'>"+ data.nome +"</div><div style='color:;' class='pcdisplay-cognome'>"+ data.cognome +"</div><div style='color:;' class='pcdisplay-tipo'>"+data.tipo+"</div><div class='pcdisplay-chem-style-name'></div></div></div><span style='display:block; text-align: center; color: #FFFF66; font-weight: bold;'>" + data.tipo + "</span></div>").hide().fadeIn(100);
                   
        }, i*900);
        });
        break;
        case "2":
            alert("//");
        break;
        case "3":
            alert("//");
        break;
        case "4":
            alert("//");
        break;
    }

});            

});

I hope someone can help me.
thank you all.

Window prompot(method) for use input text [duplicate]

please help

    <button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
  let person = prompt("Please enter your name", "Harry Potter");
  if (person != null) {
    document.getElementById("demo").innerHTML =
    "" + person + ""
  }
}
</script>

<input type=”text” name=”T1″ value=”javascript”

How can I add the field here?
“” + person + “”

input text value.

more efficient way of looping await / async? [duplicate]

I am trying to get messages given a list of message ids (Gmail API).

let messageIdList = [msg1: { id: 1234 }, ...]
 
let messages = [];

for (const msg of messageIdList) {
    const response = await gapi.client.gmail.users.messages.get({
        'userId': 'me',
        'id': msg.id,
        'format': 'full'
    })

    messages.push(response.result);
};

// do something with messages

I used a for … of loop because of this post, so it works…but it’s super slow (I assume it’s because it goes one at a time). What would be a way to go about making all of the API calls be fired at the same time but somehow knowing when all of them are complete?

Maximum update depth exceeded from Navigate component react-router-dom v6

I’m using react-router-dom v6 to control the route of my React Js app.

Here are the specifications:

  1. I’m creating the AuthenticationRoute and PrivateRoute components.

  2. The AuthenticationRoute component is used to wrap pages that the user doesn’t need to authenticate for examples SignIn, SignUp, ForgotPassword, and ResetPassword pages.

  3. The PrivateRoute component is used to wrap private pages (authentication is needed) for example Home page. Inside the PrivateRoute, there are some layouts. One of them is called the Dashboard layout to wrap the Drawer (Sidebar/Navigation) component and the Home page.

  4. If the user has not logged in via the SignIn page, the app would return the SignIn page.
    If the user has logged in, the app would return the Home page.

Here are the current conditions:

Note: The check sign (✅) represents the conditions I want while the cross sign (❌) represents the error or unwanted conditions.

  1. All of the specifications above are met. ✅

  2. The first time user runs the app, the SignIn page is returned because the user has not logged in. ✅

  3. If the user has not logged in and typed “/” route to the address bar (to access the Home page) via the SignIn page, the app will not redirect the user to the Home page instead of returning the SignIn page. ✅

  4. If the user successfully logged in via the SignIn page, the app would return the Home page (with “/” route). ✅

  5. If the user has logged in and typed “/sign-in” route to the address bar (to access the SignIn page) via the Home page, the app return error: ❌

Warning: Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render.
    at Navigate (https://5xxrw.csb.app/node_modules/react-router/index.js:247:12)
    at AuthenticationRoute (https://5xxrw.csb.app/src/components/Routes/AuthenticationRoute.jsx:21:26)
    at Routes (https://5xxrw.csb.app/node_modules/react-router/index.js:306:18)
    at App
    at Router (https://5xxrw.csb.app/node_modules/react-router/index.js:266:18)
    at BrowserRouter (https://5xxrw.csb.app/node_modules/react-router-dom/index.js:284:18)

The app should navigate back the user to the Home page (“/” route) instead of returning the error.

Here is the playground: https://codesandbox.io/s/stackoverflow-auth-private-routes-5xxrw

I did a similar thing using react-router-dom v5 but didn’t return the error. Everything was fine.

So, what’s the solution for this case?

Difference between Python’s cv2.imread(), Tensorflow’s JS tf.node.decodeImage()

Comparing the printings for a same image between the two mentioned functions I get different information.
For example using a 100×100 jpeg image in Python like:

path = "./test.jpeg"
training_data = []
pic = cv2.imread(path)
pic = cv2.cvtColor(pic,cv2.COLOR_BGR2RGB)
training_data.append(pic)
print(training_data[0][0])

For the first three rows, my print shows:

[[180  71  51]
 [233 145 125]
 [206 155 136]

Then, using the same image in VS Code with tf.node like:

const file_path   = "./test.jpeg";
const img = fs.readFileSync(file_path);
const tensor = tf.node.decodeImage(img, 3);
console.log(tensor.print())

For the same three rows, my print shows in console:

 [[[177, 70 , 50 ],
   [231, 144, 124],
   [201, 153, 133],

Altough the values are very similar, they are clearly different. Inspecting other values, they even match some times. So my question is what’s the difference between these two functions that generate different results for the same image? Also, what result should I expect from tf.browser.fromPixels(), the Python like result or tf.node?

Error deploying to vercel but no errors when I run npm run build

I’m trying to deploy my project to Vercel, so before I push my changes to GitHub I run npm run build, and it builds fine with no errors but when Vercel tries to build I get an error that it can not read properties of undefined (I believe this is because the function that makes the API call did not execute). How can I fix this?

Code that I think is causing the issue

export const getStaticProps = async () => {
    const popularCountries = ["Netherlands", "Poland", "Canada"]
    let countryData = [];
    const date = getDate();
    const promise1 = popularCountries.map(async country => {
        const options = {
            method: 'GET',
            url: 'https://covid-19-statistics.p.rapidapi.com/reports',
            params: {
              region_name: country,
              date: date
            },
            headers: {
              'x-rapidapi-host': 'covid-19-statistics.p.rapidapi.com',
              'x-rapidapi-key': process.env.RAPID_API_KEY
            }
        };
        await axios.request(options).then(response => {
            const data = response.data.data;
            const country_name = data[0].region.name;
            const date = data[0].date;
            const iso = data[0].region.iso;
            let cases = 0;
            let deaths = 0;
            data.map(item => {
                cases += item.confirmed;
                deaths += item.deaths;
            })
            countryData.push({
                "country_name": country_name,
                "date": date,
                "cases": cases,
                "deaths": deaths,
                "iso": iso
            })
        })
        .catch((error) => {
            console.error("error - ", error);
        });
        return countryData;
    })
    const returnedData = await Promise.all(promise1);
    const data = returnedData[0];

    return {
        props: { data },
        revalidate: 43200
    }
}

I’m stuck because I don’t get errors on my end so I’m not sure how to debug/fix this.

Discord JS v13 Get Status of Specific User

For the bot I’m writing I am trying to get the current status of the user that started an Interaction. This is my code, which seems perfectly fine according to the discord.js docs.

console.log(interaction.member.presence)

When running this, it outputs null.

enter image description here

Why is this happening? I’ve seen some people use fetching but I can’t seem to implement that into my app.

How can I make some arrow keys that can manipulate a js-tray-slider?

I am using this tutorial:
https://tympanus.net/codrops/2019/09/17/how-to-build-a-color-customizer-app-for-a-3d-model-with-three-js/

to create a similar concept.
However, in the color selection area (the swatches), I don’t want only to be able to use the mouse to “scroll” back and forth. I also want to be able to use some arrow keys similar to these ones:
Arrow keys to controls back and forth

However, I am having a hard time figuring out how this can be done, so I would appreciate some help.

Is this something that can be done?

Also, there is problem when you use the mouse or even use touch devices, that it will select colors while trying to slide back and forth, which is quite annoying because you can’t scroll without hitting every color you touch on the way.

How can this be fixed as well?

You can try out the whole site (the tutorial) on codepen here:

'https://codepen.io/kylewetton/pen/jONpxpa'

But I have also made a version with more colors, that is a little more simple:
js fiddle

SImple christmas tree in JS

I’m trying to make a trunk for this christmas tree. I want to use if so it can be with only one loop as in code. Any ideas how to do it? Thanks.

function Tree() {
    const star = "*";
    for (let i = 1; i <= 6; i++) {
      document.write(`${star.repeat(i)}<br/>`);
    }
  }

  Tree();