React Native text input continues writing 0s

          <TextInput
            keyboardType="decimal-pad"
            placeholder="0"
            value={repetitions?.toString()}
            onChange={(e) => {
              if (e.nativeEvent.text && !isNaN(parseInt(e.nativeEvent.text)) && parseInt(e.nativeEvent.text) > 0) {
                setRepetitions(parseInt(e.nativeEvent.text));
              } else {
                setRepetitions(null);
              }
            }}
            style={createGoalStyle.numberInput}
            maxLength={3}
          />

If I receive a 0 (or multiple 0s) by the user I want the textinput to fallback to the placeholder but the textInput allows introducing zeros even when i’m setting repetitions to null, what is happening?

Chart.js does not group equal labels

I’m trying to create a time chart using Chart.js. Apparently it’s working, however I’m having difficulties with the labels that are not grouped when equal, I believed that Chart.js did this on its own but I see that it is not. Note that, in the image, there are two “Task 2”.

chart

const config = {
  type: 'bar',
  data: {
    labels: ['Task 2', 'Task 1', 'Task 3'],
    datasets: [
      {
        label: 'Task 2',
        data: [[0, 2], [0, 0], [0, 0]],
      },
      {
        label: 'Task 1',
        data: [[0, 0], [2, 5], [0, 0]]
      },
      {
        label: 'Task 3',
        data: [[0, 0], [0, 0], [5, 7]]
      },
      {
        label: 'Task 2',
        data: [[7, 9], [0, 0], [0, 0]],
      },
    ]
  },
  options: {
    responsive: true,
    indexAxis: 'y',
    scales: {
      x: {
        beginAtZero: true,
        ticks: {
          stepSize: 1
        }
      }
    }
  }
};

new Chart(document.getElementById('myChart'), config);

My question is if I mapped the data wrong or if it is a chartjs limitation.

Discord.js Bot doesnt allow my command to run, ping works though

Here is my code I am using Discord.js and the weather API I have my config.json and my index in a seperate file

const { Client, SlashCommandBuilder, MessageEmbed } = require('discord.js');
const { WEATHER_API_KEY, GIPHY_API_KEY } = require('../config.json')
const axios = require('axios');

// TODO: const giphyurl = `https://api.giphy.com/v1/gifs/random?api_key=${GIPHY_API_KEY}&tag=${encodeURIComponent(query)}`;

module.exports = {
    data: new SlashCommandBuilder()
        .setName('weather')
        .setDescription('View the weather for your chosen area')
    .addStringOption(option => option.setName('zipcode').setDescription('The zipcode you want to see the weather from')),
    async execute(interaction, MessageEmbed) {
    console.log(interaction.options)
    const zipcode = interaction.options.getString('zipcode');
    //*const zipcode = interaction.options.get('zipcode').value;
        //const zipcode = interaction.options.getString('zipcode') ?? "no zipcode provided";
        axios.get(`https://api.openweathermap.org/data/2.5/weather?zip=${zipcode}&units=metric&appid=${WEATHER_API_KEY}`).then(response => {
      const apiData = response;
      const currentTemp = Math.ceil(apiData.data.main.temp)
      const wind = apiData.data.wind.speed;
      const icon = apiData.data.weather[0].icon
      const country = apiData.data.sys.country
      const cloudness = apiData.data.weather[0].description;
      const { pressure, humidity, temp_max, temp_min  } = response.data.main;

      //*const weatherEmbed = new EmbedBuilder()
      const weatherEmbed = new MessageEmbed()
        .setColor("0xd1e1fa")
        .setTitle(`The temperature is currently ${currentTemp}u00B0C in ${zipcode}, ${country}`)
        .addFields(
            { name: `Maximum Temperature:`, value: `${temp_max}u00B0C`, inline: true },
            { name: `Minimum Temperature:`, value: `${temp_min}u00B0C`, inline: true },
            { name: `Humidity:`, value: `${humidity} %`, inline: true },
            { name: `Wind Speed:`, value: `${wind} m/s`, inline: true },
            { name: `Pressure:`, value: `${pressure} hpa`, inline: true },
            { name: `Cloudiness:`, value: `${cloudness}`, inline: true },
        )
        .setThumbnail(`http://openweathermap.org/img/w/${icon}.png`)
        .setFooter('Requested by ' + interaction.user.username);
                          
          interaction.reply({ embeds: [weatherEmbed] })
      }).catch(err => {
        interaction.reply(`Please enter a valid zipcode`)
      })
    },
};

here is my error

{
  intents: IntentsBitField { bitfield: 1 },
  rest: {
    userAgentAppendix: 'discord.js/14.11.0 Node.js/v20.3.1',
    agent: Agent {
      _events: [Object: null prototype] {},
      _eventsCount: 0,
      _maxListeners: undefined,
      [Symbol(kCapture)]: false,
      [Symbol(destroyed)]: false,
      [Symbol(onDestroyed)]: null,
      [Symbol(closed)]: false,
      [Symbol(onClosed)]: [],
      [Symbol(dispatch interceptors)]: [Array],
      [Symbol(options)]: [Object],
      [Symbol(maxRedirections)]: 0,
      [Symbol(factory)]: [Function: defaultFactory],
      [Symbol(clients)]: [Map],
      [Symbol(finalizer)]: FinalizationRegistry {},
      [Symbol(onDrain)]: [Function (anonymous)],
      [Symbol(onConnect)]: [Function (anonymous)],
      [Symbol(onDisconnect)]: [Function (anonymous)],
      [Symbol(onConnectionError)]: [Function (anonymous)],
      [Symbol(Intercepted Dispatch)]: [Function: Intercept]
    },
    api: 'https://discord.com/api',
    authPrefix: 'Bot',
    cdn: 'https://cdn.discordapp.com',
    headers: {},
    invalidRequestWarningInterval: 0,
    globalRequestsPerSecond: 50,
    offset: 50,
    rejectOnRateLimit: null,
    retries: 3,
    timeout: 15000,
    version: '10',
    hashSweepInterval: 14400000,
    hashLifetime: 86400000,
    handlerSweepInterval: 3600000
  },
  closeTimeout: 5000,
  waitGuildTimeout: 15000,
  shardCount: 1,
  makeCache: [Function (anonymous)],
  partials: [],
  failIfNotExists: true,
  presence: { status: 'online', user: { id: null } },
  sweepers: { threads: { interval: 3600, lifetime: 14400 } },
  ws: {
    large_threshold: 50,
    version: 10,
    presence: { activities: [], afk: false, since: null, status: 'online' }
  },
  jsonTransformer: [Function: toSnakeCase],
  shards: [ 0 ]
}
TypeError: interaction.options.getString is not a function
    at Object.execute (/Users/commands/feather.js:14:41)
    at Client.<anonymous> index.js:43:23)
    at Client.emit (node:events:511:28)
    at InteractionCreateAction.handle node_modules/discord.js/src/client/actions/InteractionCreate.js:97:12)
    at module.exports [as INTERACTION_CREATE] /node_modules/discord.js/src/client/websocket/handlers/INTERACTION_CREATE.js:4:36)
    at WebSocketManager.handlePacket node_modules/discord.js/src/client/websocket/WebSocketManager.js:354:31)
    at WebSocketManager.<anonymous> node_modules/discord.js/src/client/websocket/WebSocketManager.js:238:12)
    at WebSocketManager.emit node_modules/@vladfrangu/async_event_emitter/dist/index.js:282:31)
    at WebSocketShard.<anonymous> node_modules/@discordjs/ws/dist/index.js:1103:51)
    at WebSocketShard.emit node_modules/@vladfrangu/async_event_emitter/dist/index.js:282:31)

I am completely stumped any help would be great!
I have used interaction.options.getString(‘zipcode’) and interaction.options.get(‘zipcode’).value to retrieve the value of the zipcode option, neither have worked. I am trying to have the bot pull weather from the API using the provided zip code

How to handle checkbox change in React.js?

I’m trying to handle change of the value when a check box is clicked. The component loads a response like this:

[
   {
       "id_ver_group": 7,
       "checklist": [
           {
            "check": "Custom ver 1",
            "valor": false,
            "opcional": true
           },
        {
            "check": "Custom ver 2",
            "valor": false,
            "opcional": false
        }
       ],
       "id_ver_group_char": "7",
       "fecha_crea": "2023-07-02T18:07:56.756521"
  },
  {
       "id_ver_group": 6,
       "checklist": [
           {
               "check": "Custom ver 1",
               "valor": false,
               "opcional": true
           },
           {
               "check": "Custom ver 2",
               "valor": false,
               "opcional": false
           },
       ],
       "id_ver_group_char": "7",
       "fecha_crea": "2023-07-02T18:07:56.756521"
  },
]

The response is grouped by “id_ver_group” in an “Accordion” tag where each “checklist” item is displayed in a table, its columns are: “verify” (string), “value” (bool) and “optional ” (bool) , the checkbox tag is used to display the “value” and “optional” columns, the latter being read-only.
This is the component code:

// imports...
import {
  Accordion,
  AccordionSummary,
  AccordionDetails,
  Typography,
  Table,
  TableHead,
  TableBody,
  TableRow,
  TableCell,
  Checkbox,
  Select,
  InputLabel,
  Button,
} from '@material-ui/core'

export function AddEditChecklist(props) {
     
const { Tanques, onClose, onRefetch } = props
const { Successful, errores } = alertas()
const { Data, getBaseVer } = useVerificaciones()
const { addTankVer, updateTankVer } = useTanques()
const { OperadorDB, getOperadorDB } = useOperador()
const [selectedOperator, setSelectedOperator] = useState('');
const [isOperatorSelected, setIsOperatorSelected] = useState(true);

const [selectedGroup, setSelectedGroup] = useState(null);
  const [selectedGroupIndex, setSelectedGroupIndex] = useState(null);

  useEffect(() => {
    getOperadorDB()
    getBaseVer()
  }, []);

  const [data, setData] = useState([]);

  useEffect(() => {
    setData(Data?.map(item => ({
      ...item,
      checklist: item.checklist.map(checklistItem => ({
        ...checklistItem,
        valor: false  
      }))
    })) || []);
  }, [OperadorDB, Data]);

  const handleAccordionChange = (groupId) => {
    setSelectedGroupIndex(groupId); 
    setSelectedGroup(groupId)
    
    if (selectedGroup === groupId) {
      setSelectedGroup(null); 
    } else {
      setSelectedGroup(groupId); 
    }
  };

// check box handle
  const handleCheckboxChange = (groupId, itemIndex, checklistItem) => {
    setData((prevData) => {
      const updatedData = [...prevData];
      const groupData = updatedData[groupId];

      if (groupData && groupData[itemIndex]) {
        checklistItem.valor = !checklistItem.valor; 
      }

      return updatedData;
    });
  };

  // group data by id
  const groupedData = data ? data.reduce((groups, item) => {
    const groupId = item.id_ver_group;
    if (!groups[groupId]) {
      groups[groupId] = [];
    }
    groups[groupId].push(item);
    return groups;
  }, {}) : {};
// handleSubmit...

return (
    <>
      {/* checklist */}
      {Object.keys(groupedData).map((groupId) => (
        <Accordion
          key={groupId}
          expanded={selectedGroup === groupId}
          onChange={() => handleAccordionChange(groupId)}
        >
          <AccordionSummary expandIcon={<ExpandMoreIcon />}>
            <Typography variant="h6">Conjunto de verificaciones # {groupId}</Typography>
          </AccordionSummary>
          <AccordionDetails>
            <div>
              {groupedData[groupId].map((item, index) => (
                <div key={item.id_ver_group}>
                  <Table>
                    <TableHead>
                      <TableRow>
                        <TableCell><strong>Verificación</strong></TableCell>
                        <TableCell><strong>¿Cumple?</strong></TableCell>
                        <TableCell><strong>¿Opcional? (no modificable)</strong></TableCell>
                      </TableRow>
                    </TableHead>
                    {item.checklist.map((checklistItem) => (
                      <TableBody key={checklistItem.check}>
                        <TableRow>
                          <TableCell>
                            {checklistItem.check}
                          </TableCell>
                          <TableCell>
                            <Checkbox
                              checked={checklistItem.valor}
                              name={checklistItem.check}
                              onChange={() => handleCheckboxChange(groupId, index, checklistItem)}
                            />
                          </TableCell>
                          <TableCell>
                            <Checkbox
                              readOnly
                              checked={checklistItem.opcional}
                              name={checklistItem.check}
                            />
                          </TableCell>
                        </TableRow>
                      </TableBody>
                    ))}
                  </Table>
                </div>
              ))}
            </div>
          </AccordionDetails>
        </Accordion>
      ))}
      <br></br>
      <Divider></Divider>
      <br></br>
      <Button variant="contained" color="primary" onClick={handleSubmit}>
        Save
      </Button>
    </>
  )
} 

Doing some research, I was able to come up with something to handle the checkbox changing, but the checkbox doesn’t change its value when clicked. I really don’t know how to solve this. Any help is appreciated.

cant work out how to use .focus in my assignment

https://codepen.io/Awolozzie/pen/VwVWXdJ

I have 2 days left to work this out and only 1 attempt I need to fix this code to use .focus for the error messages in the innerhtml.

any help would be great

I have tried this as well as many different options but feel i have gone wrong from the beginning I am an external student and the lecturers have been of no help, more worried about the in-class students

    if (validateEmail(email)) {
        errorMsg.textContent = '';
        emailInput.classList.remove('error');
        // Do something with the valid email address
      } else {
        errorMsg.textContent = 'Invalid email address.';
        emailInput.classList.add('error');
        emailInput.focus();
      }
    });

    function validateEmail(email) {
      const regex = /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$/;
      return regex.test(email);

Is there a way to have images in a folder automatically added to a html site?

So basically, i was wondering if there is any possible way to have someone upload an image to a folder then the site will auto add the photo to a specific place with the css that is set on all the others. I would prefer if i could do it in just javascript and or html/css but if i cannot that will be fine as well.

The reason i want to do this is im making a site for a person who isn’t very in depth with coding so i wanted to make this as simple as possible for them so i can just step away and move on.

I tried looking online, however i couldnt find anything on it so i thought id ask if its even possible here.

Apollo GraphQL Error expected ” ] ” found ” : “

Hey I’m getting an error when I run my app. it is GraphQLError: Syntax Error: Expected "]", found ":".
At the bottom of the stack trace it has path: undefined, [0] locations: [ { line: 12, column: 17 } ],

Here’s my typeDefs.js

const { gql } = require("apollo-server-express");

const typeDefs = gql`
  type User {
    _id: ID
    firstName: String
    lastName: String
    email: String
  }

  type Metric {
    _id: ID
    name: String
    labels: [key: String!, value: String!]
    values: [value: Number!, timestamp: Date!]
  }

  type Auth {
    token: ID
    user: User
  }

  type Query {
    user: User
    userById(userId: ID): User
    metric(metricId: ID): Metric
    metrics: [Metric]!
  }

  type Mutation {
    addUser(
      firstName: String!
      lastName: String!
      email: String!
      password: String!
    ): Auth
    updateUser(firstName: String, lastName: String, email: String): User
    login(email: String!, password: String!): Auth
    addMetric(
      name: String!
      labels: [key: String!, value: String!]
      values: [value: Number!, timestamp: Date!]
      ): Metric
  }
`;

module.exports = typeDefs;

Here’s my Model for metrics as i’m assuming it has something to do with how im setting up the arrays in graphql, maybe this will help!

const mongoose = require("mongoose");

const { Schema } = mongoose;

const metricsSchema = new Schema({
  name: {
    type: String,
    required: true,
  },
  labels: [
    {
      key: {
        type: String,
        required: true,
      },
      value: {
        type: String,
        required: true,
      },
    },
  ],
  values: [
    {
      value: {
        type: Number,
        required: true,
      },
      timestamp: {
        type: Date,
        default: Date.now,
        required: true,
      },
    },
  ],
});

const Metrics = mongoose.model("Metrics", metricsSchema);
module.exports = Metrics;

Thanks..

I tried changing how the arrays are wrote in the typeDefs and could not get past this error.

How can I focus a TextInput after it has loaded in an efficient way?

I want to be able to focus the TextInput after it has mounted and I’ve had a couple of solutions for this but sadly none of them works

  • autoFocus prop: causes navigation issues
  • using ref to focus
<ScreenWrapper
 onEntryTransitionEnd={() => inputRef.focus()}
 >
  <TextInput
    ref={(el) => inputRef.current = el}
  >
  

This doesn’t focus the TextInput if I reload the page. I believe by the time focus is called, TextInput hasn’t mounted

  • ref plus useEffect

Basically the same as above but I added a hook to run on change in ref.current

useEffect(() => {
   if(inputRef.current) inputRef.current.focus();
}, [inputRef.current])

This worked perfectly but react recommends against the use of refs as dependents

How can I achieve this efficiently?

I also tried setting a state when I set the ref value in TextInput. And then using an effect hook on that state, but it shows similar results as autoFocus, causing navigation transition issues

React Component isn’t getting the data from useEffect

Overview

I’m a newer developer building a facebook clone and I’m having trouble with a React component not rendering information from a useEffect hook. The component has arrays mapped onto it and it’s called Conversation.The component is supposed to return the profile picture and name of your friend, so you can click on it and open up the SMS chat. The Conversation component recieves an array that contains the user id’s of two individuals, as well as the current user that is logged in. The use effect hook checks that array to figure out which ID doesn’t belong to the current logged in user and then uses an async function to get the friends data and then sets it as state. It fetches the data using a react component called makeRequest which just shortens the base URL

The problem I’m having is that it seems like the useEffect hook is taking to long to fetch the data, so when the component renders, the state hasn’t been changed from its starting null

TypeError: Cannot read properties of null (reading ‘profilePic’)”

it has no problem returning the friends name, but their profile pictures won’t load.

Conversation Component

import { useEffect, useState } from "react";
import { makeRequest } from "../../axios";
import { AuthContext } from "../../context/authContext";
import { useContext } from "react";

const Conversation = ({ conversation, currentUser }) => {
  const [user, setUser] = useState(null);

  useEffect(() => {
    const friendId = conversation.find((m) => m !== currentUser.id);

    //get ID's of friends you have conversations with
    const getUser = async () => {
      try {
        const res = await makeRequest.get("/users/find/" + friendId);
          setUser(res.data);
      } catch (err) {
        console.log(err);
      }
    };
    getUser();
  }, [currentUser, conversation]);

  return (
    <div className="conversation">
      <img src={"/upload/" + user.profilePic} alt="" />
      <span>{user?.name}</span>
    </div>
  );
};

export default Conversation;

makeRequest Component

import axios from "axios";

export const makeRequest = axios.create({
  baseURL: "http://localhost:8800/api/",
  withCredentials: true,
});

[enter image description here](https://i.stack.imgur.com/6sd0M.png)

I’ve console logged the user in the useEffect hook and it is able to find all of the users information. I tried to change the img src to a URL and everything works fine and that’s what is attached in the image. I know I have my directories right so I’m wondering if there are caviots to using an async function in useEffect. I’ve dont this other places in my application and haven’t had issues.

Hull Moving Average in Javascript

I’m trying to calculate the Hull Moving Average and I can’t seem to figure out where i’m going wrong. I’ve consulted many guides online and I am pretty sure the formula is correct but i keep getting way too low number.

Here is the relevant code:

weighted(list, num) {
    let total = 0;
    let weightTotal = 0;
    let weight = 1;
    let x = 0;
    while (x < num){
        total += (list[x] * weight);
        weightTotal += weight;
        weight++;
        x++
    };
    return total / weightTotal;
};

hull(list, num) {
    let subList = list.slice(0, num);
    let half = Math.ceil(subList.length / 2);
    let recentHalf = subList.slice(0, half);
    let recent = this.weighted(recentHalf, recentHalf.length);
    let whole = this.weighted(subList, subList.length);
    let rough = ((2 * recent) - whole);
    let HMA = rough / Math.sqrt(subList.length);
    return HMA;
};

};

I tried to find the HMA for JPM stock and was just getting numbers in the 30s when then price is much higher.

Error: “The provided key element does not match the schema” in DynamoDB batchWrite operation

I’m facing an issue with the batchWrite operation in AWS DynamoDB. When I attempt to insert multiple items into a DynamoDB table using the following code snippet, I receive the error message: “The provided key element does not match the schema”.

module.exports.saveToDynamoDB = async (myData) => {
  const tableName = process.env.MY_TABLE;

  const putRequests = myData.map((data) => ({
    PutRequest: {
      Item: AWS.DynamoDB.Converter.marshall(data),
    },
  }));

  const params = {
    RequestItems: {
      [tableName]: putRequests,
    },
  };

  try {
    await dynamoDb.batchWrite(params).promise();

    return {
      status: 'SUCCESS',
      message: `${myData.length} data saved to the database`,
    };

  } catch (error) {
    throw new Error(error.message);
  }
};

Could someone please help me understand how I can use the marshall() function correctly to ensure DynamoDB-friendly notation for numeric values?

The AWS.DynamoDB.Converter.marshall() function appears to treat numeric values as strings and wraps them with quotation marks. This results in the mentioned error.

For example when myData is:

[
    {
        "id": 1,
        "name": "first",
        "rating": 100
    },
    {
        "id": 2,
        "name": "second",
        "rating": 99
    }
]

I get this:

{
  "RequestItems": {
    "myTable": [
      {
        "PutRequest": {
          "Item": {
            "id": {
              "N": "1"
            },
            "name": {
              "S": "first"
            },
            "rating": {
              "N": "100"
            }
          }
        }
      },
      {
        "PutRequest": {
          "Item": {
            "id": {
              "N": "2"
            },
            "name": {
              "S": "second"
            },
            "rating": {
              "N": "99"
            }
          }
        }
      }
    ]
  }
}

instead of having something like "N": 1.

Toggle button showing/hiding multiple elements with display none and block

Please help, I want the toggle button to only show and hide the paragraphs but the other contents inside the div remains visible. Also, the css is the same and I am trying to smoothen the transition of the div‘s height when showing and hiding the paragraphs

<button class="toggleButton">Toggle 1</button>
<div>
  HI <p class="paragraph hidden">Paragraph 1.</p>
</div>

<button class="toggleButton">Toggle 2</button>
<div> Hi
  <p class="paragraph hidden">Paragraph 2.</p>
</div>

<button class="toggleButton">Toggle 3</button>
<div> Hi
  <p class="paragraph hidden">Paragraph 3.</p>
</div>
  height: 0;
  overflow: hidden;
  transition: height 0.5s;
  background: blue;
}

.paragraph {
  opacity: 0;
  transition: opacity 0.5s;
}

.visible {
  opacity: 1;
  display: block;
}

.hidden {
  opacity: 0;
  display: none;
}
const divs = document.querySelectorAll('div');
const paragraphs = document.querySelectorAll('.paragraph');

toggleButtons.forEach((button, index) => {
  button.addEventListener('click', () => {
    const paragraph = paragraphs[index];
    paragraph.classList.toggle('hidden');
    paragraph.classList.toggle('visible');
    
    if (paragraph.classList.contains('visible')) {
      divs[index].style.height = paragraph.scrollHeight + 'px';
    } else {
      divs[index].style.height = '0';
    }
  });
});

Where to specify env in new ESLint config system?

ESLint introduced a new config system in 2022, outlined here

Docs for new config system |
Docs for old config system

I am using the new system and as you can see from the docs, the eslint.config.js file does not have an “env” key where you can specify the environment to give context to your linter (eg. “node”, “browser” etc). This was simple in the “old” config system (eg. using .eslintrc.js or similar.

Without specifying the env as “node”, I would have to manually add all node global variables like… Surely I am missing something?

eslint.config.js

module.exports [
    {
        files: ["**/*.js"],
        languageOptions: {
            globals: {
                console: "writable",
                __dirname: "readable",
                __filename: "readable",
                process: "readable",
                <more global variables here>
            }
        },
        rules: {
            // your rules here
        }
    }
]

Trying to use Javascript libraries for my web page, can’t understand how to load them in

I am trying to create a basic webpage that connects to my MongoDB cluster and adds to the webpage based on the return. The actual scripting hasn’t been an issue, but for the life of me I can’t understand how to properly load in the library for it to work. I am new to web development, but I also might just be dense. Thanks for your help!

My HTML is like this:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>MRE</title>
    <link rel="stylesheet" href="styles.css">
    <script src="script.js"></script>
</head>
<body>
    <div class="container">
        <div>Header</div>
    </div>
</body>
</html>

and with the line: import { MongoClient } from 'mongodb'
I get the error:
Uncaught SyntaxError: Cannot use import statement outside a module (at script.js:1:1)