Having problems with the npx command in VS code terminal not working

I am getting into react/node js, etc. I am following through with a tutorial and a book. One of the first steps is to set up an environment and I followed through the previous step. Installed VS Code then Node.js, etc. When I try to set up an environment in VS code using the code shown in the tutorial( npx create-react-app inv-man ). It gives me errors. To be more precise error npm ERR! errno -4058.

enter image description here

Can someone show me where I have made a mistake?

I tried setting up an environment in VS code for a React app with the following command:

npx create-react-app inv-man

And I got this error:

enter image description here

How to Access Posted Data in Netlify Edge Function

When using netlify edge functions I can’t access the posted data.

For example, from the front end we post this code:

fetch('/foo', {
  method: 'POST',
  body: JSON.stringify({ foo: 'bar' })
})
.then(res => res.json())
.then(data => console.log(data))

The in our netlify.toml

[[edge_functions]]
  path = "/foo"
  function = "foo"

and in our edge function foo.js

export default async (request, context) => {
  console.log(request)
  return Response.json({ msg: "Hello, World from the edge!" }, {
    headers: { 
      'Content-Type': 'application/json',
      'Access-Control-Allow-Origin': '*'
    }
  })
}

If I console.log(request.body) I get [foo] ReadableStream { locked: false }

How can we access the posted data from within the netlify edge function? I looked all over and there is no information on this.

console.log(request) outputs the following object:

[foo] EdgeRequest {
  bodyUsed: false,
  headers: Headers {
    accept: "*/*",
    "accept-encoding": "gzip, deflate, br",
    "accept-language": "en-US,en;q=0.9",
    "cache-control": "no-cache",
    connection: "close",
    "content-length": "16",
    "content-type": "text/plain;charset=UTF-8",
    cookie: "_ga=GA1.1.1939799698.1701538319; _gcl_au=1.1.1892117818.1701538319; _ga_E63KG40SSM=GS1.1.1701736526."... 132 more characters,
    host: "localhost:8888",
    origin: "http://localhost:8888",
    pragma: "no-cache",
    referer: "http://localhost:8888/",
    "sec-ch-ua": '"Not_A Brand";v="8", "Chromium";v="120", "Google Chrome";v="120"',
    "sec-ch-ua-mobile": "?0",
    "sec-ch-ua-platform": '"macOS"',
    "sec-fetch-dest": "empty",
    "sec-fetch-mode": "cors",
    "sec-fetch-site": "same-origin",
    "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0."... 17 more characters,
    "x-forwarded-for": "::1",
    "x-nf-blobs-info": "eyJ1cmwiOiJodHRwOi8vbG9jYWxob3N0OjU4NjU4IiwidG9rZW4iOiJiMGJiNThmNy1hN2I1LTQxZWYtODhkNS00N2QzNmQ4ZTEz"... 8 more characters,
    "x-nf-deploy-id": "0",
    "x-nf-request-id": "01HHQQQAD0S41ZV5EFJ06QE20F"
  },
  method: "POST",
  redirect: "follow",
  url: "http://localhost:8888/foo"
}

Chrome (d8) regression test

why i can’t run regress file in d8 that contains assert like assertThrows?does it need any specific flag?

ReferenceError: assertThrows is not defined assertThrows( ^ ReferenceError: assertThrows is not defined

i tried flags like –harmony-import-attributes and –harmony-import-assertions

When the compass points north, it spins 360 degrees each time. Is there any way to stop that behavior?

Frontend is working fine but when it points north everytime, it suddenly rotates 360. i did some changings in the handler function but the result goes same.

HTML Structure:

The HTML document starts with the usual structure, including the DOCTYPE declaration, language setting, and metadata.
The contains a flex container with a vertical direction (flex-direction: column) and a height of 100 viewport height (height: 100vh).
Compass Styles:

The compass is styled using CSS.
The .compass class defines the appearance of the compass, including its size, border-radius, and a box-shadow for a visual effect.
The .arrow class represents the arrow within the compass and is styled to create a red triangular arrow at the top of the compass.
The .compass-circle and .my-point classes are used for the background image of the compass and a custom point marker, respectively.
The .start-btn class styles a button to start the compass.
JavaScript Logic:

JavaScript is used to add interactivity and dynamic behavior to the compass.
The script begins by selecting relevant elements from the DOM, including the compass circle, the custom point marker, the start button, and checking if the device is running on iOS.
The init function sets up event listeners and initializes geolocation.
Compass Initialization:

The startCompass function is triggered when the “Start compass” button is clicked. It requests permission to use the device orientation API on iOS devices.
If permission is granted, the handler function is attached to the deviceorientation or deviceorientationabsolute event depending on the device.
Handling Device Orientation:

The handler function is responsible for updating the compass based on the device’s orientation.
It calculates the compass heading (compass) and updates the CSS transform property of the compass circle to rotate it accordingly.
The pointDegree variable is used to determine the angle between the device’s orientation and a predefined point (Qibla geolocation).
Handling Geolocation:

The locationHandler function is triggered when the device’s geolocation is obtained.
It calculates the angle (pointDegree) between the device’s location and the predefined Qibla geolocation.
Calculating Degree to Point:

The calcDegreeToPoint function calculates the angle between the device’s location and the predefined Qibla geolocation using latitude and longitude.
Initialization:

The init function is called to set up event listeners and initialize the compass.

The handler function explaination:
compass = e.webkitCompassHeading || Math.abs(e.alpha – 360);

e refers to the event object passed to the handler function. This object contains information about the device’s orientation.
e.webkitCompassHeading is used to get the compass heading in degrees on devices that support the WebKit-specific webkitCompassHeading property. This property provides the absolute heading in degrees, where 0 degrees points north.
If webkitCompassHeading is not available (for example, on non-WebKit browsers), the code falls back to using e.alpha. e.alpha represents the device’s orientation around its z-axis in degrees, with 0 degrees pointing towards the top of the screen.
Since the alpha value can be negative or greater than 360, Math.abs(e.alpha – 360) is used to ensure the resulting value is positive and within the range of 0 to 360 degrees.
The calculated compass value is then assigned to the variable compass.
compassCircle.style.transform = translate(-50%, -50%) rotate(${-compass}deg);

This line updates the CSS transform property of the .compass-circle element, which represents the circular background of the compass.
The translate(-50%, -50%) part centers the rotation point of the compass at its center. It shifts the rotation axis to the center of the compass element.
The rotate(${-compass}deg) part rotates the compass circle by the negative value of the compass variable. This rotation effectively simulates the movement of a compass needle pointing towards the specified compass heading.
The negative sign is used to ensure that the rotation is in the correct direction. For example, if the compass heading is 30 degrees, the rotation would be -30 degrees to make the compass needle point in the correct direction.
The resulting transform property visually rotates the compass circle based on the calculated compass heading, giving the appearance of a dynamic and responsive compass.

    
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta http-equiv="X-UA-Compatible" content="ie=edge" />
  <title>Document</title>
  <style>
    body {
      display: flex;
      flex-direction: column;
      height: 100vh;
    }

    .compass {
      position: relative;
      width: 320px;
      height: 320px;
      border-radius: 50%;
      box-shadow: 0 0 15px rgba(0, 0, 0, 0.2);
      margin: auto;
    }

    .compass>.arrow {
      position: absolute;
      width: 0;
      height: 0;
      top: -20px;
      left: 50%;
      transform: translateX(-50%);
      border-style: solid;
      border-width: 30px 20px 0 20px;
      border-color: red transparent transparent transparent;
      z-index: 1;
    }

    .compass>.compass-circle,
    .compass>.my-point {
      position: absolute;
      width: 90%;
      height: 90%;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      transition: transform 0.1s ease-out;
      background: url(https://purepng.com/public/uploads/large/purepng.com-compasscompassinstrumentnavigationcardinal-directionspointsdiagram-1701527842316onq7x.png) center no-repeat;
      background-size: contain;
    }

    .compass>.my-point {
      opacity: 0;
      width: 20%;
      height: 20%;
      background: rgb(8, 223, 69);
      border-radius: 50%;
      transition: opacity 0.5s ease-out;
    }

    .start-btn {
      margin-bottom: auto;
    }
  </style>
</head>

<body>
  <div class="compass">
    <div class="arrow"></div>
    <div class="compass-circle"></div>
    <div class="my-point"></div>
  </div>
  <button class="start-btn">Start compass</button>
</body>
<script>
  const compassCircle = document.querySelector(".compass-circle");
  const myPoint = document.querySelector(".my-point");
  const startBtn = document.querySelector(".start-btn");
  const isIOS =
    navigator.userAgent.match(/(iPod|iPhone|iPad)/) &&
    navigator.userAgent.match(/AppleWebKit/);

  function init() {
    startBtn.addEventListener("click", startCompass);
    navigator.geolocation.getCurrentPosition(locationHandler);

    if (!isIOS) {
      window.addEventListener("deviceorientationabsolute", handler, true);
    }
  }

  function startCompass() {
    if (isIOS) {
      DeviceOrientationEvent.requestPermission()
        .then((response) => {
          if (response === "granted") {
            window.addEventListener("deviceorientation", handler, true);
          } else {
            alert("has to be allowed!");
          }
        })
        .catch(() => alert("not supported"));
    }
  }

  function handler(e) {

    compass = e.webkitCompassHeading || Math.abs(e.alpha - 360);
    compassCircle.style.transform = `translate(-50%, -50%) rotate(${-compass}deg)`;

    // ±15 degree
    if (
      (pointDegree < Math.abs(compass) &&
        pointDegree + 15 > Math.abs(compass)) ||
      pointDegree > Math.abs(compass + 15) ||
      pointDegree < Math.abs(compass)
    ) {
      myPoint.style.opacity = 0;
    } else if (pointDegree) {
      myPoint.style.opacity = 1;
    }
  }

  let pointDegree;

  function locationHandler(position) {
    const { latitude, longitude } = position.coords;
    pointDegree = calcDegreeToPoint(latitude, longitude);

    if (pointDegree < 0) {
      pointDegree = pointDegree + 360;
    }
  }

  function calcDegreeToPoint(latitude, longitude) {
    // Qibla geolocation
    const point = {
      lat: 21.422487,
      lng: 39.826206
    };

    const phiK = (point.lat * Math.PI) / 180.0;
    const lambdaK = (point.lng * Math.PI) / 180.0;
    const phi = (latitude * Math.PI) / 180.0;
    const lambda = (longitude * Math.PI) / 180.0;
    const psi =
      (180.0 / Math.PI) *
      Math.atan2(
        Math.sin(lambdaK - lambda),
        Math.cos(phi) * Math.tan(phiK) -
        Math.sin(phi) * Math.cos(lambdaK - lambda)
      );
    return Math.round(psi);
  }

  init();
</script>

</html>    

I’m having a problem consuming my REST API made in Java

i am trying to consume a local rest api using fetch in javascript, this is the error ‘localhost/:1 Access to fetch at ‘http://localhost:8080/api/v1/movies’ from origin ‘http://localhost:3000’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.’,

import "./App.css";
//import api from "./api/axiosConfig";
import { useState, useEffect } from "react";
function App() {
  const [movies, setMovies] = useState();

  const getMovies = async () => {
    const url = "http://localhost:8080/api/v1/movies";
    fetch(url)
      .then((response) => response.json())
      .then((data) => console.log(data))
      .catch((err) => console.log(err));
  };

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

  return <div className="App"></div>;
}

export default App;

i added the second parameter to the method fetch

import "./App.css";
//import api from "./api/axiosConfig";
import { useState, useEffect } from "react";
function App() {
  const [movies, setMovies] = useState();

  const getMovies = async () => {
    const url = "http://localhost:8080/api/v1/movies";
    fetch(url, {
      method: "GET",
      headers: { "Content-type": "application/json" },
      mode: "no-cors",
    })
      .then((response) => response.json())
      .then((data) => console.log(data))
      .catch((err) => console.log(err));
  };

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

  return <div className="App"></div>;
}

export default App;

and then i have this error ‘SyntaxError: Unexpected end of input (at App.js:13:1)
at App.js:13:1’ Thank you for your help in advance.

I looked up what caused the error, but I didn’t find anything similar.

Error in the execution of JavaScript codes [closed]

I am designing a WordPress site and the problem that has arisen is that the JavaScript codes work only when the login is done and when we leave the WordPress counter, the codes do not work at all.

I also checked the login codes in the JavaScript code execution and there was no problem

my react page isn’t showing any of my components on the page

I was building a social media app, and currently I created a navbar that is supposed to show in /home, not only that, i created a login page which should be the first page the loads when you run the server. and I am very confused as its not showing when I run the code. I use nodemon to run my code, and its very fidgety. I am also very confused about react as this is my first react project. Is there any way I can load my components? Thank you

GH:
https://github.com/Anish-I/socialmedia

I checked all paths, tried using debuggers and HTML dummioes, but wouldnt show up. there are no errors in the DOM or the cmd

How to modify openweathermap JS to use lat long values

I recently posted another question about the following JS openweathermap weather app i’m re-purposing. This is a follow up question to that.

https://codepen.io/stack-findover/pen/vYgQrPP

Currently, the code uses city search and geolocation for the getWeather function. I’d like to modify the code to use a specific set of Lat / Long coordinates instead. What would be the best way to do that?

Thanks for any help you can provide.

Relevant code blocks below:

var weatherData = {};
var api = "https://api.openweathermap.org/data/2.5/forecast?lat=&lon=-&units=imperial";
var id = "&APPID=acc38546e41e0baf9aa6ba45661c094b";
var cnt =  "&cnt=4"
var country="";
var ctyName = "";
var options = {
              weekday: "long", year: "numeric", month: "short",
              day: "numeric", hour: "2-digit", minute: "2-digit"
            };
var curDate = $(".cur-date");
curDate.html(new Date().toLocaleTimeString('en-US', options));

$.ajax({url: "https://ipinfo.io/json?"})
.done( function(res) {
  console.log(res);
  country = res.country;
  ctyName = "q="+res.city+","+country;

  getWeather();
});


function getWeather() {
$.ajax({url: api+ctyName+id+cnt, dataType: 'json', success: function(result) {
  $('#loader').hide();
  console.log(result);
  weatherData = result;
  var icons= [];

  $("#loc").html(result.city.name+", "+result.city.country);
  $("#cur-weath").html(result.list[0].weather[0].main);
  $("#cur-deg").html(Math.round((result.list[0].main.temp * (9/5)) - 459.67)+"°");
  $("#cur-desc").html(result.list[0].weather[0].description);
  var icon = result.list[0].weather[0].icon;
  setBackground(icon);
  //icons.push(result.list[0].weather[0].icon+".png");
  console.log(Icons[icon].icn);
  skycons.set("cur-icon",Icons[icon].icn);
 // $("#cur-icon").html("<img src='http://openweathermap.org/img/w/"+icons[0]+"'style='width:100px;height:100px;'>");
  for(var i=1;i<4;i++) {
    var $next=$(".next-weath");
    icons.push(result.list[i].weather[0].icon);
    var dt = new Date(result.list[i].dt_txt);
    if(dt == "Invalid Date") { //modify dt for internet explorer compatibility
      var ar = result.list[i].dt_txt.split(" ");
      dt = new Date(ar[0]+"T"+ar[1]);
    }
    var hour = dt.toLocaleTimeString('en-US', {hour: "2-digit", minute: "2-digit", hour12: true,  });
    $next.eq(i-1).find(".next-hour").html(hour);
    $next.eq(i-1).find(".next-desc").text(result.list[i].weather[0].description);
    $next.eq(i-1).find(".next-deg").html(Math.round((result.list[i].main.temp * (9/5)) - 459.67)+"°");
    skycons.set($next.eq(i-1).find(".next-icon")[0], Icons[icons[i-1]].icn);
  }


},

error: function(error, errorType, errorMessage) {
    $("#loc").html("Unable to Locate").next().hide();
},

beforeSend: function() {
    $("#loc").html("loading").next().show();

}});
}

$("button").on("click", getCityWeather);

$("input").keydown(function(event){
  if (event.which == 13)
    getCityWeather();
});

$(".next-deg").on("click", function() {
  if(weatherData)
    changeTempScale( $(this));
});

$("#cur-deg").on("click", function() {
  if(weatherData)
    changeTempScale( $(this));
});


function setBackground(icon) {
$(".wrap").css('background-image', 'url(' + Icons[icon].bg + ')');
}

function getCityWeather() {
$("input").val()
ctyName = "q="+$("input").val();
getWeather();
}

Ive attempted to override the functions by modifying the openweathermap api link, as in the following.. but this did not give the expected result.

var weatherData = {};
var api = "https://api.openweathermap.org/data/2.5/forecast?lat=&lon=&units=imperial";

Eventlistener not working for iPhone only, works for everything else

I know this question has been asked many times before but I feel that this is a unique bug. I have event listeners that display extra info when clicked or pressed. The functionality works on PC (Chrome), iPad (Safari) but doesn’t work on iPhone (I have something similar on another page which works but the listener is attached to an image (tried that here too)).

I have used click, touch, touchup etc etc but still nothing. Here is my code:


<div class="sub subOne"><h4>Description</h4><img src="{{ "chevron-black-closed.svg" | asset_url }}" style="width:20px;height:20px;"></div>  
<div class="hidden info subOneinfo ">{{ product.description }}</div>

const subOne = document.querySelector('.subOne');
    const subOneinfo = document.querySelector('.subOneinfo');
    const sub2 = document.querySelector('.sub2');
    const sub2info = document.querySelector('.sub2info');
    const sub3 = document.querySelector('.sub3');
    const sub3info = document.querySelector('.sub3info');
    const sub4 = document.querySelector('.sub4');
    const sub4info = document.querySelector('.sub4info');

    const temp = document.querySelector(".temp")

    temp.addEventListener("touchstart", () => subOneinfo.classList.remove("hidden"))

    let open = false

    console.log("HI")

    function handleInteraction(evt) {
        evt.preventDefault()
        if(!open) {
            open = subOneinfo
            subOneinfo.classList.remove("hidden")
        } else if (open == subOneinfo) {
            open.classList.add("hidden")
            open = false
            {% comment %} sub1info.classList.remove("hidden") {% endcomment %}
        } else {
            open.classList.add("hidden")
            open = subOneinfo
            subOneinfo.classList.remove("hidden")
        }
    }

    subOne.addEventListener('touchmove', handleInteraction)
    subOne.addEventListener('click', handleInteraction)

UseEffect React 18 – Taking a long time to make api calls

I am trying to make 7 api calls right away when the component mounts and get data quickly, then keep on making an api call for each of the 3 methods to getTemp, getGpu, getMemory. Athough it’s taking about 20 seconds to get 1 api call.

I am looking at my backend and everything work fine, the calls are received and responded correctly

I tried to remove asyc calls but that didn’t work

Can you help with making the 7 api calls once only and making 1 api call every second?

import { Card, Metric, CategoryBar, Flex, Text, AreaChart, ProgressBar, Title, LineChart } from "@tremor/react";
import card_1 from '../assets/cards/card_1.json'
import card_2 from '../assets/cards/card_2.json'
import card_3 from '../assets/cards/card_3.json'
import card_4 from '../assets/cards/card_4.json'
import React, { useState, useEffect } from 'react';
import axios from 'axios';

var all_cards_array = [card_1, card_2, card_3, card_4]
var array_of_temperatures = []
var array_of_gpu_usage = []
var array_of_gpu_memory = []
const array_of_colors = [
    "slate",
    "gray",
    "zinc",
    "neutral",
    "stone",
    "red",
    "orange",
    "amber",
    "yellow",
    "lime",
    "green",
    "emerald",
    "teal",
    "cyan",
    "sky",
    "blue",
    "indigo",
    "violet",
    "purple",
    "fuchsia",
    "pink",
    "rose"
];

var startTime, endTime;

var optionCelsius = {
    style: 'unit',
    unit: 'celsius'
};

var optionPercent = {
    style: 'percent',
    minimumFractionDigits: 0,
    maximumFractionDigits: 0
};

axios.defaults.baseURL = 'http://27.42.10.180:5278';
const valueFormatterPercentage = (number) => `${new Intl.NumberFormat("en-US", optionPercent).format(number / 100).toString()}`;
const valueFormatterCelcius = (number) => `${new Intl.NumberFormat("en-US", optionCelsius).format(number).toString()}`;


const Dashboard = () => {
    const [temperatures, setTemperatures] = useState(null);
    const [gpuUsage, setGpuUsage] = useState(null);
    const [gpuMemory, setGpuMemory] = useState(null);
    const [count, setCount] = useState(10);

    const getTemps = async () => {
        try {
            const { data } = await axios.get('/temperature_info');
            await setTemperatures(data);
            converTemperatureJsonToArray()
            console.log('Temps')
            console.log(array_of_temperatures)
            console.log(temperatures)

            return data
        } catch (err) {
            console.error(err);
        }
    };

    const getGpuUsage = async () => {
        try {
            const { data } = await axios.get('/gpu_usage_info');
            await setGpuUsage(data);
            converGpuJsonToArray()
            console.log('Gpu Usage')
            console.log(array_of_gpu_usage)
            console.log(gpuUsage)

            return data
        } catch (err) {
            console.error(err);
        }
    };

    const getGpuMemory = async () => {
        try {
            const { data } = await axios.get('/memory_usage_info');
            await setGpuMemory(data);
            converMemoryJsonToArray()
            console.log('Memory')
            console.log(array_of_gpu_memory)
            console.log(gpuMemory)

            return data
        } catch (err) {
            console.error(err);
        }
    };

    const countDown = () => {
        const interval = setInterval(function () {
            setCount((prev) => prev - 1);
        }, 1000);
    };

    useEffect(() => {
        getTemps()
        getGpuUsage()
        getGpuMemory()
        gpuUsageKeys()
        gpuMemoryKeys()
        temperaturesKeys()
        // countDown()

    }, [temperatures, gpuUsage, gpuMemory]);


    function start() {
        startTime = new Date();
    }

    function end() {
        endTime = new Date();
        var timeDiff = endTime - startTime; //in ms
        // strip the ms
        timeDiff /= 1000;

        // get seconds 
        var seconds = Math.round(timeDiff);
        console.log(seconds + " seconds");
    }

    function select_random_color(array_lenght) {
        const list_colors = []
        for (i in array_lenght) {
            list_colors.push(array_of_colors[Math.floor(Math.random() * array_lenght)])
        }

        return list_colors
    }

    function temperaturesKeys() {
        if (temperatures) {
            console.log('In keys temperatures')
            var list_keys = []

            for (const key of Object.keys(temperatures)) {
                if (key !== 'time_stamp') {
                    list_keys.push(key)
                }
            }

            return list_keys
        }

        return null
    }

    function gpuUsageKeys() {
        if (gpuUsage) {
            console.log('In keys gpu')
            var list_keys = []

            for (const key of Object.keys(gpuUsage)) {
                if (key !== 'time_stamp') {
                    list_keys.push(key)
                }
            }

            return list_keys
        }

        return null
    }

    function gpuMemoryKeys() {
        if (gpuMemory) {
            console.log('In keys memory')
            var list_keys = []

            for (const key of Object.keys(gpuMemory)) {
                if (key !== 'time_stamp') {
                    list_keys.push(key)
                }
            }

            return list_keys
        }

        return null
    }

    function getTemperatureFormattedJson() {
        const currentDate = new Date().toLocaleTimeString()
        const dict = {}

        for (const key of Object.keys(temperatures)) {
            if (key === 'time_stamp') {
                dict[key] = currentDate
            } else {
                dict[key] = temperatures[key]
            }
        }

        return dict
    }

    function getGpuFormattedJson() {
        const currentDate = new Date().toLocaleTimeString()
        const dict = {}

        for (const key of Object.keys(gpuUsage)) {
            if (key === 'time_stamp') {
                dict[key] = currentDate
            } else {
                dict[key] = gpuUsage[key]
            }
        }

        return dict
    }

    function getMemoryFormattedJson() {
        const currentDate = new Date().toLocaleTimeString()
        const dict = {}

        for (const key of Object.keys(gpuMemory)) {
            if (key === 'time_stamp') {
                dict[key] = currentDate
            } else {
                dict[key] = gpuMemory[key]
            }
        }

        return dict
    }

    function converTemperatureJsonToArray() {
        if (temperatures) {
            if (array_of_temperatures.length > 7) {
                array_of_temperatures.splice(0, 1)
            }

            array_of_temperatures.push(getTemperatureFormattedJson())

            return array_of_temperatures
        }

        return [""]
    }

    function converGpuJsonToArray() {
        if (gpuUsage) {
            if (array_of_gpu_usage.length > 7) {
                array_of_gpu_usage.splice(0, 1)
            }

            array_of_gpu_usage.push(getGpuFormattedJson())

            return array_of_gpu_usage
        }

        return [""]
    }

    function converMemoryJsonToArray() {
        if (gpuMemory) {
            if (array_of_gpu_memory.length > 7) {
                array_of_gpu_memory.splice(0, 1)
            }

            array_of_gpu_memory.push(getMemoryFormattedJson())

            return array_of_gpu_memory
        }

        return [""]
    }

    function renderBox() {
        return (
            <div className={color}>
            </div>
        )
    }

    function uuidv4() {
        return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, c =>
            (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
        );
    }

    function renderGPUName(cardName) {
        return (
            <div key={uuidv4()}>
                <h2 className='text-2xl font-bold'>
                    Gpu Name
                </h2>
                <br />
                <Card className="max-w-xs mx-auto" decoration="top" decorationColor="indigo">
                    <Metric>{cardName}</Metric>
                </Card>
            </div>
        )
    }

    function renderCards() {
        const cards = []
        var div_top_black = 'black'
        var div_top_blue = 'grid grid-cols-5 gap-14 blue'
        const list_colors = [div_top_black, div_top_blue]
        var count = 0

        for (const card of all_cards_array) {
            var color = ''

            if (count == 0) {
                color = list_colors[0]
                count += 1
            } else {
                color = list_colors[1]
                count = 0
            }

            cards.push(
                <div key={uuidv4()}>
                    <br />
                    <br />
                    <br />
                    <br />
                </div>
            )
            cards.push(
                <div className={color} key={uuidv4()}>
                </div>
            )
            cards.push(renderGPUName(card.name))
            cards.push(
                <div key={uuidv4()}>
                    <br />
                    <br />
                    <br />
                    <br />
                </div>
            )
            cards.push(
                <div className='grid grid-cols-5 gap-14' key={uuidv4()}>
                    <div>
                        <h2 className='text-2xl font-bold'>
                            Driver Version
                        </h2>
                        <br />
                        <Card className="max-w-xs mx-auto" decoration="top" decorationColor="indigo">
                            <Metric>{card.driver_version}</Metric>
                        </Card>
                    </div>
                    <div>
                        <h2 className='text-2xl font-bold'>
                            P State
                        </h2>
                        <br />
                        <Card className="max-w-xs mx-auto" decoration="top" decorationColor="indigo">
                            <Metric>{card.pstate}</Metric>
                        </Card>
                    </div>
                    <div>
                        <h2 className='text-lg font-bold'>
                            Pcie Link Gen Max
                        </h2>
                        <br />
                        <Card className="max-w-xs mx-auto" decoration="top" decorationColor="indigo">
                            <Metric>{card.pcie_link_gen_max}</Metric>
                        </Card>
                    </div>
                    <div>
                        <h2 className='text-lg font-bold'>
                            Pcie Link Gen Current
                        </h2>
                        <br />
                        <Card className="max-w-xs mx-auto" decoration="top" decorationColor="indigo">
                            <Metric>{card.pcie_link_gen_current}</Metric>
                        </Card>
                    </div>
                    <div>
                        <h2 className='text-2xl font-bold'>
                            Temperature
                        </h2>
                        <br />
                        <Card className="max-w-sm mx-auto">
                            <Flex>
                                <Text>0 &bull; {card.temperature_gpu}C</Text>
                                <Text>200</Text>
                            </Flex>
                            <ProgressBar value={card.temperature_gpu} color="red" className="mt-3" />
                        </Card>
                    </div>
                    <div>
                        <h2 className='text-2xl font-bold'>
                            Utilization Gpu
                        </h2>
                        <br />
                        <Card className="max-w-sm mx-auto">
                            <Flex>
                                <Text>0 &bull; {card["utilization_gpu [%]"]} %</Text>
                                <Text>100</Text>
                            </Flex>
                            <ProgressBar value={card["utilization_gpu [%]"]} color="red" className="mt-3" />
                        </Card>
                    </div>
                    <div>
                        <h2 className='text-xl font-bold'>
                            Utilization Memory
                        </h2>
                        <br />
                        <Card className="max-w-sm mx-auto">
                            <Flex>
                                <Text>0 &bull; {card["utilization_memory [%]"]}%</Text>
                                <Text>100</Text>
                            </Flex>
                            <ProgressBar value={card["utilization_memory [%]"]} color="red" className="mt-3" />
                        </Card>
                    </div>
                    <div>
                        <h2 className='text-2xl font-bold'>
                            Memory Total
                        </h2>
                        <br />
                        <Card className="max-w-sm mx-auto">
                            <Flex>
                                <Text>0 &bull; {card["memory_total [MiB]"]} MiB</Text>
                                <Text>{card["memory_total [MiB]"]}</Text>
                            </Flex>
                            <ProgressBar value={card["memory_total [MiB]"]} color="red" className="mt-3" />
                        </Card>
                    </div>
                    <div>
                        <h2 className='text-2xl font-bold'>
                            Memory Free
                        </h2>
                        <br />
                        <Card className="max-w-sm mx-auto">
                            <Flex>
                                <Text>0 &bull; {card["memory_free [MiB]"]} MiB</Text>
                                <Text>{card["memory_total [MiB]"]}</Text>
                            </Flex>
                            <ProgressBar value={card["memory_free [MiB]"] / card["memory_total [MiB]"] * 100} color="red" className="mt-3" />
                        </Card>
                    </div>
                    <div>
                        <h2 className='text-2xl font-bold'>
                            Memory Used
                        </h2>
                        <br />
                        <Card className="max-w-sm mx-auto">
                            <Flex>
                                <Text>0 &bull; {card["memory_used [MiB]"]} MiB</Text>
                                <Text>{card["memory_total [MiB]"]}</Text>
                            </Flex>
                            <ProgressBar value={card["memory_used [MiB]"] / card["memory_total [MiB]"] * 100} color="green" className="mt-3" />
                        </Card>
                        <br />
                        <br />
                    </div>
                </div>
            )
        }

        return cards
    }


    return (
        <>
            <div className='grid grid-cols-1 gap-14'>
                {array_of_temperatures.length > 7 ? 'Fetched' : 'Loading... ' + count + ' seconds left'}
                <br />
                <br />
                <br />
                <br />
                <Card>
                    <Title>Cards Temperature</Title>
                    <LineChart
                        className="mt-6"
                        data={array_of_temperatures.length > 7 ? array_of_temperatures : null}
                        index="time_stamp"
                        categories={temperatures ? temperaturesKeys() : []}
                        colors={array_of_temperatures > 0 ? select_random_color(temperaturesKeys().length - 1) : ["neutral", "indigo", "orange", "green"]}
                        valueFormatter={valueFormatterCelcius}
                        yAxisWidth={100}
                    />
                </Card>
            </div>
            <br />
            <br />
            <div className='grid grid-cols-1 gap-14'>
                <Card>
                    <Title>Cards Gpu Usage</Title>
                    <LineChart
                        className="mt-6"
                        data={array_of_gpu_usage.length > 7 ? array_of_gpu_usage : null}
                        index="time_stamp"
                        categories={gpuUsage ? gpuUsageKeys() : []}
                        colors={array_of_gpu_usage > 0 ? select_random_color(gpuUsageKeys().length - 1) : ["neutral", "indigo", "orange", "green"]}
                        valueFormatter={valueFormatterPercentage}
                        yAxisWidth={100}
                    />
                </Card>
            </div>
            <br />
            <br />
            <div className='grid grid-cols-1 gap-14'>
                <Card>
                    <Title>Cards Memory Usage</Title>
                    <LineChart
                        className="mt-6"
                        data={array_of_gpu_memory.length > 7 ? array_of_gpu_memory : null}
                        index="time_stamp"
                        categories={gpuMemory ? gpuMemoryKeys() : []}
                        colors={array_of_gpu_memory > 0 ? select_random_color(gpuMemoryKeys().length - 1) : ["neutral", "indigo", "orange", "green"]}
                        valueFormatter={valueFormatterPercentage}
                        yAxisWidth={100}
                    />
                </Card>
            </div>
            <br />
            <br />
            {renderCards()}
        </>
    )
};

export default Dashboard;

insert an html element inside a textContent of another element

I have an HTML code like this

<p>some text here, also another text here, or any arbitrary position</p>

and I want to replace all occurrences of the word “text” with an anchor, so the result would be

<p>some <a href="#">text</a> here, also another <a href="#">text</a> here, or any arbitrary position</p>

note that it would be a RegExp, for example to replace any /text[^s]/ with a link

Text animation before it disappears

I made animations for text to appear and disappear, but I don’t know how to make it work correctly. Pls help. ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ
My English is bad, so this is written by a google translateㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ
ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ

<style>
@keyframes text-fade-in {
  0% {
    opacity: 0;
    transform: translateX(-10vw);
  }
  80% {
    opacity: 1;
  }
  100% {
    opacity: 1;
    transform: translateX(0vw);
  }
}
.text-fade-in {
  opacity: 0;
  animation-name: text-fade-in;
  animation-delay: 0.4s;
  animation-duration: 0.4s;
  animation-timing-function: easeOutCirc;
  animation-fill-mode: forwards;
}

@keyframes text-fade-out {
  0% {
    opacity: 1;
    transform: translateX(0vw);
  }
  80% {
    opacity: 0;
  }
  100% {
    opacity: 0;
    transform: translateX(-10vw);
  }
}
.text-fade-out {
  opacity: 1;
  animation-name: text-fade-out;
  animation-delay: 0.4s;
  animation-duration: 0.4s;
  animation-timing-function: easeOutCirc;
  animation-fill-mode: forwards;
}
</style>

<body>
    <button onclick = "show('Text1'); hide('Text2'); hide('Text3')">Text1</button>
    <button onclick = "show('Text2'); hide('Text1'); hide('Text3')">Text2</button>
    <button onclick = "show('Text3'); hide('Text1'); hide('Text2')">Text3</button>
    <button onclick = "hide('Text1'); hide('Text2'); hide('Text3')">Hide all</button>

      <p class="text-fade-in" id = "Text1" style="display:none">Text1</p>
      <p class="text-fade-in" id = "Text2" style="display:none">Text2</p>
      <p class="text-fade-in" id = "Text3" style="display:none">Text3</p>
</body>

<script>
function hide(Id){
    document.getElementById(Id).style.display = "none";
}

function show(Id){
 document.getElementById(Id).style.display = "block";
}
</script>

problem when adding row to table with javascript

I’m working on a Laravel project where I need to add a row to a table in when clicking on a button inside a popup modal. This is supposed to be a simple task, yet the problem is it won’t add a new row to the table.

This is my code:

create.blade.php

@section('content')
<div class="row mb-3">
    <label for="colFormLabel" class="col-sm-2 col-form-label">Data Barang</label>
    <div class="col-sm-10 d-flex align-items-center">
        <button type="button" class="btn btn-info btn-sm text-nowrap" id="btn-modal-cari-customer" data-bs-toggle="modal"
            data-bs-target="#modalCariBarang">
            Cari Barang
        </button>
        @include('barang.modal-cari-barang')
    </div>
</div>

<div class="row mb-3">
    <div class="table-responsive small table-content overflow-visible">
        <table class="table table-striped table-bordered table-sm table-hover">
            <thead>
                <tr>
                    <th scope="col" class="fit text-start px-2">#</th>
                    <th scope="col" class="px-2">Nama Barang</th>
                    <th scope="col" class="fit px-2">Qty</th>
                    <th scope="col" class="fit px-2">Harga Satuan</th>
                    <th scope="col" class="fit px-2">Subtotal</th>
                    <th scope="col" class="fit px-2">Profit</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td class="fit">1.</td>
                    <td>
                        <a href="#" data-bs-toggle="modal" data-bs-target="#modal-show-item-penawaran"
                            data-slug="lampu-led-12-watt">
                            Lampu LED 12 watt
                        </a>
                    </td>
                    <td class="text-center fit">15</td>
                    <td class="text-end fit">Rp 15.000</td>
                    <td class="text-end fit">Rp 20.000</td>
                    <td class="text-end fit">Rp 75.000</td>
                </tr>
                <tr>
                    <td class="fit">2.</td>
                    <td>
                        <a href="#" data-bs-toggle="modal" data-bs-target="#modal-show-item-penawaran"
                            data-slug="cctv-panasonic">
                            CCTV Panasonic
                        </a>
                    </td>
                    <td class="text-center fit">10</td>
                    <td class="text-end fit">Rp 200.000</td>
                    <td class="text-end fit">Rp 220.000</td>
                    <td class="text-end fit">Rp 200.000</td>
                </tr>
            </tbody>
        </table>
    </div>
</div>
<script src="/assets/js/script.js"></script>
@endsection

modal-cari-barang.blade.php :

<!-- Modal -->
<div class="modal fade" id="modalCariBarang" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h1 class="modal-title fs-5" id="exampleModalLabel">Modal title</h1>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          ...
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
          <button type="button" class="btn btn-primary" id="btn1">Save changes</button>
        </div>
      </div>
    </div>
  </div>

script.js

    const btn1 = document.querySelector('#btn1');
    btn1.addEventListener('click', function() {
        let table = document.querySelector('form table');
        let tblPenawaranItem = table.getElementsByTagName('tbody')[0];
    
        let newRow = tblPenawaranItem.insertRow(-1);
        let cell1 = newRow.insertCell(0);
        let cell2 = newRow.insertCell(1);
        let cell3 = newRow.insertCell(2);
        
        cell1.innerHTML = 'zxc';
        cell2.innerHTML = 'aaa';
        cell3.innerHTML = 'lorem';
        console.log('zzzzzzzzzz', newRow);
    });

when I try to log the newRow variable, this is what I get:

console.log

what am I doing wrong?? any help is appreciated..

Screen reader is not reading out div text

I have chat application written in react. So when user receives a message from chatbot the screen reader should automatically read out the message when component is rendered and only if the message is equal to some specific text.
Here is the current code I have.

import React, { Component } from 'react';

class SomeComponent extends Component {
  render() {
    const { text } = this.props;

    return (
      <div>
        <div aria-live={text === 'some text' ? 'polite' : 'off'}>
          {text}
        </div>
      </div>
    );
  }
}

export default SomeComponent;

I tried using the aria-live but it didn’t work.
I am using NVDA as screen reader.

Alert Keeps Firing Twice During Validation

Writing a simple C# CRUD Application for a college project; I feel like the solution is obvious – but I have spent a lot of time getting my form validation to work in general, and I can’t see why JS alert is firing twice.

My HTML:

My JS: Waits til DOM loads, checks for the form, gets elements, etc. The validation works, but after running, the alert shows twice. Are my “return false;” statements not enough to stop the resubmission of the form?

window.onload = formCheck;

function formCheck() {
    var form = document.getElementById("editform");

    if (form) {
        form.addEventListener("submit", formValidation);
    } else {
        console.error("No edit form found. Script will not run.");
    }
};

function formValidation() {
    // Get FORM ELEMENTS
    var tfn = document.getElementById("TeacherFName");
    var tln = document.getElementById("TeacherLName");
    var ts = document.getElementById("Salary");
    var ten = document.getElementById("EmployeeNumber");

    //Get Values

    var fNameValue = tfn.value;
    var lNameValue = tln.value;
    var salaryValue = ts.value;
    var empNumValue = ten.value;

    //CHECK IF EMPTY
    if (fNameValue.trim() === "") {
        alert("First Name field is required.");
        tfn.style.border = "1px solid red";
        return false;
    } else if (lNameValue.trim() === "") {
        alert("Last Name field is required..");
        tln.style.border = "1px solid red";
        return false;
     } else if (salaryValue.trim() === "") {
        alert("Salary field is required.");
    ts.style.border = "1px solid red";
    return false;
} else if  (empNumValue.trim() === "") {
        alert("Employee Number field is required.");
    ten.style.border = "1px solid red";
    return false;
}   
    // if validation passes, submit true
    return true;
}

I only expected the alert to pop a single time, I have return false after each statement and I am not sure why it’s going twice.