Javascript ES6 confusion [duplicate]

I ran across some code this week that has me very confused. Can someone break down for me exactly what’s going on, line-by-line?

new Date(
  (d => d.setMonth(d.getMonth() - 6))(
    new Date()
  )
)

I understand it’s creating the current date minus six months (which I didn’t expect to work in all cases, but that is an aside). In particular, I don’t understand two things:

a) The variable d. Does this represent the new Date that’s being created on line 1?

b) The second new Date() on line 3. Is d.setMonth() returning a function and new Date() is the parameter?

Thanks in advance!

await doesn’t wait before moving onto next line of code

My code:

async function main(collection, token, symbol) {
  await collection.deleteMany({});
  const priceHistory = await makePriceHistoryRequest(token, symbol, slow*2);
  await insertPriceHistory(collection,priceHistory);
  const res = await priceQuote(token,symbol);
  await insertQuote(collection,res,symbol);
  return await avgFastSlow(fast,slow,collection);
}

My code makes request to 2 endpoints and update MongoDB collection. The last code:

return await avgFastSlow(fast,slow,collection);

takes the updated collection from the two endpoints to calculate fast and slow average. Problem is that it is not waiting before moving onto the this last line of code. Isn’t the point of async function to make it “wait?”

Mystified here. Thanks for the help

node express chart js data parsing/rendering issue

Excel Data

Date    Percentage
04-03-22 (H)    80
05-03-22 (H)    55
06-03-22 (H)    20
07-03-22 (H)    49
08-03-22 (H)    61
09-03-22 (H)    73
TODAY (P)   23
11-03-22 (P)    64

Controller code

datavCenterSpacePredictionModelData = XLSX.utils.sheet_to_json(workbook.Sheets[sheet_name_list[3]]); 

Passing this object to view

await res.render('dashboard', { vCenterSpace:datavCenterSpacePredictionModelData})

In my view I am not able to parse/loop through this data so that it can be passed on to chartjs object.
Chart object need labels and data

const zschart = new Chart(document.getElementById("chartjs-0"), {
                                    "type": "line",
                                    "data": {
                                        "labels": ["04-03-22 (H)","05-03-22 (H)","06-03-22 (H)","07-03-22 (H)","08-03-22 (H)","09-03-22 (H)","TODAY (P)","11-03-22 (P)","12-03-22 (P)","13-03-22 (P)","14-03-22 (P)","15-03-22 (P)"],
                                        "datasets": [{
                                            "label": "Usage in %",
                                            "data": [80,55,20,49,61,73,23,64,60,91,70,95],
                                            "fill": false,
                                            "borderColor": "rgb(75, 192, 192)",
                                            "lineTension": 0.1
                                        }]
                                    },
                                    "options": {}
                                });

when I am trying to get this value, is returning me object. I am checking type of object it is returning me string

var vCenterSpace = ('<%=vCenterSpace%>') //value of node js object into JS
alert(typeof(vCenterSpace ))

I want to dynamically pass these value as below.
These are hardcoded values

"labels": ["04-03-22 (H)","05-03-22 (H)","06-03-22 (H)","07-03-22 (H)",
"data": [80,55,20,49,61,73,23,64,60,91,70,95],

Its all getting messed up, not able to understand how this resolve this.

Is there a way to keep an element inside the boundaries of a div while still having it be position: absolute?

I have an element that displays a tooltip when hovered over, but when the element is on the edge of the screen, the tooltip gets cut off instead of moving to stay in the div.

What it looks like (Tooltip Clipping)

What I want it to look like

Here’s some of my code:

<div class="image">
    <img src="/images/image_name.png" style="left: 100%">
    <span class="tooltiptext">Marker</span>
</div>
.image {
  position: absolute;
  width: 13px;
  height: 13px;
  user-select: none;
  pointer-events: auto;
  transform: translateX(-50%);
}

.image .tooltiptext {
  visibility: hidden;
  opacity: 0;
  transition: opacity 300ms;

  min-width: 90px;
  background-color: #000000e0;
  color: white;
  text-align: center;
  border-radius: 6px;
  padding: 5px 0;
  
  position: absolute;
  z-index: 2;
  bottom: 100%;
  left: 50%;
  transform: translate(-90%, -5px);
}

.image:hover .tooltiptext {
  visibility: visible;
  opacity: 1;
}

Let me know if there’s a way to fix this!
Thanks!

CORS issue with localhost despite proxy

I have created a REST API for the backend of this project and am using React to make the client side of the app. I have been getting this error when I am trying to login to my app.

Access to XMLHttpRequest at ‘https://studioghiblidb.herokuapp.com/login’ from origin ‘http://localhost:1234’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

I was advised to include the local host as a proxy which I did in my client side package.json like this

"devDependencies": {
    "@parcel/transformer-sass": "^2.3.2",
    "process": "^0.11.10"
  },
  "proxy" : "http://localhost:1234/"

On the server side I was instructed to use this code to keep from cross site forgery issues. I have included the essentials as accepted origins

const cors = require('cors');

 let allowedOrigins = [
'http://localhost:8080', 
'http://testsite.com',
'http://localhost',
'http://localhost:1234',
'https://studioghiblidb.herokuapp.com/'
];

app.use(cors({
  origin: (origin, callback) => {
    if(!origin) return callback(null, true);
    if(allowedOrigins.indexOf(origin) === -1){
       let message = 'The CORS policy for this application does not allow found on the list of allowed origin' + origin;
       return callback(new Error(message), false);
  }
  return callback(null, true);
}
}));

I am at a complete loss as to what is causing the CORS error to keep from giving a JWT token and logging in. I have tested in Postman and the users are there and working

How can you add multiple sources in fetch

I’m starting and one of the first things I’m trying on my own is how to add multiple sources to this promise:

    const getTodos = async () =>{
const response = await fetch('todos/resource.json');
if(response.status !== 200){
    throw new Error('Cannot fetch data');
}
const data = await response.json();
return data;
};
getTodos()
    .then(data => console.log ('Resolved: ', data))
    .catch(err => console.log ('Rejected', err.message);

I tried making different variables and using .then after to print them but that didn’t work.

    const getTodos = async () =>{
    const response = await fetch('todos/resource1.json');
    if(response.status !== 200){
        throw new Error('Cannot fetch data'); // Error from the source
    }
    const data = await response.json();
    return data;
    const response2 = await fetch('todos/resource2.json');
    if(response2.status !== 200){
        throw new Error('Cannot fetch data'); // Error from the source
    }
    const data2 = await response2.json();
    return data2;
};

getTodos()
    .then(data => console.log ('Resolved: ', data))
    .then(data2 => console.log ('Resolved: ', data2))
    .catch(err => console.log ('Rejected', err.message)) // Error for json file
    ;

any tips?

why is my admin superuser on node not existing?

Okay so i have a huge problem with a deadline. Im in my final year and i had to do a final year project to graduate. The thing is i could have done it myself, but with all the secondary assignments and projects to also give us to do, i gave a remote developer to do it for me in nodejs. i understand nodejs alot, but ive never encountered this problem. He just gave me back the system and the database. i checked the database and got the email for the admin superuser and tried logging in, but its not working. its saying “email doesnt exist”, so its not that the password is incorrect, the email doesnt exist according to the database. but its the same database i got the admin email. so my question is that how can i be accessing the same database that my system uses and trying the same admin email of the system inside the database but its telling me that the email doesnt exist. is it a problem with my laptop or something else? its a superuser so obviously it is only one so how can it not be existing? im working on a deadline so fast answers would be appreciated.

Restrict creation of new divs to a specific area

I have a small page. Divas in the form of circles are created here every certain time.
They spawn in random places

As can be seen even on the buttons and slightly outside the page

The question is. Is it possible to make a box that does not touch the buttons, and that the circles are created within this box?

This should be done as a border with a certain extension, but specifying everything in pixels is not an option, it will be bad for different screens

//timer

var minutesLabel = document.getElementById("minutes");
var secondsLabel = document.getElementById("seconds");
var totalSeconds = 0;
setInterval(setTime, 1000);

function setTime() {
  ++totalSeconds;
  secondsLabel.innerHTML = pad(totalSeconds % 60);
  minutesLabel.innerHTML = pad(parseInt(totalSeconds / 60));
}

function pad(val) {
  var valString = val + "";
  if (valString.length < 2) {
    return "0" + valString;
  } else {
    return valString;
  }
}

//create circle

var widthHeight = 65;
var margin = 25;
var delta = widthHeight + margin;

let clicks = 0;

function createDiv(id, color) {
  let div = document.createElement('div');
  var currentTop = 0;
  var documentHeight = document.documentElement.clientHeight;
  var documentWidth = document.documentElement.clientWidth;
  div.setAttribute('class', id);
  if (color === undefined) {
    let colors = ['#35def2', '#35f242', '#b2f235', '#f2ad35', '#f24735', '#3554f2', '#8535f2', '#eb35f2', '#f2359b', '#f23547'];
    div.style.borderColor = colors[Math.floor(Math.random() * colors.length)];
  }
  else {
   div.style.borderColor = color; 
  }
  div.classList.add("circle");
  div.classList.add("animation");
  
  currentTop = Math.floor(Math.random() * documentHeight) - delta;
  currentLeft = Math.floor(Math.random() * documentWidth) - delta;
  
  var limitedTop = Math.max(margin * -1, currentTop);
  var limitedLeft = Math.max(margin * -1, currentLeft);

  div.style.top = limitedTop + "px";
  div.style.left = limitedLeft + "px";
  
  const nodes = document.querySelectorAll('.animation');
  for(let i = 0; i < nodes.length; i++) {
  nodes[i].addEventListener('click', (event) => {
    event.target.style.animation = 'Animation 200ms linear';
    setTimeout(() => {
      event.target.style.animation = '';
    }, 220);  });
  }
  
  $(div).click(function() {
    $('#clicks').text(++clicks);            
    $(this).fadeOut();
  });
  
  document.body.appendChild(div);
}
    
let i = 0;

const oneSecond = 600;

setInterval(() => {
  i += 1;
  createDiv(`circle${i}`);
}, oneSecond);
html, body {
  width: 100%;
  height: 100%;
  margin: 0;
  background: #0f0f0f;
}

.back {
  font-family: "Comic Sans MS", cursive, sans-serif;
  font-size: 25px;
  letter-spacing: 2px;
  word-spacing: 2px;
  color: #ffffff;
  text-shadow: 0 0 5px #ffffff, 0 0 10px #ffffff, 0 0 20px #ffffff, 0 0 40px #ff00de, 0 0 80px #ff00de, 0 0 90px #ff00de, 0 0 100px #ff00de, 0 0 150px #ff00de;
  font-weight: 700;
  text-decoration: none;
  font-style: italic;
  font-variant: normal;
  text-transform: lowercase;
  position: absolute;
  top: 25%;
  left: 2%;
  user-select: none;
  z-index: 999;
}

.panel {
  color: #0f0f0f;
  font-size: 40px;
  z-index: 999;
  position: absolute;
  cursor: default;
  user-select: none;
  color: #0f0f0f;
}

.score {
  border: 1px solid #ffffff;
  padding: 5px;
  background-color: #ffffff;
  border-radius: 40px 10px;
}

.time {
  border: 1px solid #ffffff;
  padding: 5px;
  background-color: #ffffff;
  border-radius: 40px 10px;
}

.circle {
  width: 30px;
  height: 30px;
  border-radius: 30px;
  background-color: #0f0f0f;
  border: 3px solid #000;
  margin: 20px;
  position: absolute;
}

@keyframes Animation {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(.8);
  }
  100% {
    transform: scale(1);
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="panel">
<span class="score">Score: <a id="clicks">0</a></span>
<span class="time">Time: <label id="minutes">00</label>:<label id="seconds">00</label></span>
</span>
<a href="" class="back">back</a>

Detect when all Dropzones have been appended to a form

I have a page with multiple dropzones each set up for one image. When the user submits the form, all the images attached to the dropzones are resized and then appended to the rest of the form fields.

When this is done I send the form data via fetch. I need to wait for the all the images to be resized and appended and then send the form. How can I do this?

Current code:

  dropzones.forEach((dropzone, key, dropzones) => {
    let { paramName }  = dropzone.options
    let { resizeWidth }  = dropzone.options
    if (dropzone.files.length > 0){
      dropzone.resizeImage(dropzone.files[0], resizeWidth, null, 'contain', resizeDone, paramName); // note: resizeImage() in dropzone.js has been edited to add paramName
    }
    if (Object.is(dropzones.length - 1, key)) { // this is the final iteration
      console.log('last one') // output before resizing complete
    }
  })

  function resizeDone(newfile, paramName){
    console.log(newfile);
    console.log(paramName);  
    form.append(paramName, newfile);    
  }

Somehow I need to detect the final image has been resized and appended before calling fetch();

Comment section for webpage not able to see comments on another device

So, I want to make a comment section on my webpage and I’m using JS, JQUERY and HTML but I do not know enough to change my code so please give me the code I need instead of saying just do this. example of what not to do: Oh, you need a database (I already know that). Ok let’s get to the point. When I open the .html file on a different device, the comments are gone, and this is because I am using JS localStorage which stores the comments on the device it was written on so now let’s get to the real point I need a database. But I do not know how to make one. This is what I’m using or think I need to make the database: Xampp. Here is my code:

    function render(data) {
    var html = "<div class='commentBox'><div class='rightPanel'><span class='uu'>"+data.name+"</span><div class='date'>"+data.date+"</div><p class='ww'>"+data.body+"</p><div class='clear'></div></div></div><br>";
    $('#container').append(html);
    
    
} 


$(document).ready(function() {
var comment = [];

if(!localStorage.commentData3) {
    localStorage.commentData3 = [];
} else {
    comment = JSON.parse(localStorage.commentData3);
}

//var Talk1 =  localStorage.commentData3;

for(var i=0; i<comment.length; i++){
    render(comment[i]);
}

$('#addComment').click(function() {
    var addObj = {
        "name": $('#name').val(),
        "date": $('#date').val(),
        "body": $('#bodyText').val()
    };
    
    //console.log(addObj);
    comment.push(addObj);
    localStorage.commentData3 = JSON.stringify(comment);
    render(addObj);
    $('#name').val('');
    $('#date').val('');
    $('#bodyText').val('');
});

});
    body {
      background-image: url("background.jpg");
      font-family: "Comic Sans MS";
    }
    
    .middle {
      width: 50%;
      margin: auto;
      background: white;
      border: 1px solid white;
      padding: 2rem;
      border: 2px solid #636363;
    }
    
    a { color: #cd90b0; }
    a:hover { color: #dfc3d2; }

.form {
  border: 1px solid #000000;
  text-align: center;
  padding: 2.5rem;
  background-color: #dfc3d2;
}

.hw {
  text-align: center;
  color: #cd90b0;
}

.hideIt { #visibility: hidden; }

.leftPanelImg img {
  border-radius: 100%;
}

.jj {
  background-color: #eeeeee;
  padding: 1rem;
}

.hh {
  background-color: #eeeeee;
  padding: 1rem;
}

.mm {
  background-color: #f3f6f4;
  padding: 1rem;
}

.commentBox {
  border-bottom: 1px solid #796f6f;
  border-top: 1px solid #796f6f;
  background-color: #e2e2e2;
  padding: 1rem;
}

.uu {
  padding-left: 1rem;
  padding-right: 1rem;
  #background-color: #ffffff;
}

.ww {
  background-color: #efecec;
  padding-bottom: 0.5rem;
  padding-top: 0.5rem;
  padding-right: 0.3rem;
  padding-left: 0.3rem;
  border: 1.5px solid #dfc3d2;
}

.date {
  padding-left: 1rem;
  padding-right: 1rem;
}
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<div class="middle">
    <div class="hideIt">
    <div class="hw"><h4>Comment Below:<h4></div>
    <div id="container">
      
    </div>
    <br>
    <br>
    <br>
    <div class="form">
    <form action="post-comment.php">
      <input type="text" id="name" placeholder="Name..."></input><br />
      <input type="date" id="date" placeholder="Date..."></input><br />
      <textarea rows="5" col="30" id="bodyText" placeholder="Type your body here..."></textarea><br />
      <input type="button" id="addComment" value="Add Comment">
      </form>
    </div>
    </div>
    <br><br><br><br>
    </div>
please tell me the code for what database I need




                                          thanks!

catch error in express route is not working

I am working in node js to create API it’s function as follow
This API will be used to send images from Images folder then store the image name which has been sent to the images_thumb folder
after resizing the image with Sharp
if the server got request for any image which has been sent before the API shall send the image from Images_thumb folder
—-Proplem
When ever I open the browser to http://localhost:3000/?name=6 (6 is an image name not exists in the images folder for example)
the image name is added to visited array and i donot know how to send res.send(“file not found”)

const express = require("express");
const sharp = require("sharp");


const app = express();
let visited = []; // This array is used to sore file names for comparison later
let found; // Boolean to be true if the file name exists in Visited Array

 app.get("/", (req, res) => {
 if (visited.length == 0 ) { // is the server just started 
console.log(typeof res.statusCode);
sharp(__dirname + "\images\" + req.query.name + ".jpg") // sharp is used to resize the image 
 and save the resized version in the Images_thumb folder
    .resize(200,200)
    .toFile(__dirname + "\images_thumb\" + req.query.name + ".jpg")
    .then(console.log("done")).catch((err)=>{
      res.send('Not found');
      console.log(err);
    })
res.sendFile(__dirname + "\images\" + req.query.name + ".jpg");
visited.push(req.query.name);
console.log("initial length 0");

} else if (visited.length > 0) {
for (let index = 0; index <= visited.length; index++) { // used to chek if file name existis
in the array Visited
const element = visited[index];
console.log(index + “loop”);
if (element === req.query.name && res.statusCode==200) {

    res.sendFile(__dirname + "\images_thumb\" + req.query.name + ".jpg");
    console.log(index + "break");
    found = true;
    //res.send(index+"break")
    break;
  } else {
   
    console.log("false");
    found = false;
  }
}

} else {
}

if (visited.length > 0 && found == false ) { // used if file name not in Array visited and Array
length >0
sharp(__dirname + “images” + req.query.name + “.jpg”)
.resize(200,200)
.toFile(__dirname + “images_thumb” + req.query.name + “.jpg”)
.then(console.log(“done”)).catch((err)=>{
res.send(‘Not found’);
console.log(err);
});

      res.sendFile(__dirname + "\images\" + req.query.name + ".jpg");
      visited.push(req.query.name);
      console.log(visited);
   

};

 // res.sendFile(__dirname + "\images_thumb\" + req.query.name + ".jpg");
});

app.listen(3000, function () {
   console.log("running");
});

the file structiure as follow
main folder inside is images and images_thumb folder with server.js

What are the right types for a useContext with TypeScript/ReactJS?

I am refactoring to TypeScript a tutorial in ReactJS that I am following. For the most part, the tutorial teaches you how to refactor most of the code as bonus material. However the log-in part is done in ReactJS/JavaScript only and I tried to refactor my code as a way to challenge myself. The part I am stuck on is createContext as I am not able to understand the types needed.

Original JS code

JS code – Context/Provider

import React, { useState, createContext } from "react";


export const Context = createContext();

const UserProvider = ({ children }) => {
    const [state, setState] = useState(undefined);

    return (
        <Context.Provider value={[state, setState]}>{children}</Context.Provider>
    )
};

export default UserProvider;

On the Login component it gets called with const [_user, setUser] = useContext(Context);

My attempt

What I’ve tried

I tried to apply the following solutions and I’m not really grasping the concepts well enough to apply them successfully:

TS code – Context/Provider

import React, { useState, createContext } from "react";
import { IUser, UserContextType } from "./@types/context";


export const Context = createContext<UserContextType | undefined>(undefined);

const UserProvider: React.FC<React.ReactNode> = ({ children }) => {
    const [state, setState] = useState<IUser[]>([]);

    return (
        <Context.Provider value={{state, setState}}>{children}</Context.Provider>
    )
};

export default UserProvider;

TS code – types

export interface IUser {
    user: string;
    password: string;
};

export type UserContextType = {
    sessions: IUser[];
    saveSession: (newSession: IUser[]) => void;
};

Errors

<Context.Provider value={{state, setState}}>{children}</Context.Provider>

Type ‘{ state: IUser[]; setState: React.Dispatch<React.SetStateAction<IUser[]>>; }’ is not assignable to type ‘UserContextType’. Object literal may only specify known properties, and ‘state’ does not exist in type ‘UserContextType’.ts(2322)

const [_user, setUser] = useContext(Context);

Type ‘UserContextType | undefined’ is not an array type.ts(2461)