Why is the fetch request time and request time displayed in the Chrome Network Timing tab different?

I am trying to understand why the total fetch request time logged by my application is different than the time displayed in the Chrome Dev Tools “Network > Timing” tab.

Consider this example that logs the difference between the fetch start time & the time of the fetch response:

const startTime = new Date();
fetch('https://somedomain.com/api/route')
  .then(res => {
    const completeTime = new Date().getTime();
    console.log(completeTime - startTime)
  })

Now, when I check Chrome’s “Network” tab, click on the request in the list and then click on the “Timing” tab- I am presented with a breakdown of the different phases of the request with the total time listed at the bottom. This time is always less than the time logged from example above. Normally the difference is 1-10ms but I have observed differences as high as a several hundred milliseconds.

What factors influence this difference?

Passing Async State to Next.js Component via Prop

I’m fetching WordPress posts asynchronously via getStaticProps()

export async function getStaticProps({ params, preview = false, previewData }) {
    const data = await getPostsByCategory(params.slug, preview, previewData)
    return {
        props: {
            preview,
            posts: data?.posts
        },
    }
}

… and passing them to useState:

const [filteredArticles, setFilteredArticles] = useState(posts?.edges)

Then, I pass the state to a component:

router.isFallback ? (
    // If we're still fetching data...
    <div>Loading…</div>
) : (
    <ArticleGrid myArticles={filteredArticles} />

This is necessary because another component will setFilteredArticles with a filter function.

But when we are passing the state to ArticlesGrid, the data is not ready when the component loads. This is confusing to me since we passing the state within a router.isFallback condition.

Even if we set state within useEffect

const [filteredArticles, setFilteredArticles] = useState()
useEffect(() => {
    setFilteredArticles(posts)
}, [posts?.edges])

… the data arrives too late for the component.

I’m new to Next.js. I can probably hack my way through this, but I assume there’s an elegant solution.

Hide functions/vuex module from clientside?

I have a vuex module that i want to be used/imported only when the user call its, but when i import it in the vuex.modules it imports globally so the functions can be viewed from devtools.

I read functions/modules could be hidden with SSR either using Nuxt or another library.
Is this possible? is there a way to hide functions/modules from the client-side either using vuex or not?

Thanks.

Can I patch a function in one webpack bundle from another at runtime?

I am writing a plugin for a third-party web application, whose code I can see but can’t modify. I’m running it in Chrome. The main webapp and the plugin are both (separate) webpack bundles. At runtime when the page loads, the webapp fetches the plugin bundles from the same server, and initialises them.

My objective is to make my plugin patch/wrap a function in a module webapp/utils/target.tsx in the application, such that calls to that function from within the webapp have my modified behaviour. I am not at all experienced with javascript, particularly how modules work in browsers.

When the page is fully loaded and the app has loaded my plugin, in Chrome developer tools under Sources -> Page, I see:

localhost:port
.
com.mydomain.myplugin
  <modules for my plugin>
application
  webapp
    .
      <other modules>
      utils
        target.tsx
    webpack

I was thinking I may be able to do something like this:

import(/*webpackIgnore: true*/ 'application/webapp/utils/target').then((target) => {
    oldFunc = target.targetFunc;
    target.targetFunc = function targetFunc(args) {
        // do extra stuff here
        return oldFunc(args);
    }
});

Not surprisingly, this fails (I get Failed to resolve module specifier 'application/webapp/utils/target'). I don’t know if it’s possible to import the module from the main webapp this way.

The webapp also makes various functions available for plugins to call, by attaching them to the window object. So window.AppUtils.targetFunc is accessible globally to call. I also tried doing this:

window.AppUtils.targetFunc = function targetFunc(args) {
    // do extra stuff here
    return oldFunc(args);
}

I would not even expect that to affect calls to targetFunc from within the webapp because they wouldn’t reach the function via this reference. I was surprised to find that it doesn’t seem to work even for cases where I call window.AppUtils.targetFunc directly.

Is what I am trying to do even possible…?

I’m getting an error when I try to add value in my DataBase Uuing MongooDB

I would like to add to my Database using MongooDB values with the following code but when my code is running the data I want to add to my database does not add

const profileModel = require('../DataBase/Schema.js')


function UserTotal(userId,TotalForTheSession){
    const time = new Date();
    
    var TotalTimeUserPath = './Settings/UserDataTotal.json'
    var TotalTimeUserRead = fs.readFileSync(TotalTimeUserPath);
    var TotalTimeUserFile = JSON.parse(TotalTimeUserRead); //ready for use
    
    var theyear = time.getFullYear();
    var themonth = time.getMonth() +1;
    var thetoday = time.getDate();
    
    let DateAllTogether = `${theyear}/${themonth}/${thetoday}`
    
    async function totalTimeDataBase(userId,TotalForTheSession,DateAllTogether){
        let userData
        try{
            userData = await profileModel.modelUser.findOne({userID: userId})
            if (!userData){
                let profile = await profileModel.modelUser.insertMany({
                    userID : userId,
                    totalTime: TotalForTheSession,
                    timeDate: {
                        [DateAllTogether]: TotalForTheSession
                    }        
                })   
            }
            else if (!userData.timeDate[DateAllTogether]){
                await profileModel.modelUser.updateOne({
                    userID:userId, "timeDate": {
                        $add: [[DateAllTogether], TotalForTheSession]
                            
                      },
                },
                )
            }       
        }catch(err){
            console.log(err)
        }
    }   
    totalTimeDataBase(userId,TotalForTheSession,DateAllTogether)

The code for how my Schema in my dataBase is made

const mongoose = require('mongoose')

const profileSchema = new mongoose.Schema({
    userID: {type: String, require: true},
    timeTotal: {type: String, default: 0 },
    timeDate:{}
})



const modelUser = mongoose.model('ProfileModels', profileSchema)


module.exports = {modelUser}



When the code is executed i’m getting this errorMongoServerError: The dollar ($) prefixed field '$push' in 'timeDate.$push' is not valid for storage.*


The file where my data is stored in my database

{
    "_id" : ObjectId("61bd159db3daaef59378e5f1"),
    "userID" : "526166979321790466",
    "timeTotal" : "0",
    "timeDate" : {
        "2021/12/16" : 1
    },
    "__v" : 0
}

I want to add “2021/12/17” : 1 in “timeDate” value like so

{
    "_id" : ObjectId("61bd159db3daaef59378e5f1"),
    "userID" : "526166979321790466",
    "timeTotal" : "0",
    "timeDate" : {
        "2021/12/16" : 1,
        "2021/12/17" : 1
    },
    "__v" : 0
}

Click event not firing when input field is active

I have an Angular project with a setup similar to this:

<input type="text" [(ngModel)]="search" >
<app-item-list
    [items]="foundItems"
    (itemClick)="onItemSelected($event)">
</app-item-list>

There’s an input field that the user types in. As they type, the item-list component populates with results.

In the item list component, it simply shows all items passed in, and if one is clicked, it fires the event itemClick

So long as the input remains active, the user must click twice on an item in order for the click event to fire. Clicking anywhere else (to deselect the input field) and then clicking an item also works.

This is supposed to be some sort of search ‘dropdown box’, where typing displays a list of autocomplete-like options fetched from elsewhere. It works fine other than having to click twice. The first click only fires an ngModelChange event and the second fires the itemClick event.

When parts of an image are added, some parts do not? [closed]

Here I have made the head, body and legs separately from Photoshop. I want to add them from JavaScript and create different shapes(actions).

But when it works, the parts fall apart and add up. (Sometimes the head is lost, sometimes the legs are lost, sometimes the body and the head are both lost) Sometimes everything comes together correctly (head+body+leg).

enter image description here

hey guys iam trying to create my reacte app an i i have aproblem i dont where i can fix it

hey guys iam trying to create my reacte app an i i have aproblem i dont where i can fix itstrong text
i wrote this code but its not return a data to me and i don’t know where the problem please help
using ccreate a reacct app
hey guys iam trying to create my reacte app an i i have aproblem i dont where i can fix itstrong text
i wrote this code but its not return a data to me and i don’t know where the problem please help
using ccreate a reacct app
//this my app.j s

import Employees from "./Components/Employees";

import "bootstrap/d ist/css/bootstrap.min.css";



export default function App() {
  return (
    <div 
      
      <Employees/>
  

    </div>
  );
}


// this my Employee. j s x
import React,  { useEffect, useState } from "react";

import axios from "axios";

function Employee(props) {
    const [employeeData, setEmployeeData] = useState(null);
    useEffect(
        function(){
           a x i o s
           .get(`http://statenweb.mockable.io/employee/${props.selectedEmployee}`) // this is the data 
           .then(function(response){
               setEmployeeData(response.data);
           });
                
            },
            [props.selectedEmployee]
            
            );
            
            if (!employeeData){
            return <p> loading....</p>;
}

return(
    <div>
        <img 
    style={{ maxHeight: "300px"}}
src={employeeData.photo}

alt={employeeData.name}
/>
<p>{employeeData.name}</p>



    </div>
)
}
export default Employee;


// this my Employees.j s x

import a x i os from "ax i os";
import React,{useEffect, useState} from "react";
//import Employee from "./Employee";


function Employees(){

const [employees, setEmployees] = useState([]);
const [selectedEmployee, setSelectedEmployee] = useState(null);

function getAllEmployees(){

ax i o s . g et("https://statenweb.mockable.io/employees").then(function(response){
setEmployees(response.data);
});
}

if (selectedEmployee){
    return(
        <div>
            <p>you selected a {selectedEmployee}</p>
            
            <button  onClick={() => setSelectedEmployee(null)}>Reset</button>
        </div>
    );
}




return(
    <div>
        <button onClick={getAllEmployees}>get all the employees</button>
        {employees.map(function(employee){
            return(
                <p key={employee.id}>
                    <button  onClick={() => setSelectedEmployee(employee.department)}>
                    my name is {employee.name}- ID: {employee.id}

                        
                    </button>
                </p>
            );
        })}
    </div>

    );
    }

    
export default Employees ;

how to make an interactive button that creates a semicircle around it when clicked

So I want to create a button that would go in the bottom of my screen and create a semicircle around it with more buttons inside when clicked. I’ve tried adjusting the CSS but Im not able to come up with a solution. Do you guys know a way to do it? I came across this codepen (“https://codepen.io/jet/pen/LwiGu”), which is almost exactly what I want, instead of creating a whole circle around it, it would create a semicircle around the top. I’ve attached an image for you guys to understand it better.

var items = document.querySelectorAll('.menuItem');

for(var i = 0, l = items.length; i < l; i++) {
  items[i].style.left = (50 - 35*Math.cos(-0.5 * Math.PI - 2*(1/l)*i*Math.PI)).toFixed(4) + "%";
  
  items[i].style.top = (50 + 35*Math.sin(-0.5 * Math.PI - 2*(1/l)*i*Math.PI)).toFixed(4) + "%";
}

document.querySelector('.center').onclick = function(e) {
   e.preventDefault(); document.querySelector('.circle').classList.toggle('open');
}
@import "https://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css";

body {
  /* Image source: http://wallbase.cc/wallpaper/718405 */
  /* Excuse the base64 mess, imgur blocked the hotlinked image and this seemed like the fastest solution */
  background: cornflowerblue url(" data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAAAoCAYAAABOzvzpAAAACXBIWXMAAAsTAAALEwEAmpwYAAAOlUlEQVRo3k2aTWLj2o6DP5BHTt7dUk97C73/dbyySPSAlOoOXE7slC3+gQCO9L//839WiAyICDIAQYQAw/7bbtrmbmM35cKe9+Um1USYC8goroSfNJ+E3zS/R/xm83uJ/xzzk+L3Ej8h8ogTQhGgxErK4tahHHw7uB18ndwt7t5nB98W1eLr5Ntwd3Dv89dwF/xp+N7mW1DdfKupbm6bg5ggJDIEMplBaF5DYBuTNCa7KYss0RgoQKSCAI6KDHFlcG0iriu40nyu5OfAzxE/F/wc+JwgM0iJiAm+lYhATuTAJGERHciHaBP9vDYJiA5OiT/7c7ahgwjjalCADCW8RU2bI4Q0AQNkwBFkBhIQML1guk0HtE0f0Z4UYCGZxKTgRPBJuAI+F/wE/Fzm9yN+Uvxc5ucEP5e4TnBC831PAkhugiCRDmFx+6AS4ZiKtzj+W+1T8O0gS5yG7y3U5k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FfEN7PM2r3Ydseezr25z1nMKgXJ4Qo0ifLhiStH6fg3o8yH+1d/+78vwNnvUx1A0FR3vs9DCZ0ekNe4fW698/tlmPO1zbN7SXq/fgwzrKuYZpi/fmqdy2rnzMz353xFjTgzu5p0PB3MzUvfejadZ10VRoZ/25gWtI0d+7VvgXlX4MlL+z7+U9/w/sgwZKH+EVWgAAAABJRU5ErkJggg==") no-repeat fixed;
  background-size: cover;
}

a {
  font-size: 14px;
  text-decoration: none;
  outline: 0;
}

.circle,
.ring {
  height: 256px;
  position: relative;
  width: 256px;
}

.circle {
  margin: 0 auto;
}

.ring {
  background-color: rgba(0,0,0,0.5);
  border-radius: 50%;
  opacity: 0;

  -webkit-transform-origin: 50% 50%;
  -moz-transform-origin: 50% 50%;
  transform-origin: 50% 50%;

  -webkit-transform: scale(0.1) rotate(-270deg);
  -moz-transform: scale(0.1) rotate(-270deg);
  -transform: scale(0.1) rotate(-270deg);

  -webkit-transition: all 0.4s ease-out;
  -moz-transition: all 0.4s ease-out;
  transition: all 0.4s ease-out;
}

.open .ring {
  opacity: 1;
  
  -webkit-transform: scale(1) rotate(0);
  -moz-transform: scale(1) rotate(0);
  transform: scale(1) rotate(0);
}

.center {
  background-color: rgba(255,255,255,0.3);
  border-radius: 50%;
  border: 2px solid #ffffff;
  bottom: 0;
  color: white;
  height: 80px;
  left: 0;
  line-height: 80px;
  margin: auto;
  position: absolute;
  right: 0;
  text-align: center;
  top: 0;
  width: 80px;
  
  -webkit-transition: all 0.4s ease-out;
  -moz-transition: all 0.4s ease-out;
  transition: all 0.4s ease-out;
}

.open .center {
  border-color: #aaaaaa;
}

.menuItem {
  border-radius: 50%;
  color: #eeeeee;
  display: block;
  height: 40px;
  line-height: 40px;
  margin-left: -20px;
  margin-top: -20px;
  position: absolute;
  text-align: center;
  width: 40px;
}
<div class="circle">
  <div class="ring">
    <a href="" class="menuItem fa fa-home fa-2x"></a>
    <a href="" class="menuItem fa fa-comment fa-2x"></a>
    <a href="" class="menuItem fa fa-play fa-2x"></a>
    <a href="" class="menuItem fa fa-camera fa-2x"></a>
    <a href="" class="menuItem fa fa-music fa-2x"></a>
    <a href="" class="menuItem fa fa-user fa-2x"></a>
    <a href="" class="menuItem fa fa-trash-o fa-2x"></a>
    <a href="" class="menuItem fa fa-star fa-2x"></a>
  </div>
  <a href="#" class="center fa fa-th fa-2x"></a>
</div>

[menu mockup][1]
[1]: https://i.stack.imgur.com/GR419.png

Node JS displaying value at index instead of indices

Written this 2sums code to get efficent O(N) Time complexity algorithm for below problem

            Input: nums = [2,7,11,15], target = 9
            Output: [0,1]
            Output: Because nums[0] + nums[1] == 9, we return [0, 1].

unfortunately saw value at array nums got displayed in the output ,whereas the need is to get the indices to be displayed in output

What change needs to be done below

            let hashTwoSum = (array, sum) => {
                let numsObj = {}
                let nums = []
               
                for(let i in array){
                    let addend = sum - array[i]
                   
                    if (addend in numsObj){

                        nums.push([addend, array[i]])

                    }
                    numsObj[array[i]] = i

                    
                }
                return nums
                
            }

            let array = [2,7,11,15]
            console.log(hashTwoSum(array,9))
            
            

Your help is appreciated

Regards,

Carolyn

Is an array of ints actually implemented as an array of ints in JavaScript / V8?

There is claim in this article that an array of ints in JavaScript is implemented by a C++ array of ints.

However; According to MDN unless you specifically use BigInts, in JavaScript all numbers are repressed as doubles.

If I do:

cont arr = [0, 1, 2, 3];

What is the actual representation in the V8 engine?

The code for V8 is here on github, but I don’t know where to look:

Why is Discord API returning error 405 for adding a slash command to a guild?

I’m currently making a bot in discord.js, and I’m trying to build a command handler ( for slash commands specifically). Unfortunately, whenever i run the code, it returns a 405 error from the discord API. here is the error:

DiscordAPIError[0]: 405: Method Not Allowed
    at SequentialHandler.runRequest (/home/ayman/Documents/Projects/image-bot/node_modules/@discordjs/rest/dist/lib/handlers/SequentialHandler.js:198:23)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async SequentialHandler.queueRequest (/home/ayman/Documents/Projects/image-bot/node_modules/@discordjs/rest/dist/lib/handlers/SequentialHandler.js:99:20)
    at async /home/ayman/Documents/Projects/image-bot/src/main.js:35:5 {
  rawError: { message: '405: Method Not Allowed', code: 0 },
  code: 0,
  status: 405,
  method: 'put',
  url: 'https://discord.com/api/v9/applications/921468165576347658/guilds/545334770368774146/commands/undefined'
}

And here is the problematic code:

(async () => {
    try {
        if (process.env.ENV === "production") {
            await rest.put(Routes.applicationCommand(CLIENT_ID), {
                body: commands,
            });
            console.log("Commands successfully registered globally.");
        } else {
            await rest.put(Routes.applicationGuildCommand(CLIENT_ID, process.env.GUILD_ID), {
                body: commands,
            });
            console.log("Commands successfully registered locally.");
        }
    } catch (err) {
        if (err) console.error(err);
    }
})();

Is there any reason why this is happening? Thanks for any help!

Render multiple image carousels in a mapped array

I have an array of objects with data and one of the key is gallery, which is an array of URLs: data=[{id:1,gallery:[]},{id:2, galery:[]}].
I did an image carousel in the mapped “data” array. The problem is that the carousels, of each item, are not independent one of each other. Each time I change the picture on one of them, it changes to the other also.
Here is the code:

export class MyComponent extends Component {
    render() {
       return (
         <section>                
           {data &&
              data.map((item, i) =>
                (<div key={i}>
                   <div>
                    ...some data here
                   </div>
                    <div className='carousel' key={item}>
                            <img src={left}
                                className='left-arrow' alt="left"
                                onClick={() => prevSlide(item.gallery)} />
                            <img src={right}
                                className='right-arrow' alt="right"
                                onClick={() => nextSlide(item.gallery)} />
                            {item && item.gallery?.map((img, j) => (
                                <>
                                 {j === this.state.current && (
                                  <img src={img} alt={item.id} className='cart-image' key={j} />
                                    )}
                                </>
                            ))}
                    </div>
                 </div>))}
         </section>)}}
export default MyComponent

I want to have a different carousel for each item from data array. For the moment it is working like a big one, instead of two.
For me it is strange that all the other data it is rendered the way I want.
Could you please help me?
Thank you in advance

Ajv javascript schema validation with regex in key value

I have a schema to validate with Ajv in Node.js. There is a recurrent pattern on the properties of the json to convalidate, the possible keys value are 1,2,3,4,5. The question is, it’s possible with a regex expression to express only one property that will explain to ajv that the keys value of the json object could be an integer between one and five? And if so, how?

Below there is an example of the current code.

const Ajv = require("ajv")
const ajv = new Ajv()

const validate_setparameters = ajv.compile(
    {
        type: "object",
        properties: {
            "1": { type: "integer"},
            "2": { type: "integer"},
            "3": { type: "integer"},
            "4": { type: "integer"},
            "5": { type: "integer"}
        },
        additionalProperties: false,
        minProperties: 1
    }
)

console.log(validate_setparameters({"3":1}))