How to set Id product as key in Array JavaScript? [duplicate]

I have an array, which contains objects. Key of element is ID of “some” model. Example of array:
[null, null, null, null, ... {text: simple, type: 'class'}]

In my case I have id 3081, that means element should in 3081 index.

An array put in “some” object, which should convert to JSON. I am doing next operation:

const json = {
 data: 'simple',
 status: 'ok',
 exampleArray: [null, null, null, null...{text: simple, type: 'class'}]
} 

JSON.stringify(json)

In browser, I got next picture, that I included in attached. All elements is null, until we found 3081 index, that is our object.

Can we remove all nulls in array or this is specific for JS?

enter image description here

Discord.js 14 Music Bot won’t play music on Ubuntu but works on Windows

I’m currently using this custom music bot with discord.js 14. While it runs smoothly on Windows, I encounter an issue when attempting to launch it from Ubuntu. The bot successfully locates music, but upon trying to load it, the music fails to start, and the bot promptly responds with a stopped message. No error log was generated.

  • Works on Windows 11 23H2
  • Not working on Ubuntu 22.04.4 LTS

What I’ve tried:

  • Installing the @discordjs/opus package (https://stackoverflow.com/a/62719993/18463835).
  • Updated packages with npm update --save.
  • Installed ffmpeg using sudo apt install.
  • Tried 4-5 other music bot source codes found on GitHub; every bot encountered the same issue.
  • Updated Ubuntu and its packages.
  • Reinstalled Ubuntu from a new ISO.

Node Version:
v20.12.2 (same on Ubuntu and Windows)

Here’s an image:

enter image description here

Important API calls appearing in the network tab [closed]

I’m creating a web app and I need to do some API calls to Azure SQL for some data. I’m using NEXTjs so I already manage to “getServersideProps” to render those API calls from the back-end. My problem is that there is an email input, the user writes his email and that’s when I check into the database to get some of the data related to that email. Those are the API calls that show in the network tab with all the data from the user email.

I have heard something related with the new NEXTjs project structure (I’m using pages folder) where api calls by default are made in the back-end. Is that something I should look into or it is the same as “getServerSideProps”?

I know there is not actual way to “hide” the API calls from the network tab, but any idea is more than welcome!

Is it possible to pass variables from a child component to the parent component in react?

I am making a simple food ordering web app and was trying to organize the ordering page into separate components but am now running into the issue of passing a variable to the parent page. I want to collect the item.Price and item.specBurgerType and pass to the parent. Is this possible or should I just restructure my code?

This is what I have for the parent component:

const Order = () => {

    const [order, setOrder] = useState({
       specBurger: "",
       protein: "",
       bread: "",
       toppings: "",
       sides: "",
       drinks: "" 
    });

    function handleSpec(spec, price) {
        this.setOrder({specBurger: spec});
    }

    return(
        <div className="order">
            <h1 className="title">Welcome to D & S Burgers</h1>
            <Link to="./pages/Login"><button className="loginButton">Manager Login</button></Link>
            <h2>Please choose your items and place your order!</h2>

            <div className="orderSection">
                <SpecialtyBurgers onSpecSelect={handleSpec}/>
                <Custom/>
                <Sides />
                <Drinks />
                <div><Link to="/pages/Confirmation"><button className="orderButton">Order</button></Link></div>

            </div>
        </div>
    );
};```

Here is the child: 

const SpecialtyBurgers = () => {

const [specBurgers, setSpecBurgers] = useState([]);
useEffect( () => {
    axios.get('http://localhost:8800/specialtyburgers')
    .then(res => {
        setSpecBurgers(res.data);
    })
}, [])

const [burgerType, setBurgerType] = useState({
    burger: "",
    price: 0.0
})
const [price, setPrice] = useState();
const [specOrder, setSpecOrder] = useState([]);
function handleChange(p, e) {
    if(e.target.checked) {
        setSpecOrder(e.target.value);
        setPrice();
        //this.props.handleSpec(specOrder, price);
    }
    else if(!e.target.unchecked){
        setSpecOrder("");
        setPrice('0.0');
        //this.props.handleSpec(specOrder, price);
    }
}

var specBurgerDetails = "";
specBurgerDetails = specBurgers.map( (item, index) => {
    return(
        <div className="item">
            <h2 key={index}>{item.SpecBurgerType}</h2>
            <p>{item.Protein}</p>
            <p>{item.Toppings}</p>
            <p>{item.Price}</p>
            <input type='checkbox' value={item.SpecBurgerType} onChange={(e) => handleChange(item.price, e)}/>
            <p>{specOrder}</p>
            <p>{price}</p>
        </div>
    )
});

return(
    <div className="orderSection">
            <h1 className="menuTitle">Specialty Burgers</h1>
            <div className="menuItems">
                {specBurgerDetails}
            </div>
    </div>
);

};“`

How to correctly setup getElementById?

I am having trouble with getElementById() not working and I am unsure what is wrong.

My HTML body:

<button type="button" id="up">Increase Volume</button>
<button type="button" id="down">Decrease Volume</button>
<script src="final.js"></script>

My script file:

const upButton = document.getElementById("up");
const downButton = document.getElementById("up");


initialize();

function initialize(){

    upButton.setAttribute("width", "300px");
    console.log(upButton.getAttribute("width"));
    upButton.setAttribute("left", (Math.floor(Math.random() * 1000)).toString() + "px");

    downButton.setAttribute("top", (Math.floor(Math.random() * 1000)).toString() + "px");
    downButton.setAttribute("left", (Math.floor(Math.random() * 1000)).toString() + "px");
}

How to test button functionality based on other components in React

I have a React application. I have a main button which is supposed to be disabled unless two conditions are met, entry into a text box and a selection from a dropdown. Once enabled, if either the text box is cleared or the dropdown is reset, the button is to become disabled again.

The text box is a Form.Control from “react-bootstrap” and the dropdown is a Form.Select from the same. When text is entered into the text box, a CloseButton from “react-bootstrap” is made visible. In manual testing, clicking the close button clears the text box and, if the main button is enabled, disables it. However, in Jest testing, when calling fireEvent.click(closeBtn) when the main button is enabled, that main button is not disabled. Curiously, if the dropdown selection is cleared, the button becomes disabled.

I tried setting breakpoints in my React code to see if the onClick event for the close button is even triggered and it looks like the answer is “no”.

I was really hoping I could get the conditions to be re-evaluated for enabling and disabling the main button.

How to ensure consistent browser positioning measurements

I have a function that loops through a javascript array/object, adds some spans to the DOM, measures their positions and returns the measurements.

Example code below, but my question isn’t really about the code.

99% of the time these measurements are accurate, but not always. Sometimes the positioning will be significantly off.

Usually when they are off, running the function again will resolve it, but it has never happened to me, only other users and I am not sure what could be happening.

My only guesses are, maybe the user is resizing the browser window? Or doing something else that is affecting it? I am a bit at a loss.

So my question is, is there a standard way to prevent this sort of thing?

Could there be something I am missing? There are no animations or anything happening. Just placing the text and measuring.

To maybe lock down the browser so measurements cannot get disrupted? Or am I off track on that thinking?

EXAMPLE

HTML

<div style="position:absolute;width:400px;display:flex" id="measurecontainer"></div>

JAVASCRIPT

$( document ).ready(function() {


//example text
var tss = {};
tss[1] = {};
 Object.assign(tss[1], {word: 'Test One',id: 1});


tss[2] = {};
 Object.assign(tss[2], {word: 'Test Two',id:2});


tss[3] = {};
 Object.assign(tss[3], {word: 'Test Three',id: 3});




function measure_text(tss) {


var measurements = {};



var html = '';

for (const key in tss) {
  if (tss.hasOwnProperty(key)) {
    const item = tss[key];
     html += '<span style="margin:5px;padding:5px" id="'+item.id+'" class="measurethese" id="'+item.id+'">'+item.word+'</span>';
}
}


jQuery('#measurecontainer').html(html);


//measure each span
$('.measurethese').each(function(index, value) {

var elementid = jQuery(this).attr('id');

var innerelement = document.getElementById(elementid);
var positionInfo = innerelement.getBoundingClientRect();

var outerelement = document.getElementById('measurecontainer');
var outerpositionInfo = outerelement.getBoundingClientRect();

var positiontop = positionInfo.top - outerpositionInfo.top;
var positionleft = positionInfo.left - outerpositionInfo.left;

console.log('WORD ID '+elementid);
console.log('Position Top '+positiontop);
console.log('Position Left '+positionleft);

});


}



measure_text(tss);


});```

Nuxt useFetch: data accessible only using v-for

I attempt to fetch and display username from my API. However user.username couldn’t be accessed normal way:

<script setup>
definePageMeta({
  layout: "dashboard",
});
const token = useCookie("token");
const { data: user } = await useFetch("http://127.0.0.1:8000/auth/", {
  onRequest({ options }) {
    options.headers = options.headers || {};
    options.headers.authorization = `Bearer ${token.value}`;
  },
});
console.log(user);
</script>

<template>
  <div class="flex flex-col items-center">
    <div class="absolute top-1/4 flex flex-col items-center">
      <p class="special-font text-7xl rounded-sm px-7 gradient-red">
        {{ user.username }}
      </p>
    </div>
  </div>
</template>

I found a weird workaround, but it’s counterintuitive (iterating through array of 1 element does the job)

<template>
  <div class="flex flex-col items-center">
    <div class="absolute top-1/4 flex flex-col items-center">
      <p
        class="special-font text-7xl rounded-sm px-7 gradient-red"
        v-for="user in user"
      >
        {{ user.username }}!
      </p>
    </div>
  </div>
</template>

why does tableRow.get() not working in p5.js?

I’m trying to practice data table with geolocation. But p5 can’t load data from tableRow.get(), as I printed the lat and lon, it says undefind. What’s the problem?

let Soho;
let table;
let lat, lon, xgeo, ygeo;

let mapGeoLeft = -0.1424;
let mapGeoRight = -0.131;
let mapGeoTop = 51.5164;
let mapGeoBottom = 51.5093;

function preload() {
  soho = loadImage("cholera.png");
  table = loadTable("cholera.csv");
}

function setup() {
  createCanvas(600, 600);
  background(soho);
}

function draw() {
  for (let r = 0; r < table.getRowCount(); r++) {
    let tableRow = table.rows[r];
    lat = tableRow.get("lat");
    lon = tableRow.get("lon");

    xgeo = map(lon, mapGeoLeft, mapGeoRight, 0, width);
    ygeo = map(lat, mapGeoTop, mapGeoBottom, 0, height);

    fill(255, 0, 0);
    strokeWeight(0.5);
    circle(xgeo, ygeo, 5);
  }
  print(lat);
  noLoop();
}

here is the first few lines of data from the table:

count,lon,lat
3,-0.13793,51.513418
2,-0.137883,51.513361
1,-0.137853,51.513317
1,-0.137812,51.513262
4,-0.137767,51.513204
2,-0.137537,51.513184

How do I use the same java script for 2 different elements in html

Right now only the first mp4 works with this, the second one doesnt. Honestly the stylesheet part is not that important, I don’t mind if it gets cut out cause it’s hard to do or something. I don’t have the skills to implement other solutions that other have found so I am asking myself.

index.html:

    <div class="main-container">
        <div class="video-container">
          <video src="honda/honda adv.mp4"></video>
          <div class="hover-text active"><b>Autoturisme</b></div>
        </div>
      </div>
  
      <script src="main1.js"></script>


      <div class="main-container">
        <div class="video-container">
          <video src="honda/honda engine.mp4"></video>
          <div class="hover-text active"><b>Motoare</b></div>
        </div>
      </div>
  
      <script src="main2.js"></script>

style1.css (same code as style2.css at this moment):

.main-container {
  position: relative;
  width: 400px;
  top:-350px;
  left: -550px;
  margin: 40px auto;
  font-family: "Roboto", sans-serif;
  border-radius: 10px;
}

.video-container {
  position: relative;
}

.video-container video {
  width: 100%;
}

.video-container .hover-text {
  position: absolute;
  top: 50%;
  left: 50%;
    transform: translate(calc(-50% - 24px), -50%);
    background: #ff0019;
    color: #fff;
    padding: 8px 16px;
    border-radius: 8px;
    pointer-events: none;
    box-shadow: 4px 4px 50px -4px rgba(0, 0, 0, 0.8);
    opacity: 0;
    letter-spacing: 0.8px;
    transition: all 400ms ease;
  }
  
  .video-container .hover-text.active {
    opacity: 1;
    letter-spacing: 0;
    transform: translate(-50%, -50%);
  }

main1.js (same code as main2.js):

const video = document.querySelector(".video-container video");
const hoverText = document.querySelector(".video-container .hover-text");

video.addEventListener("mouseenter", () => {
  video.play();
  hoverText.classList.remove("active");
});

video.addEventListener("mouseleave", () => {
  video.pause();
  hoverText.classList.add("active");
});

Data exists, but NO data being returned to JSSmartClient page

I am passing in a comma-separated string from a .aspx page to a vb.net page. I want to cycle through this string and give me the results in a table that is passed back to the .aspx page, displayed in a SmartClient ListGrid. The problem I’m having is that even though the vb.net page shows that the table has been constructed with no errors, no data is being returned. I may be sending the data back to the .aspx page the wrong way or something, because I am getting an empty ListGrid. I am not seeing any errors on the console either… just nothing at all. What am I doing wrong here?

Here is the JS in the .aspx page:

The DataSource————-

var dataAnimNames = isc.DataSource.create({
dataURL: "DataScripts/ShowAnimalsList.aspx",
recordXPath: "/NewDataSet/DATA",
fields: [
{ name: "AnimalName", type: "text", title: "Name" },
{ name: "Desc", type: "text", title: "Description" }
],
});

The function call—————-

function LoadAnimDesc() {
AnimalsGrid.fetchData(null, "AnimalsGrid.setData(data)", {
params: {
Names: Form1.getValue("sNames")
}
});
};

The ListGrid——————

var AnimalsGrid = isc.ListGrid.create({
autoFetchData: false,
dataSource: "dataAnimNames",
width: "80%",
});

The Comma separated string being passed to the vb.net page

Mickey,Goofy

//The ShowAnimalsList.aspx vb.net page—————-

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim NameList As String = Request("Names")
Dim Names As String() = NameList.Split(New Char() {","c})
Dim cTypes As New TypeLib.clsTypes
Dim Desc As String

Dim dsNames As New DataSet
Dim dtNames As New DataTable
dtNames.Columns.Add("AnimalName")
dtNames.Columns.Add("Desc")
    
        Try
            If NameList.Count > 0 Then
                For Each Nme As String In Names
                    If Nme.Trim = "" Then Continue For
                    Nme = Nme.Trim
                    Desc = cTypes.GetAnimDesc(clsUtility.ConStr, Nme)
                    Dim row As DataRow = dtNames.NewRow()
                    row("AnimalName") = Nme
                    row("Desc") = Desc
                    dtNames.Rows.Add(row)
                Next
                dsNames.Tables.Add(dtChgs)
                dsNames.Tables(0).WriteXml(Response.OutputStream)
    
            End If
    
        Catch ex As Exception
        'no errors here...
    
        End Try
    End Sub`

This is the table showing in the ‘DataTable Visualizer’ of the ShowAnimalsList.aspx vb.net page

AnimalName Desc
Mickey Mouse
Goofy Dog

Discord.js Bot V14 – AuditLogs not returning right data on specific events

I’m trying to make a small Logger Discord Bot. The code below is how i get the audit logs entry (for the channelDelete event).
But i got a big problem: also if the user who deletes the message (user A) is not a bot or the author of the message (user B), the executor (and also the target) is not correct, it’s referred to a previous deleted message (the channel data is about the right deleted channel).

Example: user A create a message -> User B deletes it.
Then user B creates a message -> User A deletes it.
Both logs have as executor user B and target User A (waited until the end of an action before to perform an other)

I’ve also ried to add a setTimeout(() => {...}, 2500); But nothing changes, it doesn’t give the right executor (and target).
What i’m doing wrong?

    const AuditLogFetch = await channel.guild.fetchAuditLogs({
      limit: 1,
      type: auditType,
    });
    if (!AuditLogFetch.entries.first())
      return console.error(`No entries found.`);

    const entry = AuditLogFetch.entries.first();
    let parentChannel = null;
    if (entry.channelParentId) 
      parentChannel =                                                       channel.guild.channels.cache.get(channel.parentId).toString();

    const chDeleteEmbed = {
      color: colors.DARK_RED,
      author: {
       name: `${entry.globalName != null ? entry.globalName : 'No nickname'} [${entry.username != null ? entry.username : 'No username'}]`,
        icon_url: entry.displayAvatarURL()
      },
      description: `${channel.type} deleted by <@${entry.executor.id}> n 
        ${parentChannel != null ? `In category: ${parentChannel}` : '' }`,
      fields: [
        { 
          name: 'Nome canale', 
          value: `${channel.name}`
        }
      ],
     }
     // send embed func ...
  })

Thank you

Programmatically capture output frame rate in Chrome (or any other browser) with JavaScript?

We’ve been into some performance issues (slowness) in the Chrome browser since the mid 2023.

We are yet to find the root cause of the issue. But, in the meanwhile we want to send some statistics to our logging system to analyse the data and get towards the problem more efficiently.

We successfully captured the frame rate of our feature (a web video application).

But, we also want to capture the frame rate of the application itself, where our feature has been integrated with. So that we can get some insights about the number of users that are impacted.

I can enable the “Frame Rendering Stats” in my Chrome to see the fps meter, but I couldn’t find anything where I can get the values for the output frame rate within my feature using JavaScript.

Question: Does somebody know how to programmatically get the output frame rate of the application?

WebRTC ontrack not fired after addTrack is called

The ontrack listener is not fired when a track is supposedly added although a connection has already been established between 2 peers over WebRTC. I know this because I have data channels that work for sending messages between the 2 peers.

I tried adding a webcam to the connection by having a button call the following function:

async function startLocalVideo() {
    let stream = await navigator.mediaDevices.getUserMedia({
    video: true,
    audio: false
    });
    localStream.srcObject = stream;

    for(const track of stream.getTracks()) {
        console.log('adding tracks', track)
    let answer = currentPeer.rtc?.conn.addTrack(track, stream);
        console.log(answer)
    }
}

*localStream is a bound <video> element.

From the callee’s perspective, I added the following lines to when the RTC connection object is created:

this.conn = new RTCPeerConnection({
    iceServers: [
        { urls: 'stun:stun.l.google.com:19302' },
    ],
})

this.conn.ondatachannel = (e) => {
    console.log('got a dc')
    this.chan = e.channel
}

// NEW LINES
this.conn.ontrack = (e) => { 
    console.log("Got a track")
}

when I press the button, the console logs the following:
logged information

On the callee’s side I would expect the conn.ontrack listener be fired, but it seems like nothing happens. I tried following many tutorials and from what I understand this is supposed to work.

My current layout is this:
Peer1: creates a new data channel, makes an offer, and sends it to server
Server: sends the offer to Peer2
Peer2: accepts the offer, creates a new data channel, creates an answer with the offer, and sends the answer to the server
Server: sends the answer to Peer1
Peer1: accepts the answer

At this point, the data channels are opened on both sides and the peers can send data with them.

now what I tried is the following:
Peer1: presses the ‘video’ button and triggers the addTrack
Peer1: the allow video prompt is shown and the peer accepts it, and a live preview of the camera is shown.

Peer2: expected to receive the track, but nothing happens.

Javascript Assigning Variable from Async Function [duplicate]

I have a function that runs through an array of class objects asynchronously and returns an array of strings.
Note that I am just using regular javascript. I call this function to set a variable that I am to use later. When I go to call the variable I get that it is of the type promise and is “pending” below is the output I get.

Promise {[[PromiseState]]: 'pending', [[PromiseResult]]: undefined}

When I dig into it it, it states

[[PromiseResult]]: Array(500001)
[[PromiseState]]: 'fulfilled'
[[Prototype]]: Promise

Below is the function and how I am setting the variable.

async function objectArrayToStringArrayAsync(objectArray, threadCount = 1) {
    
    if(objectArray.length < threadCount)
    {
        threadCount = 1;
    }

    let stringArray = [];
    let taskArray = [];
    let interval = Math.floor(objectArray.length / threadCount);

    for( i = 0; i < threadCount; i ++) {
        let indexStart = interval * i;
        let indexEnd = interval * (i + 1);
        
        if(i == threadCount - 1 ) {
            indexEnd = objectArray.length;
        }

        if(i == 0) {
            stringArray.push(Object.keys(objectArray[0]).join(',') + "rn");
        }
        
        taskArray.push(async function() {
            let result = [];
            
            for(j = indexStart; j < indexEnd; j++) {
                result.push(Object.values(objectArray[j]).join(',') +"rn");
            }
            return result;
        }());
    } 

    // not sure why it is not working. Dynamicall typed languages are not my favourite
    for(k = 0; k < threadCount; k ++) {
        stringArray = stringArray.concat(await taskArray[k]);
    }
    console.log("row count inside of async function " + stringArray.length);
    return stringArray
}

let stringArray = objectArrayToStringArrayAsync(objectArray, 2);

I am used to async in other languages such as C# where I can await the function. such as let stringArray = await objectArrayToStringArrayAsync(objectArray, 2);

This does not seem to work. I also saw documentation on using then, however I was unable to get it to properly use it. I simply want to set my stringArray variable and use it right away as an array further in my code. The project is only to be done in javascript, no typescript. Not sure what I need to do next, some assistance would be greatly appreciated.

Thanks,
J