discord.js how to find all users assigned @everyone when bot is brought online in server

I am having trouble attempting to find users assigned to @everyone when I bring the bot online in my server. I can do it via commands in my discord server, however, when trying to do it automatically, I get the error:

Cannot read properties of undefined (reading ‘roles’)

Here is my code:

const Discord = require('discord.js');

const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] });

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', (message) => {
    console.log('Bot is online!');
    client.commands.get('find').execute(message);
});
module.exports = {
    name: 'find',
    description: "",
    execute(message){

        const role = message.guild.roles.cache.find(role => role.name === "@everyone");

        console.log('complete')
    }
}

How do I find all the members assigned @everyone when my bot goes online instead of having to type a command in my discord server?

How to update object field by having the object field name dynamically? [duplicate]

I have an object that holds key: value.
Now, I get dynamically the name of the key that i need to update
const chips = {
David: 1,
Goliath: 9
}

const name = 'David';

// now I want to use name dynamically and update David chips to, let's say 10
??? = chips[name] + 1; // update to... 'David': 10

How can I update David by using the argument ‘name’ in this case?

JavaScript Regexp construction: Invalid regular expression: Nothing to repeat

I have a regex pattern that works fine in Regex101: ~<a .*?">(*SKIP)(*FAIL)|bwordb

I am trying to make it a Regexp so it can be used in the replace() function in JavaScript.

The line of JavaScript code is:

var regex = new RegExp("~<a.*?">(*SKIP)(*FAIL)|\b"+ word + "\b", 'g');

Where “word” is the word I’m trying to match.

When I run it though, the console shows the following error:

Uncaught (in promise) SyntaxError: Invalid regular expression:
/~<a.*?”>(*SKIP)(*FAIL)|word/: Nothing to repeat

Am I escaping characters wrong? I tried backslash-escaping every special character I could find (?, *, <, and so on) in my JavaScript code and it still spat out that error.

How to place two 3d models in different div? Three.js

The page has a divs with classes “skin”, “skin2”, “skin3”…
And for each class you need to place your 3d model.

I’m trying to do this, but all the 3d models, are tied to the first model.

I want to do this using the example of this site minecraft-skins

Image code results

scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(10, window.innerWidth / window.innerHeight, 0.1, 50);
camera.position.z = 20;
camera.position.y = 1.5;
camera.position.x = 0;

renderer = new THREE.WebGLRenderer({ alpha: true, antialias: true });
renderer.setClearColor(0x000000, 0);
renderer.setSize(200, 300);
renderer.gammaOutput = true;
var light = new THREE.AmbientLight();
scene.add(light);
let loader = new THREE.GLTFLoader();

loader.load('/Стив.gltf', function (gltf) {
    let obj = gltf;
    document.getElementsByClassName('skin')[0].insertBefore(renderer.domElement, document.getElementsByClassName('skin')[0].firstChild);
    scene.add(obj.scene);
    obj.scene.scale.set(4.8, 1.5, 4.9);
    obj.scene.rotation.y += 3.6;
    obj.scene.rotation.x += 0.06;
});

loader.load('/Стив1.gltf', function (gltf2) {
    let obj = gltf2;
    document.getElementsByClassName('skin1')[0].insertBefore(renderer.domElement, document.getElementsByClassName('skin1')[0].firstChild);
    scene.add(obj.scene);
    obj.scene.scale.set(4.8, 1.5, 4.9);
    obj.scene.rotation.y += 3.6;
    obj.scene.rotation.x += 0.06;
});

function animate() {

    requestAnimationFrame(animate);
    renderer.render(scene, camera);
}
animate();
<!DOCTYPE html>
<htm>
<head>
    <title>Skins</title>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/build/three.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/examples/js/controls/OrbitControls.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/examples/js/loaders/GLTFLoader.js"></script>
</head>
<body>
<div class="block">
    <div class="skin">
    </div>
</div>
<div class="block">
    <div class="skin1">
    </div>
</div>

<script src="./script_01.js"></script>

</body>
</html>

why isn’t rendering? (react.js)

Hey there beautiful people, I hope your day is going well. I’m using React.js and I’m trying to do some basic stuff but I can’t figure it out. I’m just trying to render a banner with a navbar underneath it 🙁

My navBar.js code right now:

import React from "react";
import { ReactDOM } from "react-dom";

export function navBar() {
    return (
        <div>
            <nav className = "nav">
                <a>Upload Items</a>
                <a>New Items</a>
                <a>Textbooks</a>
                <a>Electronics</a>
                <a>Life</a>
                <a>Accessories</a>
                <a>others</a>
            </nav>
                
        </div>

    );
}


import logo from './logo.svg';
import React, { useState } from 'react';
import './App.css';
import ReactDOM from 'react-dom';
import {navBar} from './components/navBar'

function App() {
  
  //let [categories, setCategories] = useState(['textbooks', 'electronics', 'life', 'accessories', 'others'])
  return (
    <div className="App">
      <header className="App-header">
        <img className='logo' src={require('./revelliePicture.jpg')}/>
        <h1>Aggie Market</h1>
      </header>

      
      <navBar />
      
    </div>
  );
}


export default App;

what it currently looks like

Concatenate each object property values of javascript array , properties are list of strings in javascript

i have array of objects need to convert to new array with new property using another list of strings to read the property in javascript.

var output =

[
 {Id: '000000CayeAAC', Name: 'KCP13', FTA: 'LOS', FTN: 'M'}
 {Id: '000000CayLAAS', Name: 'KCN15', FTA: 'DC', FTN: 'M'}
 {Id: '000000CaxXAAS', Name: 'KCA21', FTA: 'AUS', FTN: 'M'}
 {Id: '000000CaxCAAS', Name: 'KCZ43', FTA: 'CA', FTN: 'M'}
]

var mypropertylist = [‘Name’,’FTA’,’FTN’];

i want to new array is like below

var newArray =

 [ 
  {value: '000000CayeAAC', concatName: 'KCP13 - LOS - M'}
  {value: '000000CayLAAS', concatName: 'KCN15 - DC - M'}
  {value: '000000CaxXAAS', concatName: 'KCA21 - AUS - M'}
 ]

i tried this way

output.map(item=>{
                    
                    this.newArray  = [...this.newArray,
                                            {value:item.Id, 
                                             concatName:item.Name + ' - '+item.FTA+ ' - '+item.FTN}];

i got desired output but i want to get dynamically by using mypropertylist

Thanks in Advance!

Cannot setting the state with the data fetched in useEffect -React

I want to send an API request in useEffect hook and setting the state variables value with the fetched data. I added 2 console.log for detecting the state variables value. I except the second log to be setted with the fetched data, however it still prints null.

Here is my code:

import { useEffect, useState } from "react";
import axios from "axios";
const Test = () =>{
    const [users, setUsers] = useState(null);
    useEffect(()=>{
        const getData = async ()=>{
            const resp = await axios.get("https://jsonplaceholder.typicode.com/todos");
            console.log(users);
            setUsers(resp.data);
            console.log(users);
        };
        getData();
    },[])
    return (
        <div>hello</div>
    )
};

export default Test;

Additionally the console output look likes this:

null
null

¿Cómo es un auténtico perro Pitbull?

Los Pitbull aparecieron por primera vez en el Reino Unido, allá por el 1800, donde fueron desarrollados como perros de pelea.

Los británicos eran unos fanáticos del “Bull Baiting”, que consistía en que uno o dos perros acosaba a un toro durante horas, hasta que el animal se desplomaba, ya fuera por la fatiga o por las heridas recibidas.

Cuando estas luchas fueron prohibidas, comenzaron a utilizarse ratas en lugar de toros. En este caso, el perro ganador era el que mataba más ratas en menos tiempo. Las ratas se colocaban en una fosa u hoyo (“pit” en inglés), para que no pudieran escapar.

Como se necesitaban perros más ágiles y veloces que para las peleas con toros, comenzaron a cruzarse los Bulldog con los Terrier. Este cruce dio lugar a perros muy poderosos, los Pitbull Terrier, que tenían la fuerza de los Bulldog y la resistencia y tenacidad de los Terrier.

Más adelante, ganaron fama las peleas entre perros, ya que eran más fáciles de ocultar como actividad clandestina.

Aún hoy se desarrollan peleas de perros ilegales. Los Pitbull son muy solicitados para estas peleas, debido a sus características físicas y a su carácter.

La cría selectiva se orientó hacia la inhibición de la mordedura a los seres humanos, ya que necesitaban poder entrar a la fosa y manejar a sus perros sin ser mordidos. Esto dio lugar a perros que se muestran leales y cariñosos con los humanos, especialmente con los niños.

Cuando los británicos llegaron a los Estados Unidos, lo hicieron con sus Pitbull. Estos perros, desarrollados para la lucha, resultaron ser unos grandes perros de trabajo, que además protegían a sus familias de los ladrones y de los animales salvajes. Poco a poco, dejaron de utilizarse como perros de pelea y se convirtieron en unos magníficos compañeros, gozando de gran popularidad.

En 1976, las peleas de perros se declararon ilegales, lo que atrajo de nuevo la atención hacia las peleas clandestinas. Los Pitbull volvieron a utilizarse con esta finalidad, y la gente dedicada a este negocio comenzó a criar a sus propios perros, sin preocuparse por su temperamento ni por su socialización, puesto que su objetivo era obtener beneficios en las peleas. Así, el Pitbull comenzó a ganarse su actual fama de perro peligroso, llegando a desarrollarse una legislación específica para la raza.

Actualmente, el Pitbull está recuperando su buena reputación, gracias a mucha gente que se ha dedicado a reeducarlos y mostrar que son unos excelentes compañeros, destacando sus habilidades como perros de trabajo. Muchos de estos perros se utilizan en campos como la detección de drogas, búsqueda y rescate, perros de terapia y otras muchas funciones.

Desgraciadamente, aún hoy algunos Pitbull son utilizados como perros de ataque, y entrenados de esta manera, pueden convertirse en perros muy agresivos y violentos.

Sin embargo, que los perros Pitbull fueran criados originalmente para la lucha no quiere decir que el comportamiento de un Pitbull vaya a ser agresivo de manera natural, o que esté destinado a este propósito. De hecho, los Pitbull son perros inteligentes y amables. Son fáciles de entrenar, ya que se muestran siempre deseosos de complacer a su dueño, y son perros obedientes. Precisamente por ello, si caen en manos de un dueño que lo entrene para pelear, lo harán sin dudarlo, de la misma manera que le traerían el periódico si fuesen adiestrados para ello.

Los perros Pitbull requieren un dueño responsable que les entrene adecuadamente, que tenga experiencia con perros de estas características y que sepa ser el macho alfa de la manada, situándose en la pirámide de la estructura jerárquica y no dejándose arrebatar este puesto. Si un Pitbull es entrenado adecuadamente, con firmeza pero con cariño, y tiene sus necesidades satisfechas, será un excelente compañero.

Why dividing my code into components lost perspective?

I would like to create flip card in angular, where checkbox will change the card side.
I divided this forms into two components: app-login-form and app-register-form.

<div class="form__container">
                <div class="form__object">
                    <app-login-form [isFormActive]="loginForm"></app-login-form>
                    
                    <app-register-form [isFormActive]="loginForm"></app-register-form>
                </div>
            </div>
.form__container{
    width: 95%;
    height: 75%;
    margin: 0 auto;
    border-radius: 7px;
    perspective: 600px;
}

.form__object{
    width: 100%;
    height: 100%;
    transform-style: preserve-3d;
    position: relative;
}

This is the code of components (they are similar at the beginning):

<form class="form" [class.form__inactive]="isFormActive" action="#" method="post" onsubmit="#" autocomplete="on">

</form>

And some css code to app-register-form component:

.form{
    width: 100%;
    height: 100%;
    position: absolute;
    transform: rotateY(180deg);
    transition-duration: 1s;
    backface-visibility: hidden;
    background-color: chocolate;
}

.form__inactive{
    transform: rotateY(360deg);
}

And obviously for app-login-form:

.form{
    width: 100%;
    height: 100%;
    position: absolute;
    transform: rotateY(0deg);
    transition-duration: 1s;
    backface-visibility: hidden;
    background-color: rgb(99, 85, 76);
}
.form__inactive{
    transform: rotateY(180deg);
}

When I wrote code from app-login-form and app-register-form into one component in container, I didn’t have any problems. But when I divided this into components, to handle code easier to maintain, I am loosing a perspective, and my small animation looks differently. Why it happened?

I can’t get my head around this JSON object?

I’ve been practicing with coingecko api & mongodb. I’m taking data from coingecko & saving it on to mongodb. But I’m stuck at this point how can i loop through this JSON data. The data is retrieved from https://api.coingecko.com/api/v3/simple/price/?ids=bitcoin,ethereum&vs_currency=usd where ‘ids’ parameter was passed using an array ‘quotes’ for composability in my code.

{
  bitcoin: {
    usd: 42658,
    usd_market_cap: 810587197433.8407,
    usd_24h_vol: 14543212536.010754
  },
  ethereum: {
    usd: 3248.93,
    usd_market_cap: 390462099892.2472,
    usd_24h_vol: 9905349820.688356
  }
}

It’s not wrapped around array notation but in a JSON notation. I wanted to do something like this with this data. To push it into a basic structured object to pass it to mongoose schema for saving it on mongodb.

$.map((e,i) => {
 temp.name: quotes[i],
 temp.usd: e.usd,
 temp.usd_market_cap: e.usd_market_cap,
 temp.usd_24h_vol: e.usd_24h_vol
// then from here it is directly send to the database to update...
})

Plz help me in solving this issue I have banged my head around every article but I can’t find anything related to this. Thanks in advance.

react (native) get state name via props

I am using react native and redux. Now I want to create a dynamic component, for example a dropdown component. I pass a state via props which works fine but to make this component re-usable I have to call the right dispatch function for this state. I am not sure if that is the right way to do. I am only working with react for a week now 😉

For the sake of simplicity a simple text field component:

import React, {Component} from 'react';
import {Button, StyleSheet, Text, TextInput, View} from 'react-native';
import allActions from '../../actions/allActions';
import {useDispatch, useSelector} from 'react-redux';

function Name (props) {
    const dispatch = useDispatch();
    const componentState = props.state;

    /**
     * Save the new user to the state
     * @param text
     */
    const handleChange = (text) => {
        // here I want to call the action dynamically
        // e.g. allActions.userActions.MY_VARIABLE_PASSED_THROUGH_PROPS
        dispatch(allActions.userActions.setUser(text));
    }
        return (
            <View>
                <TextInput
                    style={styles.input}
                    defaultValue={componentState}
                    onChangeText={handleChange}
                />
            </View>
        );
}

export default Name;

I pass the state when I instatiate the component

<Name state={ store.getState().user.name } action={my_action_to_call}/>

changing a document’s theme using multiple index files

I have a total of like 5 index.html files. They all have different index names and are linked to one JS file. When I click the button to change the theme of the index.html page. The theme changes to light theme and set in localStorage. The other pages are not changed. Can someone get me in the right direction. What am I doing wrong?

// Switch theme/add to local storage to all body elements in multiple .html files
const bodyElement = document.body
// Get the theme button via id
const themeToggleBtn = selectElement('#theme-toggle-btn');
//  passes the theme button to the toggleTheme function
const currentTheme = localStorage.getItem('currentTheme');

// checks if there is a current theme in local storage
if (currentTheme) {
    bodyElement.classList.add('light-theme');
}

//  event listener  btn is clicked the body element changes theme
themeToggleBtn.addEventListener('click', () => {
    bodyElement.classList.toggle('light-theme');

    //  checks if element has the class and sets it in local storage 
    if (bodyElement.classList.contains('light-theme')) {
        localStorage.setItem('currentTheme', 'themeActive');
        //  if not it removes it
    } else {
        localStorage.removeItem('currentTheme');
    }
});
    <script src="./assets/js/main.js"></script>

JS clientWidth returning 0 sometimes but working other times

I’m writing a program to change the positions of some subtitles. The user uploads a video, gets a thumbnail from the video, and then the editor shows up. A lot of the time, the clientWidth or clientHeight for the thumbnail just doesn’t work and it breaks the range sliders. If you refresh though, it sometimes starts working again. I have no idea what the problem is, some help would be much appreciated.

    example.style.left = width.value;
thumbWidth = thumb.clientWidth - example.clientWidth;
thumbHeight = thumb.clientHeight - example.clientHeight;
width.setAttribute('max', thumbWidth);
console.log(thumb.clientWidth);
width.setAttribute('value', thumbWidth / 2);
subWidth();
height.setAttribute('max', thumbHeight);
height.setAttribute('value', thumbHeight / 2);
subHeight();
width.style.width = thumb.clientWidth + 'px';
console.log(thumb.clientWidth);
height.style.width = thumb.clientHeight + 'px';
editor.style.width = thumb.clientWidth = 'px';
editor.style.height = thumb.clientHeight + 'px';

Here is the fiddle.

Btw, I am aware the vertical slider is very hardcoded, but I will fix it later.