Class properties inaccessible in listener function / “this” rebound when passing class member function as listener [duplicate]

I have been working on a discord bot which handles message events with a CommandManager class I wrote.
This class has an async member function messageEvent which processes all incoming messages.
To register this function as a message listener, I pass it to the discord client using client.on('messageCreate', command_manager.messageEvent).
However when I try to use class properties inside that function (e.g. this.guild of the Command Manager, set at construction), they are undefined.

What is going on here?
Why can I not use the objects properties even though they are defined well before the function is even passed as a listener?

How to fill this jagged array?

When outside of the function scope, Tiles[[]] loses all of it’s values.

var Tiles= [[]];
function drawGrid(){
    Grid=true;
    // for the amout of rows
    for (let rowcount = 0; rowcount < amountOfrows; rowcount++) {
        ctxB.lineWidth = 1;
        
        // filling the rows
        // check for (un)even
        if(rowcount%2==0){
            for (let boxcount = 0; boxcount < amountOfHorBoxes; boxcount++) {
                ctxB.strokeStyle = "black";
                ctxB.fillStyle = "white";
                ctxB.beginPath();
                ctxB.rect(addHorBox, addVertBox, boxsize, boxsize);
                ctxB.fill();
                ctxB.closePath();
                ctxB.stroke();
                Tiles[rowcount[boxcount]]={x1: addHorBox, y1: boxsize*rowcount, x2: addHorBox+boxsize, y2: boxsize*(rowcount+1)};
                //console.log('Tiles:',Tiles[rowcount[boxcount]]);
                
                addHorBox+=boxsize;
            }
        }else{
            for (let boxcount = 0; boxcount < amountOfHorBoxes; boxcount++) {
                ctxB.strokeStyle = "black";
                ctxB.fillStyle = "white";
                ctxB.beginPath();
                ctxB.rect(addHorBox+boxsize/2, addVertBox, boxsize, boxsize);
                ctxB.fill();
                ctxB.closePath();
                ctxB.stroke(); 
                Tiles[rowcount[boxcount]]={x1: addHorBox, y1: boxsize*rowcount, x2: addHorBox+boxsize, y2: boxsize*(rowcount+1)};
                //console.log('Tiles:',Tiles[rowcount[boxcount]]);

                addHorBox+=boxsize;
            }
        }
        addHorBox=0;
        addVertBox+=boxsize;
    }
}

I haven’t fully been able to check if I fill up the array properly, but regardless, it doesn’t hold the values outside of it’s scope. How do I do this?

How to import a variable from a js file

I want to import a array from a js file and it doesn’t work.
My code :

import * as dollarsValue from './index.js';
function intiualAdaptedVal(arr1, arr2, arrCid) { // arr1 => changeArr ; arr2 => dollarsValue
    let num;
    for (let i = 0; i < arr2.length; i++) {
        num = getNumber(arr2, arr2[i][1]) / arrCid[i][1];
        arr1[i].push(num.toFixed(2));
    }
    return arr1;
}
console.log(intiualAdaptedVal(changeArr, dollarsValue, cid))

But it doesn’t work:

enter image description here

Thanks you

electron.js desktop app made with python as a back-end does not RUN ON any other pc than mine

so i have recently made a CRUD software with python to connect to xampp database, but once i compile and distribute it, it run on my computer perfectly but when i share the setup file with another computer, it install properly but when you run the software, it shows the blue circle for 1-2 s and nothing opens.

Is there a problem with the SQL server or……

I am New to to develop an electron app, so guys go easy on me.

below if my package.json:

  "name": "nyota",
  "version": "1.0.0",
  "description": "",
  "main": "./web interface/main.js",
  "build": {
    "appId": "nyota"
  },
  "scripts": {
    "start": "electron-forge start",
    "watch": "nodemon --exec electron .",
    "package": "electron-forge package",
    "make": "electron-forge make",
    "dist": "electron-builder"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "electron": "^19.0.1",
    "electron-builder": "^23.0.3"
  },
  "dependencies": {
    "path": "^0.12.7",
    "request": "^2.88.2",
    "request-promise": "^4.2.6"
  }
}

Problem with inserting JS code into Electron

I just started studying Electron just a couple of weeks ago and I had a problem, I’m trying to get my old works written in javascript and it just doesn’t work, I don’t know how to connect it correctly, yes, most likely it’s easy, but for me As a beginner this is quite difficult. Thanks in advance for your time.

Index.html

<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="Content-Security-Policy" content="script-src 'self'"
    <title></title>
  </head>
  <body>
    Check
  </body>
  <script>require('chess.js') </script>
</html>

index.js

import { app, BrowserWindow } from 'electron';




if (require('electron-squirrel-startup') ){ 
  app.quit();
}

const chess = require('./chess')



let mainWindow;

const createWindow = () => {
  // Create the browser window.
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    minWidth: 500,
    minHeight: 200,
    icon: __dirname + "/icon.iso",
    webPreferences: { 
      nodeIntegration: false,
    },
  });
 


  mainWindow.loadURL(`file://${__dirname}/index.html`);




  mainWindow.on('closed', () => {

    mainWindow = null;
  });
};


app.on('ready', createWindow);

// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // On OS X it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {

  if (mainWindow === null) {
    createWindow();
  }
});

chess.js

pimg=new Array();
   i=new Array (
    "b",
    "bb1","bb2","bb3","bb4","bb5","bb6",
    "bw1","bw2","bw3","bw4","bw5","bw6",
    "l","r",
    "sbb1","sbb2","sbb3","sbb4","sbb5","sbb6",
    "sbw1","sbw2","sbw3","sbw4","sbw5","sbw6",
    "swb1","swb2","swb3","swb4","swb5","swb6",
    "sww1","sww2","sww3","sww4","sww5","sww6",
    "t","u","w",
    "wb1","wb2","wb3","wb4","wb5","wb6",
    "ww1","ww2","ww3","ww4","ww5","ww6"
   );
   for (j=0;j<i.length;++j) {
    pimg[j]=new Image();
    pimg[j].src=""+i[j]+".png";
   }
  
   N=1;
   K="";
   F=px=py=0;
  
   function sm(i) {
    if (N>120) return;
    var j="abcdefgh";
    if (N&1) { 
     if (N<19) K+=" ";
     K+=(1+N>>1)+". ";
    }
    else K+="   ";
    if (i.f==3) K+="o-o  ";
    else if(i.f==5) K+="o-o-o";
    else K+=j.charAt(i.x)+(8-i.y)+" "+j.charAt(i.X)+(8-i.Y);
    if (++N&1) K+="n";
    document.getElementById("m"+Math.floor((N-2)/20)).innerHTML="<pre>"+K+"</pre>";
    if (!((N-1)%20)) K="";
   }
  
   function un(u,b) {
    for (var i=u.x.length-1;i>=0;--i) Z(b,u.x[i],u.y[i],u.p[i]);
   }
  
   function au(u,b,x,y) { 
    u.x.push(x); u.y.push(y); u.p.push(b[x+y*8]);
   }
  
   function st(x) {
    document.getElementById("i").innerHTML=x;
   }
   
   function P(x,y,X,Y,f) {
    this.x=x; this.y=y; this.X=X; this.Y=Y; this.f=f;
   }
  
   function U() { 
    this.x=[]; this.y=[]; this.p=[];
   }
  
   function em(b,x,y) {
    return !b[x+y*8];
   }
  
   function ge(b,x,y) {
    return b[x+y*8]&7;
   }
  
   function co(b,x,y) {
    return b[x+y*8]&192;
   }
  
   function sa(b,x,y,c) {
    var i=b[x+y*8]; return i&&(i&c);
   }
  
   function op(b,x,y,c){
    var i=b[x+y*8]; return i&&!(i&c);
   }
  
   function mo(b,x,y) {
    var i=b[x+y*8]; return i&&(i&32);
   }
   
   function la(b,x,y){
    var i=b[x+y*8]; return i&&(i&16);
   }
  
   function ra(x,y) {
    return x>=0&&x<8&&y>=0&&y<8;
   }
  
   function di(c) {
    return c==64?-1:1;
   }
  
   function Z(b,x,y,p) {
    b[x+y*8]=p; return b;
   }
   
   function t(b,x,y,i,j,c,l) {
    var X=x; var Y=y;
    while (ra(X+=i,Y+=j)&&em(b,X,Y)) l.push(new P(x,y,X,Y,0));
    if (ra(X,Y)&&op(b,X,Y,c)) l.push (new P(x,y,X,Y,0));
    return l;
   }
  
   function ro(b,x,y,c,l) {
    t(b,x,y,1,0,c,t(b,x,y,-1,0,c,t(b,x,y,0,1,c,t(b,x,y,0,-1,c,l))));
   }
  
   function bi(b,x,y,c,l) {
    t(b,x,y,1,1,c,t(b,x,y,-1,-1,c,t(b,x,y,1,-1,c,t(b,x,y,-1,1,c,l))));
   }
  
   function ki(b,x,y,c,l) {
    for(var i=-1;i<2;++i) 
    for(var j=-1;j<2;++j) {
     var X=x+i; var Y=y+j;
     if ((X||Y)&&ra(X,Y)&&!sa(b,X,Y,c)) l.push (new P(x,y,X,Y,0));
    }
    if (!mo(b,x,y)) if (em(b,5,y)&&em(b,6,y)&&!em(b,7,y)&&!mo(b,7,y)) {
     var u=new U();
     au(u,b,x,y);
     Z(b,x,y,0);
     var i=fi(b,c^192);
     var j=0; var X=-1;
     while (!j&&++X!=i.length) j=i[X].Y==y&&i[X].X==5;
     if(!j)l.push(new P(x,y,6,y,3));
     un(u,b);
    }
    else if(em(b,3,y)&&em(b,2,y)&&em(b,1,y)&&!em(b,0,y)&&!mo(b,0,y)) {
     var u=new U(); au(u,b,x,y); Z(b,x,y,0);
     var i=fi(b,c^192);
     var j=0; var X=-1;
     while (!j&&++X!=i.length) j=i[X].Y==y&&i[X].X==3;
     if (!j) l.push (new P(x,y,2,y,5));
     un(u,b);
    }
   }
   
   function kn(b,x,y,c,l) {
    for (var i=-2;i<3;++i)
    for (var j=-2;j<3;++j)
    if (Math.abs(i)+Math.abs(j)==3) {
     var X=x+i; var Y=y+j;
     if (ra(X,Y)&&!sa(b,X,Y,c)) l.push(new P(x,y,X,Y,0));
    }
   }
  
   function pa(b,x,y,c,l) {
    var Y=y+di(c); var Z=y+di(c)*2;
    if (!mo(b,x,y)&&em(b,x,Y)&&em(b,x,Z)) l.push(new P(x,y,x,Z,2));
    if (em(b,x,Y)) {
     if (!Y||Y==7) l.push(new P(x,y,x,Y,4));
     else l.push (new P(x,y,x,Y,0));
    }
    for (var i=-1;i<2;i+=2) {
     var X=x+i;if(ra(X,Y)) {
      if(op(b,X,Y,c)) {
       if (!Y||Y==7) l.push (new P(x,y,X,Y,4));
       else l.push (new P(x,y,X,Y,0));
      }
      else if (em(b,X,Y)&&la(b,X,Y-di(c))) l.push(new P(x,y,X,Y,1));
     }
    }
   }
  
   function d(b) {
    for (var y=0;y<8;++y)
    for(var x=0;x<8;++x) {
     var i="<img src="";
     if (F==1&&x==px&&y==py) i+="s"; i+=(x+y&1)?"b":"w";
     if (!em(b,x,y)) i+=(sa(b,x,y,64)?"w":"b")+(ge(b,x,y)&7);
     document.getElementById(""+x+y).innerHTML=i+".png">";
    }
   }
  
   function ma(b,m) {
    u=new U();
    for (var x=0;x<8;++x)
    for (var y=0;y<8;++y)
    if (la(b,x,y)) {
     au(u,b,x,y); Z(b,x,y,ge(b,x,y)|co(b,x,y)|mo(b,x,y));
    }
    au(u,b,m.X,m.Y);
    if (m.f==4) Z(b,m.X,m.Y,37|co(b,m.x,m.y));
    else Z(b,m.X,m.Y,ge(b,m.x,m.y)|co(b,m.x,m.y)|32|(m.f==2?16:0));
    au(u,b,m.x,m.y);
    Z(b,m.x,m.y,0);
    if (m.f==1) { 
     au (u,b,m.X,m.Y-di(c));
     Z (b,m.X,m.Y-di(c),0);
    }
    else if(m.f==3) {
     au(u,b,5,m.y); au(u,b,7,m.y); Z(Z(b,5,m.y,ge(b,7,m.y)|co(b,7,m.y)|32),7,m.y,0);
    }
    else if(m.f==5) {
     au(u,b,3,m.y);au(u,b,0,m.y);Z(Z(b,3,m.y,ge(b,0,m.y)|co(b,0,m.y)|32),0,m.y,0);
    }
    return u;
   }
  
   function fi(b,c) { 
    var l=[];
    for (var x=0;x<8;++x)
    for (var y=0;y<8;++y)
    if (sa(b,x,y,c)) {
     var i=ge(b,x,y);
     if (i==1) pa(b,x,y,c,l);
     else if(i==2) kn(b,x,y,c,l);
     else if(i==3) bi(b,x,y,c,l);
     else if(i==4) ro(b,x,y,c,l);
     else if(i==5) {
      bi(b,x,y,c,l); ro(b,x,y,c,l)
     }
     else if(i==6) ki(b,x,y,c,l);
    }
    for (var i=0;i<l.length/3;++i) {
     var j=Math.floor(Math.random()*l.length);
     var k=Math.floor(Math.random()*l.length);
     var x=l[j];l[j]=l[k];l[k]=x;
    }
    return l;
   }
  
   var Sp=[0,60,370,370,450,1000,5000];
   var Sb=[
    [0,0,0,0,0,0,0,0,2,3,4,0,0,4,3,2,4,6,12,12,12,4,6,4,4,7,18,25,25,16,7,4,6,11,
    18,27,27,16,11,6,10,15,24,32,32,24,15,10,10,15,24,32,32,24,15,10,0,0,0,0,0,0,0,0],
    [-7,-3,1,3,3,1,-3,-7,2,6,14,20,20,14,6,2,6,14,22,26,26,22,14,6,8,18,26,30,30,26,18,
    8,8,18,30,32,32,30,18,8,6,14,28,32,32,28,14,6,2,6,14,20,20,14,6,2,-7,-3,1,3,3,1,-3,-7],
    [16,16,16,16,16,16,16,16,26,29,31,31,31,31,29,26,26,28,32,32,32,32,28,26,16,26,32,32,32,
    32,26,16,16,26,32,32,32,32,26,16,16,28,32,32,32,32,28,16,16,29,31,31,31,31,29,16,16,16,16,16,16,16,16,16],
    [0,0,0,3,3,0,0,0,-2,0,0,0,0,0,0,-2,-2,0,0,0,0,0,0,-2,-2,0,0,0,0,0,0,-2,-2,0,0,0,0,0,0,-2,
    -2,0,0,0,0,0,0,-2,10,10,10,10,10,10,10,10,0,0,0,0,0,0,0,0],
    [-2,-2,-2,0,0,-2,-2,-2,0,0,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0,0,0,
    2,2,0,0,0,0,0,0,2,2,0,0,0,-2,-2,0,0,0,0,0,0,-2,-2,0,0,0,0,0,0,-2,-2,0,0,0,0,0,0],
    [3,3,8,-12,-8,-12,10,5,0,0,-5,-5,-12,-12,-12,-12,-5,-5,-7,-15,-15,-15,-15,-15,-15,
    -7,-20,-20,-20,-20,-20,-20,-20,-20,-20,-20,-20,-20,-20,-20,-20,-20,-20,-20,-20,-20,
    -20,-20,-20,-20,-20,-20,-20,-20,-20,-20,-20,-20,-20,-20,-20,-20,-20,-20,-20,-20],[]];
   for (var x=0;x<8;++x)
   for(var y=0;y<8;++y) Sb[6][x+y*8]=Sb[5][(7-x)+y*8];
  
   function sc(b,c) {
    var s=0;
    for (var x=0;x<8;++x)
    for(var y=0;y<8;++y) {
     var i=ge(b,x,y);
     if (i) if (sa(b,x,y,128)) s+=Sb[i==6?6:i-1][(7-x)+y*8]+Sp[i];
     else s-=Sb[i-1][x+(7-y)*8]+Sp[i];
    }
    return c==128?s:-s;
   }
  
   function cpu() {
    if(F!=2) return;
    var now = new Date();
    var m=fi(b,c); var bs=-99999; var ws=bs; var bm=0; var C=c^192; var kx=0; var ky=0;
    for (var i=0;i<m.length;++i) {
     var u=ma(b,m[i]);
     if (ge(b,kx,ky)!=6||sa(b,kx,ky,C)) {
      kx=ky=0;
      while (ge(b,kx,ky)!=6||sa(b,kx,ky,C)) if (++kx==8) { kx=0; ++ky; }
     }
     var om=fi(b,C); var obs=-99999; var ows=99999;
     for (var j=0;j<om.length;++j) {
      if (kx==om[j].X&&ky==om[j].Y) {
       obs=-99999; break;
      }
      var U=ma(b,om[j]); var r=sc(b,c);
      un(U,b); obs=Math.max(obs,r); ows=Math.min(ows,r);
      if (r<ws) break;
     }
     un(u,b);
     if (obs>bs&&ows>ws) {
      bs=obs; ws=ows; bm=m[i];
     }
    }
    ma(b,bm); sm(bm); nx(); st("����� �� ��� "+(new Date()-now)/1000+" ���.");
   }
  
   cpw=0; cpb=1;
  
   function pw(e) {
    cpw=e.checked;
    if (F<2&&cpw&&c==64) {
     F=2; setTimeout("cpu()",100);
    }
   }
  
   function pb(e) {
    cpb=e.checked;
    if (F<2&&cpb&&c==128) {
     F=2; setTimeout("cpu()",100);
    }
   }
  
   function l() { 
    b=[];
    for (i=0;i<8;++i) Z(Z(b,i,6,65),i,1,129);
    d(Z(Z(Z(Z(Z(Z(Z(Z(Z(Z(Z(Z(Z(Z(Z(Z(b,0,0,132),1,0,130),2,0,131),3,0,133),4,0,134),
     5,0,131),6,0,130),7,0,132),0,7,68),1,7,66),2,7,67),3,7,69),4,7,70),5,7,67),6,7,66),7,7,68));
    c=64;
   }
  
   function hu(x,y) { 
    if (F==0) {
     if (sa(b,x,y,c)) {
      px=x; py=y; F=1; d(b);
     }
    }
    else if(F==1) {
     if (x==px&&y==py) {
      F=0; d(b); return;
     }
     var m=fi(b,c);
     for (var i=0;i<m.length;++i) { 
      if (m[i].x==px&&m[i].y==py&&m[i].X==x&&m[i].Y==y&&ge(b,x,y)!=6) {
       var u=ma(b,m[i]); var o=fi(b,c^192);
       for (var j=0;j<o.length;++j) if (ge(b,o[j].X,o[j].Y)==6&&sa(b,o[j].X,o[j].Y,c)) {
        un(u,b); st("�������� ���!"); return;
       }
       sm(m[i]); nx(); return;
      }
     }
     st("�������� ���!");
    }
   }
  
   function nx() {
    c^=192; F=0; d(b);
    for (var x=0;x<8;++x)
    for (var y=0;y<8;++y)
    if (ge(b,x,y)==6 && sa(b,x,y,c)) {
     var kx=x; var ky=y;
    }
    var m=fi(b,c^192); var ic=0;
    for (var i=0;i<m.length;++i) if(m[i].X==kx&&m[i].Y==ky) ic=1;
    var m=fi(b,c); var cm=1;
    for (var i=0;i<m.length;++i) {
     var u=ma(b,m[i]);
     for (var x=0;x<8;++x) 
     for(var y=0;y<8;++y) 
     if (ge(b,x,y)==6&&sa(b,x,y,c)) {
      var kx=x; var ky=y;
     }
     var om=fi(b,c^192); un(u,b); var hm=0;
     for (var j=0;j<om.length;++j) if (om[j].X==kx&&om[j].Y==ky) hm=1; cm&=hm;
    }
    if (cm) {
     alert(ic?"���!":"���!"); F=3; return;
    }
    if ((cpw&&c==64)||(cpb&&c==128)) {
     F=2; setTimeout("cpu()",500);
    }
   }
  
  
  // SecondOne__-----------------------------------------------------------------------
  
   for (var i=0;i<8;++i) {
   document.write("<img src="l.png">");
   for (var j=0;j<8;++j) document.write("<span onclick="hu("+j+","+i+")" id=""+j+i+""><img></span>");
   document.write("<img src="r.png"><br>");
  }

Character ‘#’ in web url returns location.search empty

Background:

I have recently published my angular project on namecheap hosting. Due to routing issues, I have enabled useHash = true while exporting my app-routing.ts file.

export const appRoutingModule = RouterModule.forRoot(routes,{ enableTracing: false, useHash: true});

Since, my routing issues resolved, however in all my URL’s I got #.

Issue:

At one point in my code, I access the URL and analyze the URL, if there is already a search query parameter I append the new one with & symbol or if there is not then I add the search query with ? sign.

        var uid = this.route.snapshot;
        var searchURL = "";
        
     
        alert("Checking search:: " + window.location.search); // returns empty
        alert("One more time:: " + new URLSearchParams(location.search)); // returns empty 
        if (new URL(window.location.href).search == "")
        {
          searchURL = "?"+incomingSearch;
        }
        else 
        {
          searchURL = new URL(window.location.href).search + "&" + incomingSearch;
        }
       
        this.location.replaceState( uid.routeConfig.path+ searchURL);

If my url is like

http://localhost:4200/#/women?occasion=cozy

The window.location.search returns empty

If I remove # from my URL I received the data

http://localhost:4200/women?occasion=cozy

The window.location.search returns ‘?occasion=cozy’

Any help is appreciated. I have looked at this question as well but $window.location.search gives error though I have installed jquery.

stuck on how to make searching work in dynamic table in reactjs

I have been working on a practice mini project with ReactJS of displaying a dynamic table with a mock API which should have sorting and searching as its functionality, I am stuck on how to search the data from the API and display only those rows of the table which matches any one column value of a row.
here’s the code:

import React, { useCallback } from 'react';
import {useState, useEffect} from 'react'
import './App.css';
import Header from './components/Header.js'
import Table from './components/Table.js'
import Footer from './components/Footer.js'

function App() {

  const [userData, setuserData] = useState([])
  const [keys, setKeys] = useState([])
  const [search, setSearch]= useState('')
  const [filter, setFilter]=useState([])

  const handleChange = (e)=>{
    e.preventDefault()
    setSearch(e.target.value.toLowerCase())
    setFilter(searchTable(userData))
  }



  function searchTable(rows){
        if(!search) return rows
        console.log(rows.map(row=>row.id), rows.map(row=>row.name))
        return rows.filter(row => {return Object.keys(row)===search})
    }



  const getData = async (callback)=>
  {
    await fetch('https://gorest.co.in/public/v1/users')
    .then((response)=>
    {
      if(!response.ok) throw new Error('Http Error: ', response.status)
      return response.json()
    })
    .then((response)=>
    {
      callback(response);
      return response;
    })
    .finally(console.log('successfully fetched!'));
  }

  useEffect(()=>
  { 
    getData((response)=>
    {
      setuserData(response.data)
      setFilter(response.data)
      // console.log(response.data)
      setKeys(Object.keys(response.data[0]).map((key) => key));
    })
  }, [search])

  return (
    <div className="App">
       <h1>Users</h1>
      <input type="text" placeholder='search' onChange={handleChange} value={search}/>
      <Table userData={filter} keys={keys}/>
      <Footer />

    </div>
  );
}

export default App;

Apart from this, Table and Footer Component are just to display the received data.
I have tried multiple ways but cannot get around how to display it dynamically

Mongoose how to count unique days in a month?

i am working on a problem where in my database there supposed to be multiple entries from day to day.
each entry includes a timestamp. the problem is im supposed to find how many days in each month a data has been entered.
ex: if a user sends a message every 2 days in may. my answer would be: “the user used the message function for 15 days in may”.
now if the user sends 5 messages every 2 days in may. the answer would be still 15. im only counting the days the user has been using the app.

using this query:

model.find({ 
    date: {
        $gte: new Date(startOfMonth), 
        $lt: new Date(endOfMonth)
    }
})

i was able to find all data entries on a specific month.
the data may look like something like this:

 Date: dd/mm/yy        Message:
 1/5/2022              "Hello"
 1/5/2022              "World"
 1/5/2022              "!"
 5/5/2022              "Hello World!"
 8/5/2022              "Hello World!"

the desired answer would be 3 unique days in may.

How do i achieve this using mongodb? the simplest answer that come to mind is to use additional queries to group by unique days, but i have no idea how to do that using mongo provided i need to access the date.

Cesium ScreenSpaceEventType LEFT_DOWN trigger LEFT_CLICK

i am trying to trigger Cesium ScreenSpaceEventType LEFT_DOWN but when i click on a point it triggers Cesium ScreenSpaceEventType LEFT_DOWN and Cesium ScreenSpaceEventType LEFT_UP.
i want to drag points. but right now when i click on a point and move mouse that point also moves along with mouse.

can i disable click untill some condiition is satisfied or any way i can improve it
can some one guide me please.

code : sandcastle click here

const viewer = new Cesium.Viewer("cesiumContainer");

var Poly_pointsCollections = [];
var scene = viewer.scene;
var Poly_coordiantesArray = [
  [
    72.35433701166211, 52.57522385967319, 96.18442795152974,
    44.89719893727921, 72.39011732046649, 39.86453159141635,
  ],
  [
    67.29773654341213, 32.88259716109294, 69.14234015976554,
    32.98282610463128, 69.19404079866142, 31.354623867578226,
    66.85127436871454, 31.712787322338162,
  ],
];

var Poly_nameArray = "straightLine_";

// initial polygons
for (var i = 0; i < 2; i++) {
    var temp=Poly_coordiantesArray[i];
    for (var j = 0; j < temp.length; j = j + 2) {
      draw_Zone_Corner_points(
        temp[j],
        temp[j + 1],
        0
      );
    }
}


function draw_Zone_Corner_points(lon, lat, name) {

var pointGeometry = viewer.entities.add({
  name: "straightLinePoint_",
  description: [lon, lat],
  position: Cesium.Cartesian3.fromDegrees(lon, lat),
  point: {
    color: Cesium.Color.SKYBLUE,
    pixelSize: 10,
    outlineColor: Cesium.Color.YELLOW,
    outlineWidth: 3,
    disableDepthTestDistance: Number.POSITIVE_INFINITY, // we can see points arounds earth
    //heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
  },
});
Poly_pointsCollections.push(pointGeometry);

}

var ZoneMoment = true;

// function update() {}
document
.getElementById("cesiumContainer")
.addEventListener("click", function () {
  if (ZoneMoment) {
    var rightEntityPicked = false;
    var dragging = false;
    var pickedEntity;
    var mouseDroped = false;
    var handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
    handler.setInputAction(function (click) {
      if (ZoneMoment) {
        console.log("LEFT down ");
        var pickedObject = scene.pick(click.position);
        if (Cesium.defined(pickedObject) && pickedObject.id) {
          var entityName = pickedObject.id._name;
          entityName = entityName.split("_");
          console.log("entityName ", entityName[0]);
          if (entityName[0] === "straightLinePoint") {
            rightEntityPicked = true;
          }
          if (rightEntityPicked) {
            dragging = true;
            scene.screenSpaceCameraController.enableRotate = false;
            pickedEntity = pickedObject;
          }
        }
      }
    }, Cesium.ScreenSpaceEventType.LEFT_DOWN);
    handler.setInputAction(function (movement) {
      if (ZoneMoment && rightEntityPicked && dragging) {
        var cartesian = pickedEntity.id.position.getValue(
          Cesium.JulianDate.fromDate(new Date())
        );
        var cartographic =
          scene.globe.ellipsoid.cartesianToCartographic(cartesian);
        var surfaceNormal =
          scene.globe.ellipsoid.geodeticSurfaceNormal(cartesian);
        var planeNormal = Cesium.Cartesian3.subtract(
          scene.camera.position,
          cartesian,
          new Cesium.Cartesian3()
        );
        planeNormal = Cesium.Cartesian3.normalize(
          planeNormal,
          planeNormal
        );
        var ray = viewer.scene.camera.getPickRay(movement.endPosition);
        var plane = Cesium.Plane.fromPointNormal(cartesian, planeNormal);
        var newCartesian = Cesium.IntersectionTests.rayPlane(ray, plane);
        var newCartographic =
          viewer.scene.globe.ellipsoid.cartesianToCartographic(
            newCartesian
          );
        cartographic.longitude = newCartographic.longitude;
        cartographic.latitude = newCartographic.latitude;
        pickedEntity.id.position.setValue(
          scene.globe.ellipsoid.cartographicToCartesian(cartographic)
        );
      }
      if (dragging) {
        mouseDroped = true;
      }
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
    handler.setInputAction(function () {
      if (ZoneMoment && rightEntityPicked && mouseDroped) {
        console.log("Left up ");
        dragging = false;
        mouseDroped = false;
        scene.screenSpaceCameraController.enableRotate = true;
      }
    }, Cesium.ScreenSpaceEventType.LEFT_UP);
  }
});

Need to advice on applying Replace in Javascript

I want to change the string displayed as $0 to Free in WooCommerce.

My website structure is as follows:

<div class="wc-block-components-radio-control__description-group">
   <span id="radio-control-0-free_shipping:2__description" class="wc-block-components-radio-control__description">
     <span class="wc-block-formatted-money-amount wc-block-components-formatted-money-amount">$0</span>

So, I applied the following code using the JS path of the Chrome Developer Tools.

<script>
let text = document.querySelector("#radio-control-0-free_shipping\:2__description > span").innerHTML;
document.querySelector("#radio-control-0-free_shipping\:2__description > span").innerHTML = text.replace("$0", "Free !");
</script>

But this doesn’t work.

So I re-applied the code below by changing the querySelector, but it doesn’t work.

<script>
let text = document.querySelector(".wc-block-formatted-money-amount.wc-block-components-formatted-money-amount
").innerHTML;
document.querySelector(".wc-block-formatted-money-amount.wc-block-components-formatted-money-amount
").innerHTML = text.replace("$0", "Free !");
</script>

It occur Uncaught TypeError: Cannot read properties of null (reading 'innerHTML') error.

I’ve tried this code in different cases, and it worked. But I don’t know why it doesn’t work on the cart page in WooCommerce.

Can someone give me advice on what parts I need to fix?

auto calculations with javascript and php

#I’m new in javascript and i need help in using auto calculations i try using different id but i ended the result in wrong row, when it comes more than 1 row the calculations showed in the first row. Here’s my code thankyou any help is appreciated

<?php   
$i=0;

$query = mysqli_query($conn,"SELECT * 
                            FROM tblrincistokopname 
                            WHERE id_stokop='".$_GET['idstokop']."'");

while($row=mysqli_fetch_array($query)) {  
    
    $inven=mysqli_fetch_array(mysqli_query($conn,
                        "SELECT * 
                        FROM tblinventori 
                        WHERE id_inventori='".$row[2]."'"));

    $stok=mysqli_fetch_array(mysqli_query($conn,
                        "SELECT persediaan 
                        FROM tblstokinventori 
                        WHERE id_inventori='".$row[2]."' 
                        AND outlet='".$_GET['outlet']."'"));
    if ($inven[2]=='produk') {
        $nama=mysqli_fetch_array(mysqli_query($conn,
                        "SELECT sku,nama,satuan,harga_beli 
                        FROM tblproduk 
                        WHERE id_produk='".$inven[1]."'"));
    } elseif ($inven[2]=='bahan') {
        $nama=mysqli_fetch_array(mysqli_query($conn,
                        "SELECT sku,nama,satuan,harga_beli 
                        FROM tblbahan 
                        WHERE id_bahan='".$inven[1]."'"));
    }
?>

          <tr>
            <input type="hidden" name="idinventori[]" multiple value="<?=$row[2]?>">
            <td><?=$nama[0]?></td>
            <td><?=$nama[1]?></td>
            <td><?=$nama[2]?></td>
            <td><?=$inven[2]?></td>
            <td><input type="number" name="stoksistem[]" id="stoksistem<?php echo $i; ?>" value="<?=$stok[0]?>"></td>
            <td><input type="number" name="stokaktual[]" id="stokaktual<?php echo $i; ?>" multiple onchange="calculateAmount(this)"></td>
            <td><input type="text" name="selisih[]" id="selisih<?php echo $i; ?>" value=""></td>
            <td><?=$nama[3]?></td>
            <td><input type="text" name="catatan2[]" size="10" multiple></td>
    </tr>      

<script>
function calculateAmount(e) {
    document.querySelector('#selisih<?php echo $i; ?>').value =
        document.querySelector('#stoksistem<?php echo $i; ?>').value - e.value
}
</script>
<?php
}
$i++;
?>

Use ant design dropdown

I want to create in my table the possibility of assigning a task to a collaborator in the same way as this example I put:

enter image description here

In the example in the image, when clicking on fontawesome, the possibility of selecting a collaborator appears and when clicking on the collaborator, it automatically replaces fontawesome with the name of the collaborator.

To create, I’m trying with the code that I leave below:

var mountNode = document.getElementById('container');

var linha = ``; 

linha += `<tr id="5">
            <td class="text-center text-muted"> #5</td>
            <td class="text-center text-muted"> Creche I</td>
            <td class="text-center text-muted"> Teste</td>
            <td class="text-center text-muted"> Teste de Administrador</td>                  
            <td class="text-center text-muted" style="vertical-align: middle;"><div class="tooltip-demo"><div class="most" id="container"> <i class="pe-2x pe-va pe-7s-user"></i></div><div class="tooltip">Atribuir Membro</div></div></td>
            <td class="text-center text-muted"> 2022-05-31</td>
          </tr>`;


$("#daberto tbody").html(linha);

"use strict";
const { Select, Icon, Divider } = antd;
const Option = Select.Option;
ReactDOM.render(React.createElement(Select, { defaultValue: "lucy", style: { width: 120 }, dropdownRender: menu => (React.createElement(React.Fragment, null,
        React.createElement("div", { onMouseDown: () => console.log("before clicked") }, "BEFORE"),
        menu,
        React.createElement("div", { onMouseDown: () => console.log("after clicked") }, "AFTER"))) },
    React.createElement(Option, { value: "jack" }, "Jack"),
    React.createElement(Option, { value: "lucy" }, "Lucy")), mountNode);
.tooltip-demo {
    position: relative;
}

.tooltip {
    opacity: 0;
    visibility: hidden;
    transition-property: opacity, visibility;
    transition-duration: .1s;
    position: absolute;
    top: -.75rem;
    left: 50%;
    transform: translate(-50%, -100%);
    background-color: #333;
    color: #eee;
    padding: .25rem .75rem;
    white-space: nowrap;
    border-radius: 3.5px;
}

.most:hover ~ .tooltip,
.most:focus ~ .tooltip,
.most.active ~ .tooltip {
  opacity: 1;
  visibility: visible;
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/pe-icon-7-stroke/dist/pe-icon-7-stroke.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/antd/4.20.7/antd.min.css">

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/antd/4.20.7/antd.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/antd/4.20.7/antd-with-locales.min.js"></script>

<table class="align-middle mb-0 table table-borderless table-striped table-hover daberto" id="daberto">
  <thead>
      <tr>
          <th class="text-center col-1">ID</th>
          <th class="text-center col-2">Valência</th>
          <th class="text-center col-1">Categoria</th>
          <th class="text-center col-2">Motivo</th>
          <th class="text-center col-2">Destinatário</th>
          <th class="text-center col-1">Reportado</th>
      </tr>
  </thead>
  <tbody>

  </tbody>
</table>

If you check, everything is working except the part of clicking on the fontawesome to show the collaborators to assign the task. I’m using html, css and javascript.

How can I componentize TextFields into a function rather than writing multiple TextFeilds?

There is a lot to read here, but there is no other way to explain the issue I have.

I have four files, App.js, Intakes.js, IntakeDetails.js and Sizing.js. I start on the Intakes page where the user is presented with a table of data. The user clicks on a row and is taken to IntakeDetails. In IntakeDetails, there are four MUI tabs, one of which is Sizing.

The user never actually goes to a Sizing page. They only get to IntakeDetails. From IntakeDetails, the user can view, edit, and create data based on what tab they are in. If the user wants to create or update Sizing data, they navigate to the sizing tab and click the edit icon on the row of their choice from the Sizing table. The Dialog then pops up and its TextFields are populated with the data from the row the user clicked.

Sizing.js is 600+ lines long. 211 lines in this file are taken up by the MUI dialog which displays the data from the table row the user has clicked. The dialog is so long because of 19 TextFields. I want to make a short function with a parameter for id, value and label. This way I wont need to have lots of multiline TextFields. All of the TextFields in the Dialog take up 8 lines. With a function, this could be just one or two lines.

I have made a function to shorten the file previously, but it introduces a new problem. If I have a TextField that is populated with the word ‘Hello’, and I edit it, the Dialog disappears, reappears, and focus is lost on the TextField I edited, but, the change I made is persistent. I can only enter or remove one character at a time before having to click on the TextField again to enter another. I can copy and paste full words and sentences at once, but again the Dialog disappears and comes back.

I can’t use .map because my data is not divided into groups or objects. It is all one object and needs to be presented in the dialog in a specific order, which is why they are hardcoded. When I type in a TextField, there is a long delay between the time I press a key on the keyboard and the time the character appears in the TextField. This delay gets longer when I type faster.

The return in IntakeDetails is here:

import Sizing from "./Sizing";
...
return (
  <div class="aspectwrapper">
    <div class="content">
      <Container>
        <Paper>
          <Box  sx={{ width: "100%" }}>
            <Box sx={{ borderBottom: 1, borderColor: "divider" }}>
              <Tabs value={value} onChange={handleChange}>
                <Tab label="Intake Details" {...a11yProps(0)} />
                <Tab label="Sizing" {...a11yProps(1)} />
              </Tabs>
            </Box>
            <TabPanel value={value} index={0}>
              ** Intake Details Stuff **
            </TabPanel>
            <TabPanel value={value} index={1}>
              <Sizing />
            </TabPanel>
          </Box>
        </Paper>
      </Container>
    </div>
  </div>
)

The return in Sizing. There are 19 TextFields, all structured as seen below. There are also buttons in a <DialogActions> tag which I have not included here.

const onTextChange = (e) => {
  const id = e.target.id;
  var value = e.target.value;
  setSingleSizing({ ...singleSizing, [id]: value });
};
...
return(
  <div id="sizing-container">
    <Dialog open={open} onClose={handleClose} maxWidth={"xl"}>
      <DialogTitle id="form-dialog-title">Edit estimation</DialogTitle>
      <DialogContent>
        <Box>
          <TextField
            id="SizingComments"
            value={singleSizing?.SizingComments}
            label={"Estimation Comments"}
            onChange={onTextChange}
            variant="outlined"
            style={{ margin: "1em", minHeight: "1em", minWidth: "15em" }}
          />
        </Box>
        </Box>
      </DialogContent>
    </Dialog>
  </div>
)

GraphQL Apollo solving N+1 when using RestDataSource

I am using a RestDataSource with ApolloGraphQL server when I encountered the N+1 issue, from my research, I was able to find solutions such as dataloader that solves the issue if I were to be using the graphQL directly to a DB but not one for the RestDataSource

Is there a way I could restructure my APIs or tools I can use to handle the N+1 issue when using RestDataSource?

Example Query Schema:

{
  grandParentQuery {
    parentQuery {
      childQuery {
        accountNo
      }
    }
  }
}

In my example query, I would have something like grandParentQuery which retrieves a list of grand parents, which queries a list of parents and so on to child

Example Resolver Query

  @Query('examples')
  async examples(): Promise<any> {
    const { data } =
      await this.exampleService.getAllExamplesById();

    return data;
  }

All my endpoints are currently a naive getAllDataById query which return a list based on an Id