Discord bot keeps getting rate limited

so I have a Discord bot which when someone sends a message in my server, the bot sends the message to my dm’s, and because the rate limit is 5 a second, if multiple messages are sent a second which they are it rate limit my bot, my question is how can I make it so my discordjs bot sends each message to my dm’s a few seconds after its sent.

For example message 1 is sent, 10 seconds later message 1 is dm’ed to me, and if message 2 is sent straight after 1, then still send 10 seconds later after the message is sent.

jQuery – radio click event not working with checkboxes with same class name

I have a checkbox like so with the class name anotherCheese, When someone clicks on that it will append to the steps-row-first class, what is being appeneded also has a radio button with the class name anotherCheese, but my click event does not get called on the new radio button with the class name anotherCheese, what am I doing wrong?

Here is the HTML

<div class="steps-row-first">
<div class="radio-wrapper">
              <div class="radio-group">
                <input type="radio" class="anotherCheese" name="anotherCheese" value="yes" />
                <label>Yes</label>
              </div>
              <div class="radio-group">
                <input type="radio" name="anotherCheese" value="no" />
                <label>No</label>
              </div>
            </div>
</div>

And the jQuery:

$(‘.anotherCheese').on("click", function(){
    if($(this).val() == 'yes')
    {
      $(".steps-row-first").append('<div class="radio-wrapper"> <div class="radio-group"> <input type="radio" class="anotherCheese" name="anotherCheese" value="yes"/> <label>Yes</label> </div><div class="radio-group"> <input type="radio" name="anotherCheese" value="no"/> <label>No</label> </div></div>');
    }
  });

Thanks for your help in advanced.

Json transferred in javascript

jsonData = 
        {
            "a":{
                "b":{
                    "c":"d"
                    ,"e":"f"
                }
                ,"g":{
                    "h":"i"
                    ,"j":"k"
                    ,"m":"n"
                }
                ,"l":{
                    "o":"p"
                    ,"q":"r"
                }
            }
        }
}

How do you create an array starting with a with JavaScript and transfer it to the jsondata function?

chart js doesn’t work properly on mobile devices

on my project im using chart js bar graph and line graph for data visualization from mysql database using php and javascript , both works perfect but when i try to open it on mobile device
only the line graph doesn’t work properly .
I cant see the line and also i see only 2 axis.
I tried to change mantainAspectRatio and responsive options .
I also tried to add resize-observer-polyfill.
nothing works
Does anyone have an idea how to solve this??

js file:
”’

function myFunction() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var type = [];
  var gain = [];
  var range = [];
  var dates =[];
  var gains = [];
  var gains2=[];
  range=getDates(new Date(data2[data2.length-1].TargetStart), new Date(data2[data2.length-1].TargetEnd))
for(var i in data2) {
    
    type.push("raise type: "+data2[i].type);
    gain.push( data2[i].SellPrice- (data2[i].amount* data2[i].BuyPrice) );
    dates.push(new Date(data2[i].EndDate));
    
    
  }
var x= [];
  for(let i=0;i<data2.length;i++) {  
        for (var j in range){
            if(range[j]>=dates[i]){x.push({d:range[j],g:gain[i]});break;}
    }
  }
  
  for (var j in range){
    //  if(range[3]<range[j])break;
      var culgain=0;
    for(var i in x) {    
        if(range[j]>=x[i].d)culgain+=x[i].g;
    }
    
    gains.push({x:range[j] , y:culgain});
    
  }
  
    for (var j in gains){
        if(gains[3].x<gains[j].x)break;
        gains2.push({x:gains[j].x,y:gains[j].y});
        
    }
var he=data2[data2.length-1].Aname+': רווחי גיוסים צפויים';
    
    var he2=data2[data2.length-1].Aname+':רווחי גיוסים';
const data = {
    
    datasets: [{
        label: he,
        data: gains,
        backgroundColor: "rgba(59, 89, 152, 0.75)",
        borderColor: "rgba(59, 89, 152, 1)",
        pointHoverBackgroundColor: "rgba(59, 89, 152, 1)",
        pointHoverBorderColor: "rgba(59, 89, 152, 1)",
        tension: 0.1,
        borderWidth: 1
    },
    {
        label: he2,
        data: gains2,
        backgroundColor: "rgba(211, 72, 54, 0.75)",
        borderColor: "rgba(211, 72, 54, 1)",
        pointHoverBackgroundColor: "rgba(211, 72, 54, 1)",
        pointHoverBorderColor: "rgba(211, 72, 54, 1)",
        tension: 0.3,
        
        borderWidth: 3
    }
    
    
    ]
};
const config = {
    labels:range,
    type: 'line',
    data,
    options :{
        

        
        scales : {
            x : {
                
                type : 'time' ,
                time : {
                    unit : 'week'
                }
            },
            y :{
            //max:data2[data2.length-1].Target,
            //beginAtZero: true
            suggestedMin: 0,
            suggestedMax: data2[data2.length-1].Target
            }
        }
    }
    
    
};
let el = document.getElementById("mycanvas");
    //If it isn't "undefined" and it isn't "null", then it exists.
if(typeof(el) != 'undefined' && el != null){
    el.parentNode.removeChild(el);
} 

el = document.getElementById("myTableHead");
    //If it isn't "undefined" and it isn't "null", then it exists.
if(typeof(el) != 'undefined' && el != null){
    el.parentNode.removeChild(el);
}   


    
let table = document.createElement('canvas');
    table.id="mycanvas";

    // Adding the entire table to the body tag
    document.getElementById('wrap').appendChild(table);
    


var ctx = document.getElementById("mycanvas");
const myChart = new Chart(ctx,config); } };

xmlhttp.open("GET", "raisegraph.php", true);
xmlhttp.send();
              }




    
    

    
    
    
    

”’

on computer

on computer

on safari

on safari

Can I get a JSON object with name value?

I’m trying to make Covid-19 tracker App by ReactJS.
I want to get data that only an object (a specific province value) from JSON API with ProvinceChange event.

the problem

I can’t get data that only an object (a specific province value).

what I tried

I tried method filter using province.name but is not work,like I get
enter image description here

Sample JSON API

[
{
    "txn_date": "2022-03-07",
    "province": "กระบี่",
    "new_case": 112,
    "total_case": 18101,
    "new_case_excludeabroad": 112,
    "total_case_excludeabroad": 17838,
    "new_death": 2,
    "total_death": 93,
    "update_date": "2022-03-07 07:20:43"
},
{
    "txn_date": "2022-03-07",
    "province": "กรุงเทพมหานคร",
    "new_case": 2815,
    "total_case": 590810,
    "new_case_excludeabroad": 2809,
    "total_case_excludeabroad": 587121,
    "new_death": 7,
    "total_death": 7126,
    "update_date": "2022-03-07 07:20:43"
},
{
    "txn_date": "2022-03-07",
    "province": "กาญจนบุรี",
    "new_case": 176,
    "total_case": 33734,
    "new_case_excludeabroad": 176,
    "total_case_excludeabroad": 33684,
    "new_death": 2,
    "total_death": 214,
    "update_date": "2022-03-07 07:20:43"
},
{
    "txn_date": "2022-03-07",
    "province": "กาฬสินธุ์",
    "new_case": 214,
    "total_case": 18163,
    "new_case_excludeabroad": 214,
    "total_case_excludeabroad": 18159,
    "new_death": 0,
    "total_death": 97,
    "update_date": "2022-03-07 07:20:43"
},]

This is my code

const App = ()=>{
  const [provinces, setProvinces] = useState([]);
  const [province, setProvince] = useState("thailand");
  const [provinceInfo, setProvinceInfo] = useState({});

  useEffect(() => {
   
   const getProvincesData = async  () => {
     fetch("https://covid19.ddc.moph.go.th/api/Cases/today-cases-by-provinces")
      .then((response) => response.json())
      .then((data) => {
        const provinces = data.map((province) => ({
          name: province.province,
        }));
        setProvinces(provinces);
      });
   };
  
    getProvincesData();
  }, []); 

  const onProvinceChange = async (event) =>{
    const provinceCode = event.target.value;
    //setProvince(provinceCode);

    const url = 
      provinceCode === "thailand"
       ? "https://covid19.ddc.moph.go.th/api/Cases/today-cases-all"
       : 'https://covid19.ddc.moph.go.th/api/Cases/today-cases-by-provinces' ;

    await fetch(url)
    .then(response => response.json())
    .then(data => {
      const provinceInfo = data.filter((data) => {
          return data.name === '{province.name}'
        })
        setProvince(provinceCode);
      // All of the data from the province response
        setProvinceInfo(data);
        });
    
    };
  
  console.log(provinceInfo);

  return (
    <div className="app">
      <div className='app__left'>
        <div className="app__header">
          <h1>COVID-19 TRACKER in Thailand</h1>
          <FormControl>
            <Select variant="outlined" onChange={onProvinceChange} value={province}>
              <MenuItem value="thailand">ประเทศไทย</MenuItem>
              {provinces.map((province) => (
                <MenuItem value={province.name}>{province.name}</MenuItem>     // Loop through all the province and show drop down list of the option 
              ))}

            </Select>
          </FormControl>
       </div>
    </div>
  
  );
}

Best way to handle value tied to conditional

In a function I have I try to take a value, and if the value ends up as undefined, then I call the same function but with a different parameter

let price = await getPrice(name, category, '1');

if (price === undefined) {
   price = await getPrice(name, category, '2');

   if (price === undefined) {
      price = await getPrice(name, category, '3');
   }
}

I’m told that this approach can be very error prone, and after a bit of analyzing, I can see why. However, I don’t know if there’s a better way to handle this.

I need the third parameter since I use it to process a URL, as that URL has one of those strings.

static getPrice(productName, productCategory, variantNumber) {
 ...
 let url = `https://exampleurl.com/${productName}cat=${productCategory}${variantNumber}`;
 ...
}

I want to get the value of this function but i cant access it

How can I access the value of function result into a variable, actually I am trying to get the value from this function and save it into a variable so then I can submit this value into POST request, but right now I am unable to get the value, what I did in this function I have puppeteer node js code I have a result of OCR into a variable and I just need to submit this OCR result into POST login function.

  let res = "";
  // Run and wait the result
  ocrSpaceApi.parseImageFromLocalFile(imageFilePath, options)
    .then(function (parsedResult) {
      //console.log('parsedText: n', parsedResult.parsedText);
      res =  parsedResult.parsedText;
      console.log(res);
    }).catch(function (err) {
      console.log('ERROR:', err);
    });
    console.log(res);

want the parsed result in RES varaiable.

Angular Datatables not working with button in td

When I remove the update and delete button the code work sometime and sometime says no data available and sometime the datatable also didn’t show up.. Can anyone help me removing the problem..the following code is given below

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

import { User } from 'src/app/Model/user.model';
import { UserService } from 'src/app/Service/user.service';

@Component({
  selector: 'app-user-list',
  templateUrl: './user-list.component.html',
  styleUrls: ['./user-list.component.css']
})
export class UserListComponent implements OnInit {
  users!: User[];
  constructor(private userService: UserService, private router: Router) { }
  dtOptions: DataTables.Settings = {};
  ngOnInit(): void {
    this.dtOptions = {
      pagingType: 'full_numbers',
      pageLength: 5,
      lengthMenu: [5, 10, 15],
      processing: true
    };
    this.userService.findAll().subscribe(data => {
      this.users = data;
    });
    // $('#datatable-userlist').DataTable();
  }
  deleteUser(userId: number) {
    this.userService.deleteUser(userId).subscribe(
      data => {
        this.userService.findAll().subscribe(data => {
          this.users = data;
        });
      },
      result => this.gotoUserList());
  }
  gotoUserList() {
    this.router.navigate(['/users']);
  }

  updateUser(user: User) {
    this.router.navigate(['update', user]);
  }
}
<div class="panel panel-primary">
    <div class="panel-heading">
        <h2>User List</h2>
    </div>
    <div class="panel-body">
        <table datatable [dtOptions]="dtOptions" 
        class="table table-striped table-bordered table-sm row-border hover"
         cellSpacing="0" width="100%">
            <thead>
                <tr>
                    <th>Id</th>
                    <th>Name</th>
                    <th>ContactNo</th>
                </tr>
            </thead>
            <tbody>
                <tr *ngFor="let user of users">
                    <td>{{user.userId}}</td>
                    <td>{{user.userName}}</td>
                    <td>{{user.contactNo}}</td>
                    <td>
                        <div class="user-update-btn">
                        <button (click)="deleteUser(user.userId)" class="btn btn-danger shiv">Delete</button>
                        <button (click)="updateUser(user)" class="btn btn-success shiv">Update</button>
                    </div>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
</div>

Its showing No data available in table even the data is in table When I remove the update and delete button the code work sometime and sometime says no data available and sometime the datatable also didn’t show up.. Can anyone help me removing the problem..

Javascript addeventlistener with parameter in for loop [duplicate]

I am trying to add onclick listeners to a list of buttons, the id of the buttons is in a range of 0-array length in this pattern btn1-btn2-btn3 and so on

I use a for loop to get the buttons by id and the event listeners against the fetched dom element:

for(var i =0; i<length; i++){
  console.log("log 1: Adding listener for "+i);
  document.getElementById("btn"+i).addEventListener("click", function(){
  myFunc(i);
  });
}

The Function

myFunc(i){
  alert(i);
}

The Problem

No matter what button I click, I always get the last number in the for loop in the alert. I have checked and all buttons have different id’s and the log 1 output is correct( ten logs 0-9). However log 2 output is the last number 10 no matter what button I click.

I want to know how I can pass the iterator(i) in the onclick listener. Any advice or suggestion will be agreat help to this newbie,Thanks!

Focusing a text input using a ref works but focusing a radio input does not

I have a simple React example created here: https://codesandbox.io/s/cocky-browser-bjj9z8?file=/src/App.js

The goal is to have 2 outcomes:

  1. The first button causes the text input to gain focus (this works)
  2. The second button causes the radio input to gain focus (this does not work)

I have implemented the refs and focus events on the buttons in the same way but the radio input does not gain focus for some reason. Attempting to tab and shift+tab through the document will show that both input elements have the ability to be focused.

How to add a field to an array of objects using useState in react

I’m building an app in react native and I want a way in which I can regularly add a field to one ore all of the user data before pushing it to the database, It is an array of objects and I know the index of each object. I’m aware of object destructuring but I don’t know how to go about this.
In the example below, how do I add the field “hobby” and a value of “Football” to smith alone? Thanks in advance.

const [usersData, setUsersData] = useState([
  {
    name: "Jane",
    sex: "female",
    age: "20",
  },
  {
    name: "Doe",
    sex: "male",
    age: "29",
  },
  {
    name: "Smith",
    sex: "male",
    age: "24",
  },
]);

const addHobby = (index, hobby) => {
  //Adding the field here//
};

Sync two scrolls with different sizes

I have been trying to sync two different divs with different sizes. As you can see in this jsfiddle I’m almost there. But while move the bigger horizontal scroll the inner one doesn’t finish at its final scroll end. I want both to be synchronized, start and finish in their own sizes. I have tried to play with their width but cannot make it work. I believe an offset is missing.

 $(function() {
   // move along with container
   $('#container').on('scroll', e => {
     $('#container2').css(
       'transform',
       `translate(${e.target.scrollLeft}px, ${e.target.scrollTop}px)`,
     );

     const containerElement = $('#container'),
       bigPanelElement = $('#big-panel'),
       container2Element = $('#container2'),
       bigPanelWidth = bigPanelElement.width(),
       bigPanelHeight = bigPanelElement.height(),
       containerScrollLeft = containerElement.scrollLeft(),
       container2ScrollLeft = container2Element.scrollLeft(),
       containerScrollTop = containerElement.scrollTop(),
       container2Width = container2Element.width(),
       container2Height = container2Element.height();

     const newScrollLeft =
       bigPanelWidth === 0 ?
       0 :
       (container2Width * containerScrollLeft) /
        bigPanelWidth,
       newScrollTop =
       bigPanelHeight === 0 ?
       0 :
       (container2Height * containerScrollTop) /
       bigPanelHeight;

     //console.log(`newScrollLeft ${newScrollLeft}`);

     container2Element.scrollLeft(newScrollLeft).scrollTop(newScrollTop);

   });
 });

Secondly, would be nice to have that the inner horizontal scroll also scroll the outer one in sync too.

Chrome Extension Scraping Loop

I am trying to learn web scraping through chrome extensions. I scrape some hard to scrape things and I have built some custom scraping extensions. This is the first one where I am trying to loop, and automatically open and hopefully close tabs in a loop.

The problem I have seems to have to do with active = false windows. When I use active = true windows I get presumably all the AJAX loading of the page however I don’t get the full data when I do it with false windows. It is like the AJAX loading doesn’t occur.

I believe my code fires when the page is fully loaded.

I scrape these pages normally by simply loading the page active and sending a message from the content to a textarea using the same code as in payload.js. Then I finish parsing in PHP ;(

I used this answer in my solution. Open tab, wait for it to finish loading then close it

Does anyone know why I get different results using the same content script (payload.js) for active and inactive windows?

{
    "manifest_version": 2,

    "name": "Loop",
    "description": "A simple Looping page-scraping extension.",
    "version": "1.0",
    "author": "willrich33",

    "background": {
        "scripts": ["popup.js"],
        "persistent": true
    },

    "permissions": [
        "tabs",
        "http://*/",
        "https://*/",
        "storage"
    ],
    
    "content_scripts": [{
        "matches": ["<all_urls>"],
        "all_frames": true,
        "js": ["jquery-3.6.0.min.js"],
        "run_at":"document_start"
    }],
    
    "browser_action": {
        "default_icon": "logo.png",
        "default_popup": "popup.html"
    }
}

popup.js

//Simple button on the popup
document.addEventListener('DOMContentLoaded', function () {
    
    var btn = document.getElementById('myOpen');
    
    btn.addEventListener('click', function() {       
                       
        var arr = document.getElementById('pagearea').value.split("n");
        var urls = arr.map(element => {
           return element.trim();
        });
        
        document.getElementById('pagearea').value = "";
             
        create_tab(urls);       

    });
});

//Javascript Promise timer
const timer = ms => new Promise(res => setTimeout(res, ms));

// We need to wrap the loop into an async function for this to work
async function create_tab (urls) { 

//loop through urls
for (let i = 0; i < urls.length; i++) {
    
    chrome.tabs.create({url: urls[i], selected: false }, myTab => {
      
      function listener(tabId, changeInfo, tab) {
          // make sure the status is 'complete' and it's the right tab
          if (tabId === myTab.id && changeInfo.status == 'complete') {
              
              chrome.extension.getBackgroundPage().chrome.tabs.executeScript(
                      tabId, 
                      { file: 'payload.js' },
             );
              
             chrome.tabs.onUpdated.removeListener(listener);
          }
      }
      chrome.tabs.onUpdated.addListener(listener);
    });
    
    await timer(10000); // then the created Promise can be awaited
  }
}

// Listen to messages from the payload.js script and write to popout.html
chrome.runtime.onMessage.addListener(function (message) {
    
    document.getElementById('pagearea').value =  message;
    
});

payload.js

chrome.runtime.sendMessage(document.body.outerHTML);

popup.html

<!doctype html>
<html>

<head>
    <title>Loop</title>
    <script src="popup.js"></script>
</head>

<body>
    <h3>Loop</h1>
    <p id='pagetitle'></p>
    <textarea id='pagearea' cols="40" rows="6"></textarea><br>
    <button id="myOpen">Open Page</button>
    
</body>
</html>

Exporting Async API call to another file

Im’trying to seperate api call from return/rendering but when importing teams (which contains data) shows as undefined. Is it because of the async await function?
How can I export the data and map it in the return on Teams.js?
Is there a better way to seperate the Api call from the return/rendering component?

FormTeams.js

import { useState, useEffect } from 'react';
import { Spinner } from "react-bootstrap";
import 'bootstrap/dist/css/bootstrap.min.css';

const FormTeams = () => {
    const BASE_URL = process.env.REACT_APP_URL

    const [isLoading, setIsLoading] = useState(true);
    const [teams, setTeams] = useState([]);

    useEffect(() => {
        getTeams();
    }, []);

    const getTeams = async () => {
        try {
            const response = await fetch(`${BASE_URL}/teams`)
            return response.json()
                .then(data => {
                    setTeams(data)
                    setIsLoading(false)
                })
        } catch (error) {
            console.log(error)
        }
    }

    if (isLoading) {
        return (<Spinner animation="border" variant="primary" />)
    }

    const deleteTeam = async (id) => {
        try {
            await fetch(`${BASE_URL}/teams/${id}`, {
                method: "DELETE",
            }).then(response => {
                setTeams(teams.filter(team => team.id !== id))
                return response.json()
            })
        } catch (error) {
            console.log(error)
        }
    }
    
    return {teams, deleteTeam}
}

export default FormTeams

Teams.js

import { Link, } from "react-router-dom";
import { Button, ButtonGroup } from "react-bootstrap";
import FormTeams from './FormTeams'

const Teams = () => {
   const {teams, deleteTeam} =FormTeams()

    return (
        <div>
            <h2 className='centered'>Clubs</h2>
            <div><Link to="/Teams/add" className="link">Add New</Link></div>
            <table className='teams'>
                <thead>
                    <tr >
                        <th>№</th>
                        <th>Team</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody >
                    {teams.map((team, index) => (
                        <tr key={team.id}>
                            <td>{index + 1}.</td>
                            <td>{team.team_name}</td>
                            <td>
                                <ButtonGroup>
                                    <Link to={`/Teams/${team.id}`} className='link'>View</Link>
                                    <Link to={`/Teams/edit/${team.id}`} className='edit'>Edit</Link>
                                    <Button variant="danger" onClick={() => deleteTeam(team.id)}>Delete</Button>
                                </ButtonGroup>
                            </td>
                        </tr>
                    ))}
                </tbody>
            </table>
            <Link to={'/'} className='link'>Back To Home Page</Link>
        </div>
    )
}

export default Teams