My nodejs request doesnt work, what am i missing?

I am writting a Node.js console application that , receives an excel sheet, gets the values of a column, then with those values i call a Google Maps Geocode request to get the Latitude and Longitude, save it and add new columns to the excel sheet.

I have those two archives

const ExcelJS = require('exceljs');

// Ler o Excel existente e pegar os ceps

const wb = new ExcelJS.Workbook();

const fileName = 'NovoExcel.xlsx';

var ceps = [];


wb.xlsx.readFile(fileName).then(() => {
    
    const ws = wb.getWorksheet('Planilha1');

    const c1 = ws.getColumn(1);
    
    c1.eachCell(c => {

        ceps.push(c.value);
    });

    console.log(ceps);

    var mapsFunc =require("./maps")

    var coordenadas = mapsFunc(ceps);

    console.log(coordenadas)


}).catch(err => {
    console.log(err.message);
});

Thats the other archive which calls the Api

const {Client} = require("@googlemaps/google-maps-services-js");
var maps = function(ceps){
  
var Latitude = [];
var Longitude = [];

ceps.forEach(element => {
    

const args = {
  params: {
    key: 'AIzaSyA5_Hox6vhpLt3kRpqxr_0eXBUssHIva7g',
    address: element + ' br ',
  }
};
const client = new Client();
client.geocode(args).then(gcResponse => {
  Latitude.push(gcResponse.data.results[0].geometry.location.lat)
  Longitude.push(gcResponse.data.results[0].geometry.location.lng)
  console.log(Latitude)
});

});

return [Latitude,Longitude]

}

module.exports = maps;

Callstack

I dont understand why it calls the console.log thats the answer of the function i call before it calls the actual function, what am i missing?

populating seed data from a join table javascript

I have seed data for agents, listings and potential buyers for migration files using knex. I created a join table called listingsBuyers referencing the foreign key for listings and buyers. Is there a way to seed a join table referencing the the foreign key for listings and buyers? The way it is set up below is giving an error listing not defined.

exports.up = function(knex) {
    return knex.schema.createTable('listings', table =>{
        table.increments()
        table.string('address')
        table.integer('agent_id')
        table.foreign('agent_id').references('agents.id')
    })
};

exports.down = function(knex) {
    return knex.schema
        .dropTable('listings')
};
exports.up = function(knex) {
    return knex.schema.createTable('buyers', table =>{
        table.increments()
        table.string('name')
        table.integer('listing_id')
        table.foreign('listing_id').references('listings.id')
    })
};

exports.down = function(knex) {
    return knex.schema
        .dropTable('buyers')
};

this is the join table

exports.up = function(knex) {
    return knex.schema.createTable('listingsBuyers', table =>{
        table.increments()
        table.integer('listing_id')
        table.foreign('listing_id').references('listings.id')
        table.integer('buyer_id')
        table.foreign('buyer_id').references('buyers.id')
    })
};

exports.down = function(knex) {
    return knex.schema
        .dropTable('listingsBuyers')
};

the seed file

exports.seed = function(knex) {
  return knex('listingsBuyers').alter([
    {listing_id: listings.id , buyer_id: buyers.id},
    //{listing_id: 2, buyer_id: 1},
    //{listing_id: 3, buyer_id: 3}
  ])
  .then(() =>{//set the value for auto-incrementing
    return knex.raw(`SELECT setval('listingsBuyers_id_seq', (SELECT MAX(id) FROM listingsBuyers))`)
  });
};

Mapping array values in javascript object with fixed keys

I want to create a javascript object such as below :

{
   {
    "Image" :  img_src,
    "Text" :   text
    },

}

I have two arrays

img_src = [ value1, value2, value3 ....... ]
text = [ text1, text2, text3 .......]

I want to map the values of these arrays in that object such that values of img_src is placed next to key “Image” and values of text is places next to key “Text” in the following manner:

{
   {
     "Image" : value1,
     "Text" : text1
   },
  {
     "Image" : value2,
     "Text" : text2
   },
  {
     "Image" : value3,
     "Text" : text3
   } 
}

and so on. I tried reading javascript documentation and tried all sort of things but I am unable to come up with a solution. Could someone kindly explain how can I achieve this? Thank you

I tried reading javascript documentation and tried all sort of things but I am unable to come up with a solution. Could someone kindly explain how can I achieve this? Thank you

sum of textboxes with javascript and using comma instead of dot in decimal numbers

I found a code block on the web that does the sum of textboxes. This block of code looked exactly what I was looking for, but I need to use commas instead of dots, and I even need to prevent the entry of periods in textboxes. unfortunately my javascript knowledge is very amateur and i don’t know how to do this. can you help me with this
thanks

<html>
    <head>
        <title>Sum Html Textbox Values using jQuery/JavaScript</title>
        <style>
            body {
                font-family: sans-serif;
            }
            #summation {
                font-size: 18px;
                font-weight: bold;
                color:#174C68;
            }
            .txt {
                background-color: #FEFFB0;
                font-weight: bold;
                text-align: right;
            }
        </style>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    </head>
    <body>
<table width="300px" border="1" style="border-collapse:collapse;background-color:#E8DCFF">
    <tr>
        <td width="40px">1</td>
        <td>Butter</td>
        <td><input class="txt" type="text" name="txt"/></td>
    </tr>
    <tr>
        <td>2</td>
        <td>Cheese</td>
        <td><input class="txt" type="text" name="txt"/></td>
    </tr>
    <tr>
        <td>3</td>
        <td>Eggs</td>
        <td><input class="txt" type="text" name="txt"/></td>
    </tr>
    <tr>
        <td>4</td>
        <td>Milk</td>
        <td><input class="txt" type="text" name="txt"/></td>
    </tr>
    <tr>
        <td>5</td>
        <td>Bread</td>
        <td><input class="txt" type="text" name="txt"/></td>
    </tr>
    <tr>
        <td>6</td>
        <td>Soap</td>
        <td><input class="txt" type="text" name="txt"/></td>
    </tr>
    <tr id="summation">
        <td>&nbsp;</td>
        <td align="right">Sum :</td>
        <td align="center"><span id="sum">0</span></td>
    </tr>
</table>
<script>
    $(document).ready(function(){
 
        //iterate through each textboxes and add keyup
        //handler to trigger sum event
        $(".txt").each(function() {
 
            $(this).keyup(function(){
                calculateSum();
            });
        });
 
    });
 
    function calculateSum() {
 
        var sum = 0;
        //iterate through each textboxes and add the values
        $(".txt").each(function() {
 
            //add only if the value is number
            if(!isNaN(this.value) && this.value.length!=0) {
                sum += parseFloat(this.value);
            }
 
        });
        //.toFixed() method will roundoff the final sum to 2 decimal places
        $("#sum").html(sum.toFixed(2));
    }
</script>

jsfiddle link

WKWebView keeps reloading its content when copying text to Clipboard in iPhone

I’m using WKWebView to load a HTML-based string. One of requirements is to be able to copy certain elements to clipboard. I tried a few options. All of them have refresh issues. When the user clicks the link, it will copy the text but the screen always flashes once. It was like that WKWebView is trying to reload the whole page again.

Here are my codes:

let htmlContent = """

 <!doctype html>

     <html>

       <head>

 <script>

 function newcopySectionText(event) {

          // Save the current scroll position

          var link = event.target;

          var section = event.target.parentNode;

          var sectionText = section.innerText.trim().replace(link.innerText.trim(), '');

          var temp = document.createElement("textarea");

          temp.style.position = "fixed";

          temp.style.left = "-9999px";

          temp.style.top = "-9999px";

          temp.value = sectionText;

          document.body.appendChild(temp);

          temp.select();

          document.execCommand("copy");

          document.body.removeChild(temp);

          link.classList.remove("original-link");

          link.classList.add("copied-link");

 }

 </script>

 </head>

 

 <body>

 <div> texts to be copied.

 <a href='#' onclick='newcopySectionText(event)' class='original-link'> copy texts</a>

 </div>

 </body>

 """

 let webConfiguration = WKWebViewConfiguration()

 webConfiguration.applicationNameForUserAgent = "Chrome"

 webConfiguration.websiteDataStore = WKWebsiteDataStore.default()

 

 let contentTextView = WKWebView(frame: .zero, configuration: webConfiguration) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.0 Mobile/15E148 Safari/604.1";

 contentTextView.customUserAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 16_3_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.3 Mobile/15E148 Safari/604.1";

 contentTextView.navigationDelegate = self

 contentTextView.loadHTMLString(htmlContent, baseURL: nil)

Tried multiple suggestions from stackoverflow and apple guides. Also tried ChatGPT. Couldn’t find the solution. Please help.

Invalid Hook Call Error when using Material UI in ReactJS Web App

Context: This page uses ReactJS to list a series of cards (rows) with information about people (screenshot below). Each one of these cards has a “Details” button that would expand into a pop-up modal (Material UI) that displays more information about the person.

Page Screenshot

Problem: Whenever the “Details” button is clicked, I am being prompted with the following error. The button calls the “DetailedModal” function below “TutorCard” function, located in the same file.
Invalid Hook Error. I believe that this could be either (1) or (3) as suggested by the error above.

Code:

import React from "react";
// import {ExpandedTutorCard} from "./ExpandedTutorCard.js"
import Button  from '@mui/material/Button';
// import ExpandedTutorCard from "./ExpandedTutorCard.js";
import PropTypes from 'prop-types';
import { styled } from '@mui/material/styles';
import Dialog from '@mui/material/Dialog';
import DialogTitle from '@mui/material/DialogTitle';
import DialogContent from '@mui/material/DialogContent';
import DialogActions from '@mui/material/DialogActions';
import IconButton from '@mui/material/IconButton';
import CloseIcon from '@mui/icons-material/Close';
import Typography from '@mui/material/Typography';

 function TutorCard({ first_name, last_name, grade, subject}) {
    return (
        <div className="md:flex bg-white shadow text-gray-800 my-4 py-4 px-10 rounded-md items-center justify-between hover:bg-gray-300"  >
            {/* <img
                style={{ maxWidth: "60px"}}
                className="rounded-full shadow-md border border-gray-300"
                src={image}
                alt="employee"
            /> */}
            <p className="font text-md" style={{ color: 'black', textAlign: "center"}}>{first_name}</p>
            <p className="font text-md" style={{ color: 'black', textAlign: "center" }}>{last_name}</p>
            <p style={{ color: 'black', textAlign: "center" }}>{grade}</p>
            <p style={{ color: 'black', textAlign: "center" }}>{subject}</p>
            <Button onClick={DetailedModal}> Details </Button> //Calls "DetailedModal"
        </div>
    )
}


const BootstrapDialog = styled(Dialog)(({ theme }) => ({
  '& .MuiDialogContent-root': {
    padding: theme.spacing(2),
  },
  '& .MuiDialogActions-root': {
    padding: theme.spacing(1),
  },
}));

function BootstrapDialogTitle(props) {
  const { children, onClose, ...other } = props;

  return (
    <DialogTitle sx={{ m: 0, p: 2 }} {...other}>
      {children}
      {onClose ? (
        <IconButton
          aria-label="close"
          onClick={onClose}
          sx={{
            position: 'absolute',
            right: 8,
            top: 8,
            color: (theme) => theme.palette.grey[500],
          }}
        >
          <CloseIcon />
        </IconButton>
      ) : null}
    </DialogTitle>
  );
}

BootstrapDialogTitle.propTypes = {
  children: PropTypes.node,
  onClose: PropTypes.func.isRequired,
};

function DetailedModal() { //called when "Details" button
  const [open, setOpen] = React.useState(false);

  const handleClickOpen = () => {
    setOpen(true);
  };
  const handleClose = () => {
    setOpen(false);
  };

  return (
    <div>
      <Button variant="outlined" onClick={handleClickOpen}>
        Open dialog
      </Button>
      <BootstrapDialog
        onClose={handleClose}
        aria-labelledby="customized-dialog-title"
        open={open}
      >
        <BootstrapDialogTitle id="customized-dialog-title" onClose={handleClose}>
          Modal title
        </BootstrapDialogTitle>
        <DialogContent dividers>
          <Typography gutterBottom>
            Cras mattis consectetur purus sit amet fermentum. Cras justo odio,
            dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac
            consectetur ac, vestibulum at eros.
          </Typography>
          <Typography gutterBottom>
            Praesent commodo cursus magna, vel scelerisque nisl consectetur et.
            Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.
          </Typography>
          <Typography gutterBottom>
            Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus
            magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec
            ullamcorper nulla non metus auctor fringilla.
          </Typography>
        </DialogContent>
        <DialogActions>
          <Button autoFocus onClick={handleClose}>
            Save changes
          </Button>
        </DialogActions>
      </BootstrapDialog>
    </div>
  );
}

export default TutorCard;

Package.json:

{
  "name": "tutors-information",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@emotion/react": "^11.10.6",
    "@emotion/styled": "^11.10.6",
    "@fortawesome/fontawesome-svg-core": "^6.4.0",
    "@fortawesome/free-regular-svg-icons": "^6.4.0",
    "@fortawesome/free-solid-svg-icons": "^6.4.0",
    "@fortawesome/react-fontawesome": "^0.2.0",
    "@mui/icons-material": "^5.11.16",
    "@mui/material": "^5.12.2",
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "@trimbleinc/modus-react-bootstrap": "^1.2.0",
    "@types/react": "^18.0.35",
    "@types/react-dom": "^18.0.11",
    "axios": "^1.3.6",
    "mdb-react-ui-kit": "^6.0.0",
    "react": ">=16.8.0",
    "react-axios": "^2.0.6",
    "react-dom": ">=16.8.0",
    "react-icons": "^4.8.0",
    "react-router-dom": "^6.10.0",
    "react-scripts": "^2.1.3",
    "tailwindcss": "^3.3.1",
    "u": "^0.1.0",
    "uid": "^2.0.2",
    "web-vitals": "^2.1.4"
  },
  "peerDependencies": {
    "react": ">=16.8.0",
    "react-dom": ">=16.8.0"
  },
  "scripts": {
    "start": "set PORT=3008 && react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "@expo/webpack-config": "^18.0.4"
  }
}

I had already tried implementing the workarounds found on almost every other StackOverFlow question for this error, however none of it seems to resolve the issue.

Why is .remove() not removing the object from array?

In this project, a keyboard-arrow controlled cat walks over mice and causes them to disappear.

Main.js

Index.html

Style.css

Screenshot of app in browser

The mice are successfully disappearing within the browser window, however, when I console log the “mice” array, the mouse objects are not disappearing from the array; there remains 7 objects.
However, I want to alert the user when they’ve successfully eliminated all of the mice (and eventually add another level). It seems that this code is only removing the HTML div element and not the actual object from the array.

if(mice.length === 0){
    console.log("success!")
}

Initially I tried the above but it 1. logs to the console on initial render right before the array is populated and 2. doesn’t work as I intended since the array length never goes back to 0.

function checkCollisions(){
    mice.forEach(mouse => {
        if(collision(mouse.mouse, cat)){
            sound.play()
            mouse.mouse.remove()
            // generateMouse()  //* removed regenerate
            console.log(mice)
        }
    })
}

Is mouse.mouse.remove() just removing the html div from the browser? I’m not understanding why this is not removing the “mouse” property from the object.
How can I get it to remove the collided mouse from the array?

Console screenshot after initial render and checkCollisions() executing twice

Thanks in advance!

How to disable magnifying glass on double tap in mobile safari?

I’m developing an HTML5 canvas game and one very frustrating thing my users keep reporting is that if they double tap the canvas while playing the game, the little blurred glass rounded rectangle briefly appears and jumps at the user’s finger. I believe this is the text selection magnifying glass feature? It happens on both iPads and iPhones. I have been trying for the past hour to get rid of it, to no avail. What am I doing wrong? I have tried the following CSS:

  -webkit-tap-highlight-color: transparent;
  -webkit-touch-callout: none !important;
  user-select: none;
  -webkit-user-select: none !important; 
  -webkit-text-size-adjust: none;  
  touch-action: manipulation;

I have tried calling preventDefault on the touch start event.

I have tried disabling the context menu from appearing on right clicks.

I have tried adding the above css to every element on the page.

I have tried disabling zoom through the entire document.

Literally nothing works. Is it possible to get rid of this thing?!

Discord.js V14 Slash Command Channel Option Type

Hello was doing a slashcommandbuilder in discord.js V14 command and I can’t get it to select only text type channels –>

const commands = [
    new SlashCommandBuilder()
        .setName('setup')
        .setDescription('Setup the embed.')
        .addChannelOption(option => option
            .setName('channel')
            .setDescription('text channel')
            .setRequired(true)
        )
        .toJSON(),
];

I ran it and it works except that it offers me all the channel categories, vocals, text whereas I only wanted the text channels

localstorage for login[reactjs]

im paratice my react and i have a idea but its not very well
i have a button and if user click on it say “WELCOME USER” so if button clicked say it and is not dont say it but is use localstorage and its not working
code:


    import { useState } from "react";

function App(){
    let [isLogin,setIsLoging] = useState(false)
    localStorage.setItem("isLogin",false)
    if(localStorage.getItem("isLogin") == "true"){
        return(
            <>
                <h1>Welcome user</h1>
            </>
        )
    }else{
        return(
            <>
                <button onClick={login}>login</button>
                
            </>
        )
    }
    function login(){
        setIsLoging(isLogin = true)
        localStorage.setItem("isLogin",true)
    }
}
 
export default App;

can anyone help?

Why animation with canvas / scss is not working?

Id like to create a rain of pretzels, I have took the code from codepen.io and when I execute it over there it works. link but when I execute in local is not working. Could someone help me ?

HTML code

<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <title>Page TEST</title>
    <meta name='viewport' content='width=device-width, initial-scale=1'>
    <link rel='stylesheet' type='text/css' media='screen' href='style.css'>
    <script src='../main.js'></script>
</head>
<body>
    
    
    <canvas id="canvas"></canvas>    
    
<script src='../main.js'></script>

    
</body>
</html>

CSS


body {
  margin: 0;
  overflow: hidden;
  background: #061928;
}/*# sourceMappingURL=style.css.map */

JS

$(document).ready(function() {
    var canvas = document.getElementById("canvas");
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    
    if(canvas.getContext) {
      var ctx = canvas.getContext('2d');
      var w = canvas.width;
      var h = canvas.height;
      var img = new Image();
      img.src = "https://images.vexels.com/media/users/3/138154/isolated/preview/5d645814754f5509238ef242137b0fa3-oktoberfest-pretzel-cookie-illustration-by-vexels.png"; 
      
      var init = [];
      var maxParts = 1000;
      for(var a = 0; a < maxParts; a++) {
        init.push({
          x: Math.random() * w,
          y: Math.random() * h,
          l: Math.random() * 30,
          xs: -4 + Math.random() * 4 + 2,
          ys: Math.random() * 10 + 10
        })
      }
      
      var particles = [];
      for(var b = 0; b < maxParts; b++) {
        particles[b] = init[b];
      }
      
      function draw() {
        ctx.clearRect(0, 0, w, h);
        for(var c = 0; c < particles.length; c++) {
          var p = particles[c];
          ctx.drawImage(img, p.x, p.y, p.l, p.l); // draw image at particle's position
        }
        move();
      }
      
      function move() {
        for(var b = 0; b < particles.length; b++) {
          var p = particles[b];
          p.x += p.xs;
          p.y += p.ys;
          if(p.x > w || p.y > h) {
            p.x = Math.random() * w;
            p.y = -20;
          }
        }
      }
      
      setInterval(draw, 30);
      
    }
  });
  

SCSS

/*# sourceMappingURL=style.css.map */
body {
    margin: 0;
    overflow: hidden;
    background: #061928;
  }

style.css.map

{"version":3,"sources":["style.scss","style.css"],"names":[],"mappings":";AACA;EACI,SAAA;EACA,gBAAA;EACA,mBAAA;ACCJ","file":"style.css"}

I install several times SASS, I empty my caches, and adapt my code several times but it does not work.

About next 3 odd and even number

import { useState } from 'react';

function NumberInput() {
  const [inputValue, setInputValue] = useState('');
  const [errorMessage, setErrorMessage] = useState('');

  const handleInputChange = (event) => {
    const value = event.target.value;
    setErrorMessage('');

    // Only allow positive numbers
    if (value < 0) {
      setErrorMessage('Please enter a positive number');
      return;
    }

    // Only allow numbers
    if (isNaN(value)) {
      setErrorMessage('Please enter a valid number');
      return;
    }

    setInputValue(value);

    if (value % 2 === 0) {
      // If the number is even, show the next 3 even numbers
      const nextEvens = [value + 2, value + 4, value + 6];
      setErrorMessage(`The next even numbers are: ${nextEvens.join(', ')}`);
    } else {
      // If the number is odd, show the next 3 odd numbers
      const nextOdds = [value + 2, value + 4, value + 6];
      setErrorMessage(`The next odd numbers are: ${nextOdds.join(', ')}`);
    }
  };

  return (
    <div>
      <label htmlFor="number-input">Enter a number:</label>
      <input
        type="number"
        id="number-input"
        value={inputValue}
        onChange={handleInputChange}
      />
      {errorMessage && <div style={{ color: 'red' }}>{errorMessage}</div>}
    </div>
  );
}

export default NumberInput;

Question is Create a simple UI with one input field that accepts only numbers.
If the user types negative numbers, show “enter a positive value”.
If the user types an even number, show the next 3 even numbers.
If the user types an odd number, show the next 3 odd numbers.

and i think logic is correct but i can’t get the proper answer

ex – i type a even number but couldn’t get the correct next three even number