Carousel randomly breaks and throws “Cannot read properties of undefined”. Any suggestions on how to fix?

I’m trying to code my own portfolio website (I am new to this..), and I have 9 images that open their own modal using Javascript. Each of those modals has a carousel in them with 1-5 pictures each. The code I’m currently using works, but about 10% of the time, the button won’t move to the next image, or it only moves between half of the images or the carousel breaks entirely, and the console displays

Uncaught TypeError: Cannot read properties of undefined (reading 'classList')
    at moveToNextSlide (main.js:121:22)
    at HTMLButtonElement.<anonymous> (main.js:63:66)

I’ve console logged the slides and next button each time you open a modal, and it shows a proper list of items, so it doesn’t seem to have problems grabbing all the slide-items or the button, but sometimes it still breaks. Not sure what to do, or if I should just code the carousel entirely different.

My HTML sorta looks like

<dialog class="modal">
    <div class="modal-container">
        <div class="image-slide">

            <div class="slide-item slide-item-visible">
                <img src="" alt="">
            </div>

            <div class="slide-item">
                <img src="" alt="">
            </div>

            <div class="slide-actions">
                <button class="slide-next"></button>                                    

And Javascript

openPortfolioModal.forEach((grid, index) => grid.addEventListener("click", () => {

    modal[index].showModal()

    let slides = modal[index].querySelectorAll(".slide-item")

    let slideNext = modal[index].querySelector(".slide-next")
    slideNext.addEventListener("click", () => moveToNextSlide(slides))
}

function hideAllSlides(x) {
    for (let slide of x) {
        slide.classList.remove("slide-item-visible")
    }
}

let slidePosition = 0

function moveToNextSlide(x) {
    hideAllSlides(x)
    let totalSlides = x.length


    if (slidePosition === totalSlides - 1) {
        slidePosition = 0
    } else {
        slidePosition++
    }

    x[slidePosition].classList.add("slide-item-visible")
}

Error with NPM install on new Macbook Pro

I just installed node.js on a new Macbook Pro. Trying to run npm install and getting this error:

npm ERR! code ENOENT
npm ERR! syscall open
npm ERR! path /Users/user0/package.json
npm ERR! errno -2
npm ERR! enoent ENOENT: no such file or directory, open '/Users/user0/package.json'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent 

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/user0/.npm/_logs/2022-04-17T01_26_17_892Z-debug-0.log

I don’t see aa package.json file in the directory specified, only a package-lock.json file.

How to fix node.js error when trying to execute?

I am starting to work with server side (node.js), and am having some errors when I try to execute it. I am using 127.0.0.1:80 as the server, but I am experiencing some errors when I try to run it.

Console:

Server running at http://127.0.0.1:80/
node:events:505
      throw er; // Unhandled 'error' event
      ^

Error: Listen EACCES: permission denied 127.0.0.1:80
  //at Server.setupListenHandle [as _listen2] (node:net:1363:21)
  at listenInCluster (node:net:1428:12)
  at doListen (node:net:1567:7)
  at processTicksAndRejections (node:internal/process/task_queues:83:21)//
Emitted 'error' event on Server instance at:
  at emitErrorNT (node:net:1407:8)
  at processTicksAndRejections (node:internal/process/task_queues:83:21) {
       code: 'EACCES',
       errno: -13,
       syscall: 'listen',
       address: '127.0.0.1',
       port: 80
 }

Javascript:

 var http = require('http');
 http.createServer(function (req, res) {
   res.writeHead(200, {'Content-Type': 'text/plain'});
   res.end('Hello Worldn');
 }).listen(80, '127.0.0.1');
 console.log('Server running at http://127.0.0.1:80/');

package.json:

     {
   "name": "test-web-server",
   "version": "1.0.0",
   "description": "Node.js test server. Use for whatever bs you want to do",
   "main": "index.js",
   "scripts": {
     "start": "node server.js",
     "test": "echo "Error: no test specified" && exit 1"
   },
   "author": "PlazL",
   "license": "ISC"
 }

Time out session in R Shiny

I followed this question Login Screen For My Shiny App Does Not Time Out, but I want to add the warning alert before time out. When the alert window popped up, but then it got stuck and the app never close even though the time ran out.

Any thought?

library(shiny)
library(leaflet)


timeoutSeconds <- 60

inactivity <- sprintf("function idleTimer() {
var t = setTimeout(logout, %s);
var timeout = setTimeout(alertFunc, %s);

window.onmousemove = resetTimer; // catches mouse movements
window.onmousedown = resetTimer; // catches mouse movements
window.onclick = resetTimer;     // catches mouse clicks
window.onscroll = resetTimer;    // catches scrolling
window.onkeypress = resetTimer;  //catches keyboard actions

function alertFunc(){
  alert('You are about time out!')
  t = setTimeout(logout, %s);
}


function logout() {
Shiny.setInputValue('timeOut', '%ss')
}

function resetTimer() {
clearTimeout(t);
t = setTimeout(logout, %s);  // time is in milliseconds (1000 is 1 second)
}
}
idleTimer();", timeoutSeconds*1000, timeoutSeconds*500,timeoutSeconds*500,timeoutSeconds, timeoutSeconds*1000)


ui <- fluidPage(
  tags$script(inactivity),    
  leafletOutput("mymap")
  
)

server <- shinyServer(function(input,output,session){
  
  observeEvent(input$timeOut, { 
    print(paste0("Session (", session$token, ") timed out at: ", Sys.time()))
    showModal(modalDialog(
      title = "Timeout",
      paste("Session timeout due to", input$timeOut, "inactivity -", Sys.time()),
      footer = NULL
    ))
    session$close()
  })
  
  points <- eventReactive(input$recalc, {
    cbind(rnorm(40) * 2 + 13, rnorm(40) + 48)
  }, ignoreNULL = FALSE)
  
  output$mymap <- renderLeaflet({
    leaflet() %>%
      addProviderTiles(providers$Stamen.TonerLite,options = providerTileOptions(noWrap = TRUE)) %>% 
      addMarkers(data = points())
  })
  
})
runApp(list(ui = ui, server = server))

problem uploading image from react native app to node.js server

i’m building a marketplace react native app (with expo) where the user post his products.
The user enters the product’s information in addition to uploading an image from his gallery to the product. I have trouble sending that image then uploading to my backend folder (i’m using node.js/express). The image picker component is successfully upload the image i do append it formaData object but i have trouble posting it.
here’s my code axios api + react native code

AXIOS API CONFIG

import axios from "axios";
const baseURL = `http://localhost:5000/`;

export default axios.create({
  baseURL: baseURL,
});
import axiosApi from "../../api/axios";

const handleSubmit = async (listing, { resetForm }) => {
    const data = new FormData();
    data.append("nom", listing.titre);
    data.append("description", listing.description);
    data.append("category", listing.category.label);
    data.append("categoryId", listing.type.id);
    data.append("categoryPath", listing.type.path);
    data.append("categoryType", listing.type.label);
    data.append("taille", listing.taille.label);
    data.append("marque", listing.marque.label);
    data.append("prix", listing.prix);

    listing.images.forEach((image, index) =>
      data.append("images", {
        name: "image" + index,
        type: "image/jpeg",
        uri: image,
      })
    );

    await axiosApi
      .post(
        "/products/addProduct",
        data
      )
      .then(function (response) {
        // handle success
        console.log(response.data);
      })
      .catch(function (error) {
        // handle error
        console.log(error);
      });

  };

when i console.log the data formData object i get following

FormData {
  "_parts": Array [
    Array [
      "nom",
      "1123",
    ],
    Array [
      "description",
      "Eeeee",
    ],
    Array [
      "category",
      "Enfants",
    ],
    Array [
      "categoryId",
      316,
    ],
    Array [
      "categoryPath",
      ",Enfants,Garçon,",
    ],
    Array [
      "categoryType",
      "Pulls & sweets",
    ],
    Array [
      "taille",
      "1-3 mois / 56-62 cm",
    ],
    Array [
      "marque",
      "Puma",
    ],
    Array [
      "prix",
      "31232132",
    ],
    Array [
      "images",
      Object {
        "name": "image0",
        "type": "image/jpeg",
        "uri": "file:///Users/zakisb/Library/Developer/CoreSimulator/Devices/83E12EA5-E8FA-4850-82C1-84021B25450D/data/Containers/Data/Application/AF39E1CC-D48A-4D8E-A28B-D82718E12096/Library/Caches/ExponentExperienceData/%2540anonymous%252FLokazz-app-5f4724db-b9d7-45aa-a8ca-ac5acf2f4780/ImagePicker/DA37F5A0-1717-425D-BB49-C2B561FDCBF3.jpg",
      },
    ],
  ],

meaning the image is being updated successfully and the problem reside in my request

here’s my backend code

const multer = require("multer");
//multer configuration
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "./images");
  },
  filename: function (req, file, cb) {
    cb(null, Date.now() + file.originalname);
  },
});

router.post(
  "/products/addProduct",
  upload.array("images"),
 
  async (req, res) => {
   /// when i remove this part of the code i receive the ok response in my front-end
      var images = [];
      req.files.forEach(function (item, index) {
      images.push(item["name"]);
    });

    
    try {
      // this doesn't get sent which means there's a problem uploading the file
      res.send("ok");
    } catch (err) {
      res.send("Error " + err);
    }
  }
);

NOTE that i tried uploading an image using Insomnia api client, i uploaded an image from my desktop, by hitting my api and the image gets added successfully to my server “images” folder. meaning the API is working fine and there’s a problem with my axios request . PLEASE HELP ME OUT !

Is there a way to create an array of all attributes from a website’s HTML?

I’d like to create a program that will allow me to input a hyperlink address and the output would display a list of attribute contents. For example, inputting a Netflix genre hyperlink for Adventure Movies and receiving a list output for all the movie titles and individual movie title links for that genre.

I looked at the View Page Source data for this genre and saw this code:

<script type="application/ld+json">
{"@context":"http://schema.org","@type":"ItemList","name":"Adventure Movies","itemListElement":
[{"@type":"ListItem","position":1,"item":{"@type":"Movie","name":"The Adam Project","url":"https://www.netflix.com/title/81309354"}},
{"@type":"ListItem","position":2,"item":{"@type":"Movie","name":"Red Notice","url":"https://www.netflix.com/title/81161626"}}

I’m thinking that there’s a way to retrieve the “name” and “url” attributes for each item in the list and display them in an array?

Unfortunately, I’m not very familiar with programming beyond some basic HTML, CSS, and Javascript. I’m not sure what programming language would be needed to do this. It seems like the script is in JSON – would I use JSON to do this?

Any and all help is greatly appreciated!

JS map generates double square brackets

I use the following to merge sub-arrays:

var myArray = [
        {
            "QuestionId": 1,
            "mySeries": [{ "name": "Male", "data": [1] }],
            "mySeries1": [
                { "name": "Male", "data": [0] },
                { "name": "Female", "data": [0] },
                { "name": "Unknown", "data": [0] }
            ],
            "mySeries3": []
        },
        {
            "QuestionId": 2,
            "mySeries": [{ "name": "Banana", "data": [1] }],
            "mySeries1": [
                { "name": "Orange", "data": [0] },
                { "name": "Banana", "data": [0] },
                { "name": "None", "data": [0] }
            ],
            "mySeries3": []
        }
    ];
    var res = [];
    for (let i = 0; i < myArray.length; i++) {
        res = myArray[i].mySeries1.map(obj => myArray[i].mySeries.find(o => o.name === obj.name) || obj);
        myArray[i].mySeries3.push(res);

It works; however, I get double square brackets:

"mySeries3": **[** [
                  { "name": "Orange", "data": [0]},
                  { "name": "Banana","data": [1]},
                  {"name": "None", "data": [0] 
              ]  **]**

Is push the correct way?

Lightgallery jsimage background in windows popup

I using lightgallery.js to show zoom image. It is working fine when the image is displayed from browser. But when I display an image from a popup window, then the entire popup window comes in background in the zoom image mode.

Please suggest how to remove the popup window from the background in zoom image mode.

How do I make time between each code key click I press?

I want to ask you how I could make time between each “Space” click I squeeze. I want the bullet to go separate from the bullet and I am not allowed to perform the function after that certain time between clicks.
If I made some errors or if you have an idea how this code could look better, feel free to write me your ideas below, I am a beginner, I am new to javascript. Thanks.
My code:

<!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>

    <style>
      * {
        padding: 0;
        margin: 0;
        box-sizing: border-box;
      }

      .pistol {
        background-color: black;
        width: 100px;
        height: 30px;
        position: absolute;
        top: 70px;
      }

      .bullet {
        position: absolute;
        width: 60px;
        height: 3px;
        background-color: rgb(151, 151, 0);
        left: 110px;
      }

      .bullet p {
        font-size: 28px;
        text-align: center;
      }

      ul {
        margin: 0;
        padding: 0;
        font-size: 30px;
        border: 3px solid black;
        text-align: center;
      }

      ul > span:not(:last-child) {
        margin-right: 30px;
      }
    </style>
  </head>

  <body>
    <div class="pistol"></div>
    <ul>
      <span>ArrowUp to go Up</span>
      <span>ArrowDown to go Down</span>
      <span>Space to shot</span>
    </ul>

    <script>
      let body = document.querySelector("body");
      let pistol = document.querySelector(".pistol");
      pistol.style.top = "70px";
      let pistolSteps = 70;

      function stepsDown() {
        pistolSteps += 5;
        pistol.style.top = pistolSteps + "px";
        if (pistolSteps >= 550) {
          pistolSteps = 550;
          pistol.style.top = "550px";
        }
      }

      function stepsUp() {
        pistolSteps -= 5;
        pistol.style.top = pistolSteps + "px";

        if (pistolSteps <= 70) {
          pistolSteps = 70;
          pistol.style.top = "70px";
        }
      }

      let gunStart = function () {
        let bulletSteps = 13;
        let bullet = document.createElement("div");
        bullet.className = "bullet";
        let bulletPosition = parseInt(pistol.style.top);
        bullet.style.top = bulletPosition + 13 + "px";
        body.appendChild(bullet);
        let bulletShot = setInterval(() => {
          bulletSteps++;
          bullet.style.left = bulletSteps + 100 + "px";

          if (bullet.style.left > "400px") {
            bullet.style.backgroundColor = "red";
            bullet.innerHTML = `<p>⚠️</p>`;
          }
          if (bullet.style.left == "700px") {
            bullet.remove();
          }
        }, 10);
      };
      window.addEventListener("keydown", function (e) {
        if (e.code == "Space") {
          gunStart();
        }
      });

      window.addEventListener("keydown", function (e) {
        if (e.code == "ArrowDown") {
          stepsDown();
        }
      });

      window.addEventListener("keydown", function (e) {
        if (e.code == "ArrowUp") {
          stepsUp();
        }
      });
    </script>
  </body>
</html>

How to sort object entries by key order from another array? [closed]

Let’s say I have an object

const obj = {
  foo: 1,
  zoo: 2,
  abc: 3,
}

And suddenly I want to make an array out of it via Object.entries(obj) which returns [['foo', 1], ['zoo', 2], ['abc', 3]]. Now how can I sort this two-dimensional array by order from another array ['abc', 'foo', 'zoo']? The end result of sorting algorithm should be

[['abc', 3], ['foo', 1], ['zoo', 2]]

Stylizing Array Content within a div

I’m not sure why my content is appear the way it is… but I think that there are not new divs being created and rather all of the array content is going into that one div. I attached a photo of how I would like to have my array content organized… do I need to put the text into a h# or p instead?

Sketch:

here is my sketch of what i would like it to look like... ideally

Current display:
what it looks like now..
HTML:

    <div class="data_cards">
  <div class="data_display">
    <div id="data_imgs" width="20%" height="auto"></div>
    <div id="data_printCovers"></div>
    <div id="data_brand"></div>
    <div id="data_datePublished"></div>
  </div>
</div>

CSS:


.img {
    margin-left: 2vh;
    width: 20vw;
    height: auto;
  }
.data_cards {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    flex-direction: column;
    overflow:wrap;
  }
.data_display {
    display: flex;
    justify-content: space-between;
    /* flex-direction: row; */
    /* flex-direction: column;
    flex-wrap: wrap; */
    /* align-content: space-between; */

    width: 70vw;
    font-family: 'Inter';
    font-size: 2vw;
  } 

JAVASCRIPT:

const div1 = document.getElementById("data_brand");
const div2 = document.getElementById("data_datePublished");
const div3 = document.getElementById("data_printCovers");
const div4 = document.getElementById("data_imgs");

async function getPeople() {
  const response = await fetch(
    "https://api.airtable.com/v0/appi4i01ehJf6jzVP/Table%201?api_key=keyOInlFujAUpPC0f"
  );
  const data = response.json();
  return data;
}

getPeople().then((data) => {
  makeList(data.records);
});

function makeList(records) {
  console.log(`making list of ${records.length} records...`);

  for (let i = 0; i < records.length; i++) {
    const recordField = records[i].fields;
    const attachments = recordField.Attachments;

    if (attachments) {
      const listItem1 = document.createElement("div");
      const listItem2 = document.createElement("div");
      const listItem3 = document.createElement("div");
      const listItem4 = document.createElement("div");

      listItem1.appendChild(composeText(recordField.Brand));
      listItem2.appendChild(composeText(recordField.DatePublished));
      listItem3.appendChild(composeText(recordField.PrintCovers));
      listItem4.appendChild(composeImage(attachments));

      div1.appendChild(listItem1);
      div2.appendChild(listItem2);
      div3.appendChild(listItem3);
      div4.appendChild(listItem4);
    }
  }
}

function composeText(text) {
  return document.createTextNode(text);
}

function composeImage(attachments) {
  const attachment = attachments[0];
  const img = document.createElement("img");
  img.setAttribute("id", attachment.id);
  img.setAttribute("src", attachment.thumbnails.full.url);

  return img;
}

Vue3 and Vue-Router cannot access the parameters with the $route object in production but can in dev

I’m having some bad time with the build of a Vue3 app for production, literally 90% of my scripts are broken in production and that’s related to my variables being undefined in production, I really don’t know why this occurs. But for one of them I have a concrete example :

I access a parameter value in my route using this.$route.params.myParameter which works totally fine in dev mode, but in prod it’s undefined and crash the whole thing

I can edit the question with code snipets but I don’t think it’s required

use variable req.body in mongoose

My Mongoose schema:

         var book_listSchema = new mongoose.Schema({

                 userId:{type: String, required: true},
                 first_name: { type: String, required: true},
                 last_name:{ type: String, required: true},
                 newList: [],
                                     });

In Express I have the post function

router.post('/fileExpress/:title&:author?',...

var list_name = req.body.list;
var title = req.params.title;
var author = req.params.author;

Inside this post function I have the Mongoose command

  `book_list.findOne({"userId":req.userContext.userinfo.sub,"newList.list_name.book_name":title`

The code section newList.list_name.book_name does not work with the variable “list_name”. It does work when I type in the name of the actual list.

I am using this because there will be lists with many different names and one function needs to work for all of them.

Why is Math.hypot so slow?

I am performing a ton of distance calculations in my code, to the point where Math.sqrt(a*a + b*b) is run hundreds of thousands of times.

I then recalled how there is a Math.hypot function that does exactly this. However, in all the testing I’ve done, it seems significantly slower than doing Math.sqrt. For example, if you run the following code:

var i, tmp, x = 55, y = 66, end, ini = performance.now();

// Math.sqrt operation
i = 0;
ini = performance.now();
tmp = 0;
while(i++ < 2000000){
  tmp += Math.sqrt(x*x + y*y)
}
end = performance.now();
console.log(tmp, "Math.sqrt operation: " + (end - ini) + " ms");

// Math.hypot

i = 0;
ini = performance.now();
tmp = 0;
while(i++ < 2000000){
  tmp += Math.hypot(x, y)
}
end = performance.now();

console.log(tmp, "Math.hypot: " + (end - ini) + " ms");

On my computer the hypot function is 5x faster. And I tried a benchmarking site as well and there it was 25x slower.

What is causing the hypot function to be so slow? Should it not be used at all for performance critical distance calculations, or am I doing something wrong?

Live Soccer Score [closed]

I’m doing Live Soccer Score for my project but the time on the score doesn’t show up on the scoresheet. I have a html file, body and a json file on Visual Studio where I’m doing this project. Maybe I have to create a ‘div’ in the html but I’m not sure. Any help would be appreciated. It does only show the time on the first game or the game on the top.
Here is my JavaScript:

var elapsedTime = document.querySelector("#elapsed");
var homeTeamLogo = document.querySelector("#homeLogo");
var homeTeamName = document.querySelector("#homeName");
var awayTeamLogo = document.querySelector("#awayLogo");
var awayTeamName = document.querySelector("#awayName");
var lastMatchGoals = document.querySelector("#goals");
 matchTable = document.querySelector("#matchTable");




function addMatchTile(data){




    var matchTile = document.createElement('div');
    matchTile.classList.add("match-tile");

    //Home team image and name
    var homeTeam = document.createElement('div');
    homeTeam.classList.add("team");

    var homeTileLogo = document.createElement('img');
    var homeTileName = document.createElement('p');

    homeTileLogo.src = data['teams']['home']['logo'];
    homeTileName.innerHTML = data['teams']['home']['name'];

    var awayTeam = document.createElement('div');
    awayTeam.classList.add("team");

    var awayTileLogo = document.createElement('img');
    var awayTileName = document.createElement('p');

    awayTileLogo.src =data['teams']['away']['logo'];
    awayTileName.innerHTML = data['teams']['away']['name'];

    homeTeam.appendChild(homeTileLogo);
    homeTeam.appendChild(homeTileName);

    awayTeam.appendChild(awayTileLogo);
    awayTeam.appendChild(awayTileName);

    var score = document.createElement('p');
    score.innerHTML = data['goals']['home'] + "  -  "+ data['goals']['away'];


    matchTile.appendChild(homeTeam);
    matchTile.appendChild(score);
    matchTile.appendChild(awayTeam);








    matchTable.appendChild(matchTile);



}






fetch("https://api-football-v1.p.rapidapi.com/v3/fixtures?live=all", {
    "method" : "Get",
    "headers" : {
        "x-rapidapi-host": "api-football-v1.p.rapidapi.com",
        "x-rapidapi-key": "my key",

    }

})
.then(response => response.json().then(data => {
   var matchesList = data['response'];
   var fixture = matchesList[0]['fixture'];
   var goals = matchesList[0]['goals'];
   var teams = matchesList[0]['teams'];
   console.log(matchesList.length);

     //Now let's set our first match
   elapsedTime.innerHTML = fixture['status']['elapsed'] + "'";
   homeTeamLogo.src = teams['home']['logo'];
   homeTeamName.innerHTML = teams['home']['name'];
   awayTeamLogo.src = teams['away']['logo'];
   awayTeamName.innerHTML = teams['away']['name'];
   lastMatchGoals.innerHTML = goals['home']+ " - " + goals['away'];

    
    for(var i = 1; i<matchesList.length;i++){
        addMatchTile(matchesList[i]);
    }  


}))
.catch(err => {
    console.log(err);
});