Sorting Dates in Node.js

I’m pretty new to javascript, and I’m working on a dashboard in which I want to display all of the dates since the first order was created. I have created the code that I need to add the dates for orders where the orders have not been created (with orders as 0), but now I’m having an issue where the dates that have orders created are listed in the beginning of the graph instead of in chronological order with the rest of the dates in the graph. I think this is a sorting issue, but I’m not sure, and my attempts to sort the date haven’t really made any changes to the graph. I would really appreciate any help or advice on how to fix this issue.

enter image description here

import express from 'express';
import expressAsyncHandler from 'express-async-handler';
import Order from '../models/orderModel.js';
import User from '../models/userModel.js';
import Product from '../models/productModel.js';
import {isAdmin, isAuth, isSellerOrAdmin, mailer, payOrderEmailTemplate} from '../utils.js';

const orderRouter = express.Router();
orderRouter.get(
  '/summary',
  isAuth,
  isAdmin,
  expressAsyncHandler(async (req, res) => {
function getDates(startDate, stopDate) {
  var dateArray = new Array();
  var currentDate = new Date(startDate);
  while (currentDate.getTime() <= new Date(stopDate).getTime()) {
      dateArray.push(getFormattedDate(currentDate));
      currentDate.setDate(currentDate.getDate() + 1)
      dateArray.sort((startDate, stopDate) => new Date(stopDate[0]).getTime() - new  Date(startDate[0]).getTime());
  }
  return dateArray;
}
  
    const dailySales = await Order.aggregate([
      {
        $group: {
          _id: { $dateToString: { format: '%m-%d-%Y', date: '$createdAt' } },
          orders: { $sum: 1 },
          sales: { $sum: '$totalPrice' },
          date: {$first: '$createdAt'}, 
        },
      },
      { $sort: { date: 1 } },
    ]);
  
  
    let today = new Date();

    let date=parseInt(today.getMonth()+1)+ "-"+ today.getDate()+"-"+today.getFullYear();
    
    
    const datesArray = getDates(dailySales[0]._id, date)
    
    
    for(let dateVal of datesArray){
      
     let isInArray = false;
     
     for(let dayVal of dailySales){
  
      
       if(dayVal._id === dateVal){
         isInArray = true;
       }
   
     }
       if(isInArray == false){
        dailySales.push({ "_id":dateVal, "orders":0, "sales":0}) 
      }
   }
res.send({dailySales});
  })
);

Error: net::ERR_SSL_PROTOCOL_ERROR when playing upload video in React component

As per the title, I’m uploading a video file using React Hooks. Then, I’m trying using to use video-react package to visualize the uploaded video.

The video visualizer works properly if no video is provided, which just default to this source https://media.w3.org/2010/05/sintel/trailer_hd.mp4 as in the official documentation.

However, when I update the Player's src property with the uploaded video & I click on the play button, I get this error in the dev console:

GET https://localhost:3000/video1.mp4 net::ERR_SSL_PROTOCOL_ERROR

This is my code:

import { Player } from 'video-react';
import  React, { useState } from 'react';

const App = () => {
  const [video, setVideo] = useState('');

  const handleUpload = e => setVideo(e.target.files[0]);

  return (
    <div className="App">
      <h1>Video Visualizer</h1>
      <input type="file" name="file" onChange={handleUpload} />

      <Player
        playsInline
        poster="/assets/poster.png"
        src={ video ? `https://localhost:3000/${video.name}` : "https://media.w3.org/2010/05/sintel/trailer_hd.mp4" }
      />
    </div>
  );
}

export default App;

I’m trying to start my discord bot and I’m getting an error. I need help so bad. I’m getting ESM error [duplicate]

New to stack overflow. So I’m currently trying to code a multipurpose discord bot for a school project as well as for personal use and I have pretty much the entire code written, but I am unable to debug. I’m going to input my “index.js” which is my main file and if more is required please let me know and I can attach that as well. After inputting node . to turn on my discord bot I am getting “Error [ERR_REQUIRE_ESM]: require() of ES Module C:UsersDesktopDiscordBotnode_moduleschalksourceindex.js from C:UsersDesktopDiscordBotindex.js not supported. Instead change the require of C:UsersDesktopDiscordBotnode_moduleschalksourceindex.js in C:UsersDesktopDiscordBotindex.js to a dynamic import() which is available in all CommonJS modules.” My current index.js code is

const chalk = require("chalk");

const { Client, Collection, Intents, MessageEmbed } = require("discord.js");
const { DEFAULT_PREFIX, BOT_TOKEN, ERROR_LOGS_CHANNEL, ALEXFLIPNOTE_API_KEY, YT_COOKIE } = require("./config.json");
const { loadCommands } = require("./handler/loadCommands");
const { loadEvents } = require("./handler/loadEvents");
const { loadSlashCommands } = require("./handler/loadSlashCommands")
const { loadPlayerEvents } = require("./handler/loadPlayerEvents");
const { DiscordTogether } = require('discord-together')
const { Player } = require('discord-player')
const Enmap = require("enmap")

const client = new Client({
    allowedMentions: { parse: ["users", "roles"] },
    intents: [
        Intents.FLAGS.GUILDS,
        Intents.FLAGS.GUILD_MESSAGES,
        Intents.FLAGS.GUILD_MEMBERS,
        Intents.FLAGS.GUILD_MESSAGE_REACTIONS,
        Intents.FLAGS.GUILD_WEBHOOKS,
        Intents.FLAGS.GUILD_VOICE_STATES,
        Intents.FLAGS.GUILD_INVITES,
        Intents.FLAGS.GUILD_BANS,
        Intents.FLAGS.GUILD_PRESENCES,
    ],
});
const { checkValid } = require("./functions/validation/checkValid")
const Embeds = require("./functions/embeds/Embeds")
const Logger = require("./functions/Logger/Logger")
const Util = require("./functions/util/Util")

const alexClient = require("alexflipnote.js")
client.images = new alexClient(ALEXFLIPNOTE_API_KEY)
client.discordTogether = new DiscordTogether(client);
client.commands = new Collection();
client.slash = new Collection();
client.aliases = new Collection();
client.categories = fs.readdirSync("./Commands/");
client.setMaxListeners(0);
const Cookie = YT_COOKIE;
client.logger = Logger;
client.utils = Util;
client.say = Embeds;
const player = new Player(client, {
    leaveOnEnd: true,
    leaveOnStop: true,
    leaveOnEmpty: false,
    leaveOnEmptyCooldown: 60000,
    autoSelfDeaf: true,
    initialVolume: 130,
    ytdlDownloadOptions: {
        requestOptions: {
            headers: {
                cookie: Cookie,
            }
        }
    },
})

player.use("YOUTUBE_DL", require("@discord-player/downloader").Downloader);
client.player = player;
client.db = new Enmap({ name: "musicdb" });

loadCommands(client);
loadEvents(client);
loadPlayerEvents(client);
loadSlashCommands(client);
checkValid();

// Error Handling

process.on("uncaughtException", (err) => {
    console.log("Uncaught Exception: " + err);

    const exceptionembed = new MessageEmbed()
        .setTitle("Uncaught Exception")
        .setDescription(`${err}`)
        .setColor("RED")
    client.channels.cache.get(ERROR_LOGS_CHANNEL).send({ embeds: [exceptionembed] })
});

process.on("unhandledRejection", (reason, promise) => {
    console.log(
        "[FATAL] Possibly Unhandled Rejection at: Promise ",
        promise,
        " reason: ",
        reason.message
    );

    const rejectionembed = new MessageEmbed()
        .setTitle("Unhandled Promise Rejection")
        .addField("Promise", `${promise}`)
        .addField("Reason", `${reason.message}`)
        .setColor("RED")
    client.channels.cache.get(ERROR_LOGS_CHANNEL).send({ embeds: [rejectionembed] })
});

client.login('key').then(() => {
    console.log(
        chalk.bgBlueBright.black(
            ` Successfully logged in as: ${client.user.username}#${client.user.discriminator} `
        )
    );
});```

Loading Images in Phaser and Node js

Im am trying to load images in phaser with node js and i always get the same error

:3000/assets/img/feet/idle/survivor-idle_0.png:1 Failed to load resource: the server responded with a status of 404 (Not Found)

if you know a way to get this to work please tell me. here is my code:

preload() {
        // Used for preloading assets into your scene
        
        //Idle feet image
        this.load.image('idleFeetFrame', '/assets/img/feet/idle/survivor-idle_0.png');
}

Trying use react slot machine cause: Support for the experimental syntax ‘jsx’ isn’t currently enabled error

I am trying to use slot machine in react but when I try use this I get an following error:

./node_modules/react-slot-machine-gen/src/react-slot-machine.js
SyntaxError: C:Projectnode_modulesreact-slot-machine-gensrcreact-slot-machine.js: Support for the experimental syntax 'jsx' isn't currently enabled (38:7):

  36 |   render() {
  37 |     return (
> 38 |       <div id={this.props.id} className="slot-machine" ref="wrapper"></div>
     |       ^
  39 |     );
  40 |   }
  41 | };

Add @babel/preset-react (https://git.io/JfeDR) to the 'presets' section of your Babel config to enable transformation.
If you want to leave it as-is, add @babel/plugin-syntax-jsx (https://git.io/vb4yA) to the 'plugins' section to enable parsing.

And simple react code

import SlotMachine from "react-slot-machine-gen";

<div className={styles.page_container}>
        <SlotMachine reels={reels} play={play}/>
        <input type="text"/>
        <button onClick={() => {
            setPlay(true);
        }}>Play
        </button>
    </div>

Information above does not solve this problem.
Thank you, any help will be appreciated

What is the alternative method of ‘window.external’ in VB Script?

I used the WebBrowser control to add existing Web application written by VB Script code to my Windows Forms client applications.

But, I have some problem. I have to communicate between Web application and Windows Forms applications. I already found similar function in Javascript. ‘window.external’.
I’m looking for the alternative method of ‘window.external’ in VB Script.

please check the following code. how to implement to execute windows Forms Application methods in VB Script?

<script language="vbscript" type="text/vbscript">
   Sub callForm2()
      window.external.ShowMessage("from vbscript")
   End Sub
</script
public class ScriptManager
{
   private Form _form = null;
   public ScriptManager(Form1 form)
   {
      _form = form;
   }


   public void ShowMessage(object msg)
   {
      MessageBox.Show(msg.ToString());
   }
}

Hot to fix “Type ‘string’ is not assignable to type ‘T'”?

Here’s the code with error:

    let createArray = function<T>(length: number, value: T): T[] {
        let result: T[] = [];
        for (let i = 0; i < length; i++) {
            if (typeof value === 'string') {
                result[i] = value + '_' + i;  // Type 'string' is not assignable to type 'T'. 'T' could be instantiated with an arbitrary type which could be unrelated to 'string'.
            } else {
                result[i] = value;
            }
            
        }
        return result;
    }
    
    createArray(3, 'x');

I have no idea why Typescript can not recognize the Generics T as string in this case.

How can I fix it?

estoy intentando hacer un embed basico para un bot de discord [closed]

estoy intentando hacer un embed basico para un bot de discord este es el siguiente codigo

client.on("message", (message) =>{
   if(message.author.bot) return;
   if (!message.content.startsWith(prefix)) return;
//comandos
   const args = message.content.slice(prefix.length).trim().split(/ +/g)
   const command = args.shift().toLowerCase();
//embeds
if(command === 'embed'){
 const embed = new Discord.MessageEmbed()
   .setTitle('Infomacion del servidor');
 message.channel.send(embed);
}
});
client.login(config.token);

error:

DiscordAPIError: Cannot send an empty message
at RequestHandler.execute (C:UsersChinuDesktopbotdsGolden-botnode_modulesdiscord.jssrcrestRequestHandler.js:350:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (C:UsersChinuDesktopbotdsGolden-botnode_modulesdiscord.jssrcrestRequestHandler.js:51:14)
at async TextChannel.send (C:UsersChinuDesktopbotdsGolden-botnode_modulesdiscord.jssrcstructuresinterfacesTextBasedChannel.js:175:15) {

method: ‘post’,
path: ‘/channels/929202157410988113/messages’,
code: 50006,

JavaScript: does reassigning a variable declared by `let` change the memory location of that variable?

I have a variable foo which has the value of string foo

let foo = 'foo'

let’s say the variable foo is loaded at the memory address 100000f91. Does this re-assignment

  1. change its memory address, let’s say from 100000f91 to 100000f92?
  2. only rewrite the content/data at the address 100000f91?
foo = bar

What about changing it to a different type? does this change the answer?

foo = 123

Comparing data from JSON and input.value

I am working on small shopping cart project. I have products in JSON.file, also I have input for finding price of products.
I am using class method
question is: this are strings or numbers? -> (3) [’35’, ’35’, ’35’]


searchItem(data) {
    let that = this

    searchBtn.addEventListener('click', function(e) {
      
       const input = document.querySelector('.input').value

           
       const findItem = data.filter(function(item) {
          if(item.price === input) {
            return item
          }
        })   // this return all data of product so I filtered only prices bellow


        const getItem = findItem.map(item => {
          return item.price
        })                      
 
       // this give:    (3) ['35', '35', '35']  


    
         if(input === getItem) {     
             console.log('same') 
        } else {
          console.log('try it again') 
        }
                         
         // this cond. show me :  console.log('try it again')
         // HOW TO GET:   console.log('same')  
      
       e.preventDefault()
    })


Load image from URL and upload to media library in Strapi

I’m building a CSV importer for my Strapi application and one of its task is to read an image URL from a cell and download it from the URL and save it to media library.

The code looks like this:

const request = require('request').defaults({ encoding: null });

request.get(src, function (err, res, body) {
    const fileName = src.split('/').pop();

    strapi.plugins.upload.services.upload.upload({
        files: {
            path: body,
            name: fileName,
            type: res.headers['content-type'],
            size: Number(res.headers['content-length']),
        },
        data: {
            ref: 'products',
            refId: data.itemID,
            field: 'images'
        }
    });
});

The download works and I get a Buffer in the body variable of the request.get callback. But passing this to strapi.plugins.upload.services.upload.upload give me the following error:

UnhandledPromiseRejectionWarning: TypeError [ERR_INVALID_ARG_VALUE]: The argument 'path' must be a string or Uint8Array without null bytes. Received <Buffer ff d8 ff e1 10 c1 45 78 69 66 00 00 49 49 2a 00 08 00 00 00 0f 00 00 01 03 00 01 00 00 00 6c 05 00 00 01 01 03 00 01 00 ...

I already tried to replace path: body, with path: new Uint8Array(body), but without no luck.

Any idea what I do wrong here?

Thanks for your help!

Trying to understand the differences across these promises and setTimeouts [duplicate]

I’m learning about promises, setTimeout and async calls and have done a great job of confusing myself. I think I’m lacking some understanding around the callback and how setTimeout works. I’ve been looking at Mozilla documentation and the various Stackoverflow posts regarding these topics. I’m still having some trouble wrapping my head around why some of the functions I’ve created behave the way they do regarding the timeouts that are set.

Between wait0 and wait1 I don’t understand why the timeout for wait0 works properly and wait1 doesn’t adhere to it. With wait2 it is like wait1 except wrapped in an arrow function expression. Why does that make the timeout work properly? wait3 isn’t actually using the callback so that makes sense why the promise and then functions don’t do anything. But it stops wait4 from running. Is it blocking progression indefinitely or actually ending execution? For wait4 I’m also not passing a value into the callback like with wait0 but the timeout isn’t being adhered to.

function wait0() {
    return new Promise((resolve, failure)=>{
    setTimeout(resolve, 2000);
  });
}

function wait1() {
    return new Promise((resolve, failure)=>{
    setTimeout(resolve('resolved ' + new Date().toGMTString()), 2000);
  });
}

function wait2() {
    return new Promise((resolve, failure)=>{
    setTimeout(()=>{
        resolve('resolved ' + new Date().toGMTString());
    }, 2000);
  });
}

function wait3() {
    return new Promise((resolve, failure)=>{
    setTimeout(()=>{}, 2000);
  });
}

function wait4() {
    return new Promise((resolve, failure)=>{
    setTimeout(resolve(), 2000);
  });
}

async function test() {
  await wait0().then((result)=>console.log(result)); // Works as expected
  console.log(new Date().toGMTString());
    await wait1().then((result)=>console.log(result)); // Doesn't adhere to timeout
  console.log(new Date().toGMTString());
  await wait2().then((result)=>console.log(result)); // Works as expected
  console.log(new Date().toGMTString());
  await wait3().then((result)=>console.log(result)); // Never resolves
  console.log(new Date().toGMTString());
  await wait4().then((result)=>console.log(result)); // Doesn't adhere to timeout
  console.log(new Date().toGMTString());
}


test();

How to iterate through and modify each element

I have a readSourceList that I need to iterate through and modify the name with the word “bill” in front of them. Would I be able to do that within this function?:

DataExplorerUI.prototype.consumptionResponse = function (data) {
    var self = this;
    console.log(self.readerSourceList);
    $.each(data, function () {
        this.key = Enumerable.from(self.readerSourceList).first("$.f == " + this.key).name;
        $.each(this.values, function () {
            this.x = getUTCTimeInUserTimeZone(this.x);
        });
    });
};

Thanks

I’m trying to create and advanced command handler and I’m getting the error ‘CLIENT_MISSING_INTENTS’ and I feel like I’ve written the code perfectly

So I’m trying to branch off from a basic command line to an advanced command handler where the commands will call the command from a different file. I’ve been following videos and guides and I feel like there should be no issues and I also don’t have any errors within VSC. But after starting the discord bot and I inputted the node . command and got the error [Symbol(code)]: ‘CLIENT_MISSING_INTENTS’. This is my current code


    const client = new Discord.Client();

    const prefix = '-'

    const fs = require('fs');

    client.commands = new Discord.Collection();

    const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));
    for(const file of commandFiles){
        const command = require(`./commands/${file}`);

        client.commands.set(command.name, command);
    }


    client.once('ready', () => {
        console.log('You are connected to Weekly Releases!');
    });

    client.on('messageCreate', message => {
        if(!message.content.startsWith(prefix) || message.author.bot) return;

        const args = message.content.slice(prefix.length).split(/ +/);
        const command = args.shift().toLowerCase();

        if(command === 'ping'){
            client.commands.get('ping').execute(message, args);

        } else if (command == 'youtube'){

        }
    });

    client.login```
and I don't know where to look for the issue. Any tips and tricks will help.