is map more efficient than an object in this case?

Hello i just want to understand and clarify something , i was solving this problem “Longest Substring Without Repeating Characters” , i was using an object as a map but the solution was not accepted , it says time limit exceeded , but when i changed object to a map it works perfectly .

here is the code :

function lengthOfLongestSubstring(s = "") {
        let end = 0;
        let start = 0;
        let maxLength = 0;
        const map = new Map();
        while (end < s.length) {
          if (!map.has(s[end])) {
            map.set(s[end], end);
            end++;
            maxLength = Math.max(maxLength, end - start);
          } else {
            map.delete(s[start]);
            start++;
          }
        }
        return maxLength;
      }

thank you 😀

Automatically shift the section to the start of page

I would like to have a functionality in a page that, when we scroll the page it automatically shift the section to the start of page, if the previous section is present less then 25% on the screen,Is there anyone who can help me out or guide to do so?

sample code, or any other reference materiial to get help from

How to log userId in a server that handles concurrent requests?

I have an express server, and it handles all kind of functionalities that I want to log. I also have a client that passes username as a header to each request in the server, and I want the username to be a part of every log. I can’t store the username in a class or a global variable, as it won’t be correct when multiple requests from different users are made. My logger is a class that you can simply call in order to log, for example: logger.log(“blah”, payload)

I don’t want to pass the userId to every function where I want to log, what can I do?

Things I thought to do:

  1. pass userId to every function, though I don’t want to do it
  2. Maybe somehow make the req known to the logger? But I don’t know how to do it correctly

Add Link to NavDropdown react bootstrap 5

I’m trying to add a Link from the react-router-dom directory

For NavDropdown from the react bootstrap 5 library

I tried to find a guide but it doesn’t work for me

What am I doing wrong?


<NavDropdown
title="In store restaurant"
id="basic-nav-dropdown"
as={Link}
to="/InStoreRestaurant"
 renderMenuOnMount={true}
  >
...

Thank you

how to get the snowflake value of a string that is a valid user id discord.js

I am trying to turn a string into a snowflake user.id to edit its permissions on a specific channel. In the below code, only user ids fetched in this way: interaction.user.id or client.user.id work. However, using this way: const user2 = await client.users.fetch(u2id) (u2id is a string of a valid user id value) doesn’t work.

Here is my entire code:

var u2id = found.slice(0, 18)
const user2 = await client.users.fetch(u2id);
console.log(u2id)
interaction.guild.channels.create({
            name: interaction.user.id + u2id,
            type: ChannelType.GuildText,
            permissionOverwrites: [
              {
                id: interaction.guild.roles.everyone,
                deny: [PermissionFlagsBits.ViewChannel],
              },
              {
                id: interaction.user.id,
                allow: [PermissionFlagsBits.ViewChannel],
              },
              {
                id: client.user.id,
                allow: [PermissionFlagsBits.ViewChannel],
              },
              {
                id: user2,
                allow: [PermissionFlagsBits.ViewChannel],
              },
            ],
});

When I remove this part (which edits channel permissions for the user2 id)

{
  id: user2,
  allow: [PermissionFlagsBits.ViewChannel],
},

the code fully works. Any ideas on why its not working?

URL.createObjectURL() providing url that redirects to 404 in AWS production env

I have a django application deployed on AWS EBS. I have a function that takes a blob and create URL of it so that I can download the pdf file from the site. The function is working perfectly on localhost but in prod environment the created url from URL.createObjectURL() is redirecting to the error page or 404 page. Im using nginx as the reverse proxy. I have checked the blob is valid and the django function is generating the pdf layout correctly. Below is my js code to build the pdf download link

function showFile(blob){
 
  var newBlob = new Blob([blob], {type: "application/pdf"})
  if (!newBlob) {
    console.error("Blob object is not valid");
    return;
  }

  // Create a link pointing to the ObjectURL containing the blob.
  const data = window.URL.createObjectURL(newBlob);
  console.log(data)
  var link = document.createElement('a');
  link.href = data;
  link.open="file.pdf";
  link.download = 'Calculation.pdf';
  link.click()
}

the console.log(data) is returning https://<mydomain>/d6527ea6-5c1d-457a-bfb2-2b6aff01ae31

Any idea on how I can make it work in my prod env?

Thank you

I tried to log the flow and everything is returning correctly. So I am not sure what is the issue

bot keeps spamming every 4 second

so my bot when i run it it runs pretty much fine but what i hate is that it keeps spamming every 4 seconds a voice update of the user, i want it to stop spamming, i also tried to use @discordjs/voice instead of quick.db it does not spam though like it does with quick.db but the function where the bot goes into the channels does not work and does not make any movmements only it makes with quick.db however what i want is only to stop making it spamming because its taking full cache of disk for absolute nothing. i tried this with the ready function i have`

const { Client } = require('discord.js');
const { activity } = require('../../config/bot.json');
const { status } = require('../../config/bot.json');
const { joinVoiceChannel } = require('@discordjs/voice');

/**
 * 
 * @param {Client} client 
 */

async function ReadyFunction(client, red, blue) {
    console.log(blue('Connected in to: ') + red(client.user.username));
    await client.user.setActivity(activity.name, {
        type: activity.type
    });
    await client.user.setStatus(status);

    setInterval(() => {
        try {
            client.guilds.cache.forEach(guild => {
                let channelID = require('discordjs/voice').fetch(`Voice_Channel_${guild.id}`)
                if (channelID !== null) {
                    let channel = client.channels.cache.find(c => c.id == '941600059093553175');
                    const connection = joinVoiceChannel({
                        channelId: channel.id,
                        guildId: channel.guild.id,
                        adapterCreator: channel.guild.voiceAdapterCreator,
                    });
                    connection;
                    connection.on("error", err => {
                        return
                    });
                }
            });
        }  catch {
            
        }
    }, 9000);
};


module.exports.get = ReadyFunction;

with this it keeps spamming every 4 second without any stop when i use quick.db as the quild fecher for cache


 const { Client } = require('discord.js');
const { activity } = require('../../config/bot.json');
const { status } = require('../../config/bot.json');
const { joinVoiceChannel } = require('@discordjs/voice');

/**
 * 
 * @param {Client} client 
 */

async function ReadyFunction(client, red, blue) {
    console.log(blue('Connected in to: ') + red(client.user.username));
    await client.user.setActivity(activity.name, {
        type: activity.type
    });
    await client.user.setStatus(status);

    setInterval(() => {
        try {
            client.guilds.cache.forEach(guild => {
                let channelID = require('quick.db').fetch(`Voice_Channel_${guild.id}`)
                if (channelID !== null) {
                    let channel = client.channels.cache.find(c => c.id == '941600059093553175');
                    const connection = joinVoiceChannel({
                        channelId: channel.id,
                        guildId: channel.guild.id,
                        adapterCreator: channel.guild.voiceAdapterCreator,
                    });
                    connection;
                    connection.on("error", err => {
                        return
                    });
                }
            });
        }  catch {
            
        }
    }, 9000);
};

module.exports.get = ReadyFunction;

`please i want someone to make it stops spamming

How to make a request call running in the background in JS?

I have the following code:

function getRegionList() {
    return new Promise(function(resolve, reject) {
        const config: ExtendedAxiosConfig = {
            method: "GET",
            url: "businesses/regions",
            _addToken: false,
        };
        axios(config)
            .then((res) => {
                resolve(true);
                store.set(LocalStoragekeys.Regions, res.data.data);
            })
            .catch((err) => {
                reject(err);
            });
    });
}

It returns about 10k rows (that will be stored in the indexDB) and takes about 20sec to be finished. I call it in the application’s loading step and it’s like a bottleneck and increases the bounce-rate.

Any idea how can I make it running in the background? I mean, avoid stopping for it to get finished.

I am trying to download compression webpack plugin with npm but its giving me error

Hi there this is the message that APPEARS WHEN I TRY TO RUN THE COMMAND

npm install compression-webpack-plugin

and this is the error:

`PS D:phaser gamesgame-slot-machine> npm install compression-webpack-plugin
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/webpack
npm ERR! dev webpack@”^4.41.2″ from the root projectnpm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer webpack@”^5.1.0″ from [email protected]
npm ERR! node_modules/compression-webpack-plugin
npm ERR! compression-webpack-plugin@”*” from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with –force, or –legacy-peer-dnpm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See C:UsersCheetayAppDataLocalnpm-cacheeresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR! C:UsersCheetayAppDataLocalnpm-cache_logs2023-01-31T07_37_59_109Z-debug-0npm install compression-webpack-plugin –save-devine>
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/webpack
npm ERR! dev webpack@”^4.41.2″ from the root projectnpm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer webpack@”^5.1.0″ from [email protected]
npm ERR! node_modules/compression-webpack-plugin
npm ERR! dev compression-webpack-plugin@”*” from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with –force, or –legacy-peer-deps
n) dependency resolution.
npm ERR!
npm ERR! See C:UsersCheetayAppDataLocalnpm-cacheeresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR! C:UsersCheetayAppDataLocalnpm-cache_logs2023-01-31T07_39_13_026Z-debug-0.log
PS D:phaser gamesgame-slot-machine> npm install compression-webpack-plugin –save-dev
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/webpack
npm ERR! dev webpack@”^4.41.2″ from the root projectnpm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer webpack@”^5.1.0″ from [email protected]
npm ERR! node_modules/compression-webpack-plugin
npm ERR! dev compression-webpack-plugin@”*” from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with –force, or –legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See C:UsersCheetayAppDataLocalnpm-cacheeresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR! C:UsersCheetayAppDataLocalnpm-cache_logs2023-01-31T07_39_20_653Z-debug-0.log`

i am trying to reduce size of my js file in a game and trying to download this plugin that reduces the size.

Can you make individual points in a THREE.js Points object transparent/invisible?

I have a Three.js Points object that contains data to display a bunch of points in the 3D space. I want to dynamically make some points invisible, but not sure how.

The material is a PointsMaterial. xyz data is stored in pointsObj.geometry.attributes.position.array and color data is stored in pointsObj.geometry.attributes.color.array, but I’m not sure if it’s possible to alter things like alpha value or visibility of individual points (I can make all the points invisible, but this is different)

Does anyone know if this is possible?

Sort Array of objects to nested array of objects [closed]

First I am initializing a filterArray which will filter those object which have reporting
manager key and they have not the key value of subordinates. Then Declaring an empty array
of companyHirarchy1.looping through both array and using a condition I am assigning a child variable and then calling another function (parentChild) .

var arr = [
    { position: 'CEO' },
    { position: 'COO', reportingManager: 'CEO' },
    { position: 'CFO', reportingManager: 'COO' },
    { position: 'Finance Manager', reportingManager: 'CFO' },
    { position: 'Accountant', reportingManager: 'Finance Manager' },
    { position: 'Bookkeeper', reportingManager: 'Finance Manager' },
    { position: 'Treasurer', reportingManager: 'CFO' },
  ]

I want to show the given array like:

var resultArray = [
     {
         position: "CEO",
         subordinates: [
             {
                 position: "COO",
                 subordinates: [
                     {
                         position: "CFO",
                         subordinates: [
                             {
                                 position: "Finance Manager",
                                 subordinates: [
                                     {
                                     position: "Accountant",
                                     subordinates: []
                                     },
                                     {
                                         position: "Bookkeeper",
                                         subordinates: []
                                     }
                                 ]
                             },
                             {
                                 position: "Treasurer",
                                 subordinates: []
                             }
                         ]
                     },
                   ]
             },
           ]
    },
   ]

Hope so you will understand my question

I tried this but it just throughs the object inside the subordinate of CEO. What I am missing ?

My practice on this problem.
Result of my practice

const imgs has already been declared

Please how do I resolve this error?

Uncaught SyntaxError: Identifier ‘imgs’ has already been declared on line #1

Below I am sharing the code:

const imgs = document.querySelectorAll('.img-select a');
const imgBtns = [...imgs];
let imgId = 1;

imgBtns.forEach((imgItem) => {
    imgItem.addEventListener('click', (event) => {
        event.preventDefault();
        imgId = imgItem.dataset.id;
        slideImage();
    });
});

function slideImage(){
    const displayWidth = document.querySelector('.img-showcase img:first-child').clientWidth;

    document.querySelector('.img-showcase').style.transform = 'translateX(${- (imgId - 1) * displayWidth}px)';
}

window.addEventListener('resize', slideImage);

I don’t understand this error. There are no two declared ‘imgs’ as a constant.