How do I pass a variable value which was collected from user input from one function to another (javascript)

I am trying to create a page on html that automatically creates a pie chart with data provided from the user input form. I am trying to pass the values tax, mort,f,transport,and saving from collect() to drawChart() so that it could use those values to create the pie chart, but it doesn’t seem to work. Does anyone know why?

function collect() {
    var tax = +document.getElementById("taxes").value;
    document.getElementById('tax').innerHTML = tax;

    var mort = +document.getElementById("mortage").value;
    document.getElementById('mort').innerHTML = mort;

    var f = +document.getElementById("food").value;
    document.getElementById('f').innerHTML = f;

    var transport = +document.getElementById("transportation").value;
    document.getElementById('transport').innerHTML = transport;

    var saving = +document.getElementById("savings").value;
    document.getElementById('saving').innerHTML = saving;

    drawChart(tax,mort,f,transport,saving);
}


    function drawChart(val1,val2,val3,val4,val5) {
  
    var data = google.visualization.arrayToDataTable([
    ['Expense/Income', '$ per Month'],
    ['Taxes',val1],
    ['Mortage', val2],
    ['Food', val3],
    ['Transportation', val4],
    ['Savings',val5]
    ]);
var options = {'title':'Monthly Budget', 'width':550, 'height':400};

    // Display the chart inside the <div> element with id="piechart"
    var chart = new google.visualization.PieChart(document.getElementById('piechart'));
    chart.draw(data, options);
    }
<div class="editTable">
  <div class="left">Taxes: </div><div class="right"><input type="number" name="taxes" id="taxes"></div><br><br>
  <div class="left">Mortages: </div><div class="right"><input type="number" name="mortage" id="mortage"></div><br><br>
  <div class="left">Food: </div><div class="right"><input type="number" name="food" id="food"></div><br><br>
  <div class="left">Transportation: </div><div class="right"><input type="number" name="transportation" id="transportation"></div><br><br>
  <button onclick="collect();" class="editRowBtn">Update</button><br><br>
</div>

im getting the error clear missing intends when coding a bot

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

const client = new Discord.Client({ ws: { intents: new Discord.Intents(Discord.Intents.ALL) } });

‘this is a code that requires all intents is it wrong’

client.once('ready', () => {
    console.log('Coleria is online!');
});

const prefix = '*'

‘can i go with this prefix’
client.on(“message”, message =>{
if(!message.content.startsWith(prefix) || message.author.bot) return;

    const args = message.content.slice(prefix.length).split(" ");
    const command = args.shift().toLowerCase();

    if(command === 'sa'){
        messageCreate.channel.send('As kardeşim hoşgeldin.');
    }
});

client.login("my token");

‘cant give my token xd’

How to integrate 2.5% sales fee in an NFT Marketplace

I’m currenttly building an NFT marketplace, I am done with all the major functionalities, i.e listing, selling, buying etc. but the problem is, when wiriting the code earlier I used a fixed listing fee of 0.1 ether and now I would like to integrate a 2.5% fee on every sale
Here’s my solidity code

function createMarketSale(address nftContract, uint256 itemId, uint256 commission)  
 public  
 payable  
 nonReentrant  
    {  
        uint256 price = idToMarketItem[itemId].price;  
        uint256 tokenId = idToMarketItem[itemId].tokenId;  
 require(  
 msg.value == price,  
 "Please submit the asking price in order to complete the purchase"  
        );  
        idToMarketItem[itemId].seller.transfer(msg.value);  
 IERC721(nftContract).transferFrom(address(this), msg.sender, tokenId);  
        idToMarketItem[itemId].owner = payable(msg.sender);  
        idToMarketItem[itemId].sold = true;  
        _itemsSold.increment();  
 payable(owner).transfer(commission);  
    }

Here’s How my web3 frontend interacts with the contract

async function buyNFT() {
 const web3Modal = new Web3Modal();
 const connection = await web3Modal.connect();
 const provider = new ethers.providers.Web3Provider(connection);

 const signer = provider.getSigner();
 const contract = new ethers.Contract(nftmarketaddress, Market.abi, signer);

 const price = ethers.utils.parseUnits(nft.price.toString(), "ether");
 const fee = +((2.5 / 100) * nft.price);
 let commission = fee.toString();

 let transaction = await contract.createMarketSale(nftaddress, nft.itemId, commission, {
 value: price,
 });

 await transaction.wait();
    window.location.replace("/profile");
 }

but I keep getting an Error: Transaction reverted: function call failed to execute when it gets to this line :

 payable(owner).transfer(commission);  

I have no idea what I’m doing wrong, please help

MongoDB aggregate to extract values from a nested array and return a total

I have this collection structure:

[
   "_id": "61a013b59f9dd0ebfd23ftgb",
   "modules": [
     {
       "_id": "61a013b59f9dd0ebfd964dgh",
       "videos": [
         {
           "_id": "213412",
           "progress": 100
         },
         {
           "_id": "61a013b59f9dd0ebfd965f4a",
           "progress": 0
         },
       ]
     },
     {
       "_id": "43556hujferwdhgsdft",
       "videos": [
         {
           "_id": "fdsg3sg98er989890",
           "progress": 66
         },
         {
           "_id": "fdsg3sg98er989890",
           "progress": 100
         },
         {
           "_id": "fdsg3sg98er989890",
           "progress": 100
         }
       ]
     }
   ]
 ]

I am trying to return the overall progress for each “module” by adding up all the videos that have progress of 100 and creating a percentage based on number of videos in the module. For example, the first module should return “module_progess” of 50 within it as this has 1/2 videos completed.

{
   "_id": "61a013b59f9dd0ebfd964dgh",
   "module_progress": 50,
   "videos": [
     {
       "_id": "213412",
       "progress": 100
     },
     {
       "_id": "61a013b59f9dd0ebfd965f4a",
       "progress": 0
     },
   ]
},

How do i access each videos object to make this calculation and add the new field to the response?

How can i add multiple views to one view without conflict on scripts?

I am trying to add multiple views to one view, but it conflicts with scripts and repeating IDs, these are previsualization views before convert to PDF file, these are generating charts.

What i do to add the multiple views is:

 $view .= view('system.administrator.history.pdf.layout-multiple', compact('sample', 'samples', 'tests'))->render(); // These is into a foreach loop
return $view; // This is what i received at the AJAX function and is sended to a form element hidden to send data to a new view

Function to add multiple views at one is working, my problem is with scripts, and IDs.

Any solution?

Suspense fallback doesn’ t work with react router

In my project I’ m using react-router and Suspence for rendering multiple lazy pages.
The only thing that doesn’ t seem working is the fallback prop of the Suspence component, that is, the LoadingSpinner component doesn’ t load when you go from one page to another.

The App.js code:

import React, { lazy, Suspense } from 'react';
import { Routes, Route } from 'react-router-dom';

import { AppContainer, RedirectComponent } from './app.styles';

import SearchField from '../components/search-field/search-field.component';
import ErrorBoundary from '../components/error-boundary/error-boundary.component';
import LoadingSpinner from '../components/loading-spinner/loading-spinner.component';
import RefreshRoute from '../components/refresh-route/refresh-route.component';

const PageNotFound = lazy(() => import('../pages/page-not-found/page-not-found.component'));
const MainPage = lazy(() => import('../pages/main-page/main-page.component'));
const CurrentForecast = lazy(() => import('../components/current-forecast/current-forecast.component'));

const App = () => ( 
  <AppContainer>
    <RedirectComponent to='/'>GO TO HOME PAGE</RedirectComponent>
    <SearchField />
    <ErrorBoundary>
      <RefreshRoute>
        <Suspense fallback={<LoadingSpinner />}>
          <Routes>        
              <Route exact path='/' element={<MainPage />} />
              <Route exact path='/details/:detailsID' element={<CurrentForecast isMainPage={false} />} />            
              <Route exact path='*' element={<PageNotFound />} />            
          </Routes>        
        </Suspense>
      </RefreshRoute>
    </ErrorBoundary>
  </AppContainer>
);

export default App;

querySelectorAll() with multiple tables

I´m generating dinamic user´s config tables with PHP, and there is a function to match the password for each user, individualy.
When I have one table only, I can use getElementById and the functions works fine. With multiple tables, using querySelectorAll(“.class”) something happens and I don´t know what is going on.
So I made a test.php script and made a test function to see the javascript console output.
I have 3 tables, and the for last one user´s input it appears for all the tables, but it should work for each one table individually, as the user inputs stuff for each one. Here goes the code:
(HTML)

<div class='config_user' >
    <table>     
        <tr><td>Senha: <td><input type='text' class='senha1' oninput='testE()'>
        <tr><td>Confirmar Senha: <td><input type='text' id='senha1'>        
    </table>
    <table>     
        <tr><td>Senha: <td><input type='text' class='senha1' oninput='testE()'>
        <tr><td>Confirmar Senha: <td><input type='text' id='senha2'>        
    </table>
    <table>     
        <tr><td>Senha: <td><input type='text' class='senha1' oninput='testE()'>
        <tr><td>Confirmar Senha: <td><input type='text' id='senha3'>        
    </table>    
</div>

(JS)
function retornaV(x){
    document.getElementById("senha1").value = x;
    document.getElementById("senha2").value = x;
    document.getElementById("senha3").value = x;
}
function testE(){
var teste = window.document.querySelectorAll(".senha1");
   teste.forEach(function(item, index){
       retornaV(item.value);
       console.log(index + " <- index , valor -> " + item.value);
   })
 }

The console.log returns all the inputs just fine, but retornarV() just give me the value of the last table for all tables.
If someone can help, I appreciate.
Roberto Carreira

Formating v-model make a decision if you meet the condition

I have one component that have one input, the input value indicates the unit of measurement, the measurements can be kilogram, gram, units, etc …

I have registered in the database

Kg = 0.1
g = 100
unit = 1

The type of input value, is selected from a select

so in my code I have:

<template>
    <tr>    
        <td class="product-quantity">
            <input
                class="quantity no-round-input"
                type="numeric"
                v-model="item.quantity"
                min="0"
                @keypress="isNumber($event)"
            />
        </td>
        <td class="product-price">
            <select
                name="unit"
                class="form-control"
                v-model="item.attributes.unit"
            >
                <option v-bind:key="unit.id" v-for="unit in units" :value="unit.abr">
                    {{ unit.unit }}
                </option>
            </select>
        </td>
    </tr>
</template>

the value I get from props, so in my vue I have:

<script>
export default {
      props: ["item"],
      watch: {
          'item.quantity' (){ 
            if( (this.item.quantity - Math.floor(this.item.quantity)) !== 0 ){
                this.item.quantity = this.item.quantity.toFixed(1);
            }else{
                this.item.quantity = this.item.quantity;
            }
    
          }
       },
       methods: {
        isNumber(evt) {
          evt = (evt) ? evt : window.event;
          var charCode = (evt.which) ? evt.which : evt.keyCode;
          if ((charCode > 31 && (charCode < 48 || charCode > 57)) && charCode !== 46) {
            evt.preventDefault();;
          } else {
            return true;
          }
        },
     }
   }
</script>

so, I just want that when v-model is Kg, the value input is in decimals, only decimals to Kg, so I implemented in propiety watch to observe input(item.quantity) but it’s not working, do you can help me please?

creating new force graph with react+ts and d3

im trying to create a simple force graph with react+ts and d3.

after long research everything i found online isn’t updated lately.
so i would like to use your help with that.

Main issue
i have now is to connect my nodes with a line

heres my code:

import React from "react";
import { forceSimulation, forceManyBody, forceLink, forceCenter } from 'd3-force'
import d3 ,{ SimulationNodeDatum } from "d3";
import { Box } from "@mui/system";


type Node = {
  id: string;
  class: string;
  x?: string;
  y?: string;
}

type Link = {
  source: string;
  target: string;
  connectionType: string;
}

the data (in the same file)

const { links, nodes } = {
  nodes: [{
    id: "honda",
    class: "cars",
  }, {
    id: "civic",
    class: "cars",
  },{
    id: "toyota",
    class: "cars",
  },{
    id: "corola",
    class: "cars",
  }],
  links: [{
    source: 'civic',
    target: 'honda',
    connectionType: 'm2o'
  },{
    source: 'corola',
    target: 'toyota',
    connectionType: 'm2o'
  }]
}

and heres the component

function Rd4Component (): JSX.Element {
  const simulation = forceSimulation(nodes as SimulationNodeDatum[]);
    simulation
      .force('charge', forceManyBody().strength(-100))
    .force('link',
      forceLink(links)
        .id((d) => (d as Node).id)
        .distance(75)
    )
      .force("center", forceCenter(300, 300));

  const svg = d3.select('#Target');

  const node = svg
      .selectAll("circle")
      .data(nodes)
      .enter()
      .append("circle")
      .attr("r", 15)
      .attr("stroke", "green")
      .attr("stroke-width", 0.5)
      .style("fill", "red");

  const link = svg
      .selectAll('path.link')
      .data(links)
      .enter()
      .append("path")
      .attr("stroke", "black")
      .style("fill", "none");


  function ticked() {
     link
       .attr("x1", function (d: any) {
         return d.source.x;
       })
       .attr("y1", function (d: any) {
         return d.source.y;
       })
       .attr("x2", function (d: any) {
         return d.target.x;
       })
       .attr("y2", function (d: any) {
         return d.target.y;
       });

    node
      .attr("cx", function (d: any) {
        return d.x;
      })
      .attr("cy", function (d: any) {
        return d.y;
      });

    // label
    //   .attr("x", function (d: any) {
    //     return d.x + 5;
    //   })
    //   .attr("y", function (d: any) {
    //     return d.y + 5;
    //   });
  }

  simulation.nodes(nodes as SimulationNodeDatum[])
    .on("tick", ticked)


  return <Box sx={{overflowY: "scroll"}}>
    <svg height={600} width={600} id="Target" />
  </Box>
}

export default Rd4Component;

and here the results
the render
inspected results

i cant find a way to render the lines, looked at the docs and even paid online courses. seems that nothing works.. )):

thanks in advanced

Uploading .txt files to the chat discord js

I have a txt file full of stuff that I want the bot to upload to the chat. So far I have found no such code on the internet and I have tried nothing yet. Can anyone write me a script that uploads the whole txt file to the chat(not the content, UPLOAD the text file)? Thanks.

LIFI VLC with JS

I am making a code to send information by bits, it is LIFI information that the flash uses to send said information. I have managed to turn on the torch from the web with JS but at the time of sending the message I have an error, any idea what I can do?

The code is this:

<html><head><meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
  <div class="input-group mt-3 ml-auto mr-auto">
    <input id="msg" class="form-control" type="text" name="msg" placeholder="Type message here..." />
    <div class="input-group-append">
        <button id="toggle" class="btn btn-primary">Send</button>
    </div>
<script>
//have a console on mobile
var consoleOutput = document.getElementById("console");
const log = function(msg){
    //  consoleOutput.innerText = `${consoleOutput.innerText}n${JSON.stringify(msg)}`;
    document.getElementById("console").innerText = msg;
    console.log(msg);
}

//Test browser support
const SUPPORTS_MEDIA_DEVICES = 'mediaDevices' in navigator;

if (SUPPORTS_MEDIA_DEVICES) {
  //Get the environment camera (usually the second one)
  navigator.mediaDevices.enumerateDevices().then(devices => {
  
    const cameras = devices.filter((device) => device.kind === 'videoinput');

    if (cameras.length === 0) {
      log('No camera found on this device.');
    }
    const camera = cameras[cameras.length - 1];

    // Create stream and get video track
    navigator.mediaDevices.getUserMedia({
      video: {
        deviceId: camera.deviceId,
        facingMode: ['environment', 'user'],
        height: {ideal: 1080},
        width: {ideal: 1920}
      }
    }).then(stream => {
      const track = stream.getVideoTracks()[0];

      //Create image capture object and get camera capabilities
      const imageCapture = new ImageCapture(track)
imageCapture.getPhotoCapabilities().then(capabilities => {
 
        //let there be light!
        var isTorchOn  = false;
        const btn = document.querySelector('.switch');
        // if (capabilities.torch){
          btn.addEventListener('click', function(){
            isTorchOn = !isTorchOn;
            log("El flash esta encendido?: " + isTorchOn)
            try{
                track.applyConstraints({
                advanced: [{torch: isTorchOn}]
              });
            } catch(err){
                    log(err);
            }
          });

        const btn2 = document.querySelector('.switchOff');
        if (!capabilities.torch){
            log("Precione habilitar y encender");
        }
          btn2.addEventListener('click', function(){
            try{
                track.applyConstraints({
                advanced: [{torch: false}]
              });
            } catch(err){
                    log(err);
            }
          });

      });
    }).catch(log);
  }).catch(log);
  
const msg = document.getElementById("msg");
const button = document.getElementById("toggle");
let interval = null;
button.onclick = () => {

  if (interval) {
        clearInterval(interval);
        interval = null;
    }
    const seq = [];
    ["x02", ...msg.value, "n", "x03"].forEach(c => seq.push(...encode(c.charCodeAt(0))));
    interval = setInterval(() => {
        if (!seq.length) {
            clearInterval(interval);
            interval = null;
        } else if (seq.shift()) {
          try{
            track.applyConstraints({
                advanced: [{torch: isTorchOn}]
              });
            } catch(err){
                    log(err);
          }
        } else {
          try{
                track.applyConstraints({
                advanced: [{torch: false}]
              });
            } catch(err){
                    log(err);
            }
        }
    }, 50);

    function parity(val) {
    val = val ^ (val >> 1);
    val = val ^ (val >> 2);
    val = val ^ (val >> 4);
    return val & 1;
}

function encode(char) {
    const bits = [1];
    for (var i = 0x80; i > 0; i >>= 1) {
        bits.push(char & i ? 1 : 0);
    }
    bits.push(parity(char));
    bits.push(0);
    return bits;
}}}
</script>
</head>
<body>
    <button class="switch">Encender / Apagar</button> - 
    <button class="switchOff">Apagar</button>
    <h2>
    Console output
    </h2>
    <div id="console">Precione habilitar y encender</div>
</body></html>

When you click on turn On / Off the torch turns on, but I need that when a user enters a message or a number in the textbox a sequence is turned on when pressing accept. It should be clarified that this program only works in Chrome

Construct object wit array

I have a array of objects:

const arr = [
  {
    name: "Name 1",
    symbol: "S1"
  },
  {
    name: "Name 2",
    symbol: "S2"
  },
]

And I want to transform this on this

{
  S1: "Name 1", S2: "Name 2"
}

I tried this

arr.map((a) => { [a.symbol]: a.name })

But no luck. How can I achieve this?

how to change the download directory/location in pipe() method?

this code downloads the files in the project folders, how do i change this to another location?

await new Promise((resolve, reject) => {
    let fileExt = post.url.split(".").pop();
    request(`${post.url}`)
      .pipe(
        fs.createWriteStream(
          `${post.title.slice(0, 10).replace(/ +/g, "")}.${fileExt}`
        )
      )
      .on("finish", () => {
        console.log("download success..!");
        resolve();
      })
      .on("error", (error) => {
        console.log("from event ===>", error);
        rejects(error);
      });
  });

jquery submit form and stay on same page not working

The below code is supposed to submit the form and stay on the current page. It does submit the form, but it doesn’t stay on the same page as it redirects to the form processing page. I have tried using event.preventDefault(); and return false; – but neither are stopping the redirect. I tried them one at a time then added both at the same time and at different locations in the functin, but the redirect still happens.

  function submitForm() {
    var $subForm = $('#signupForm')[0] ;
    if (!$subForm.checkValidity()) {
      $subForm.find(':submit').click() ;
      return ;
    }
    
    $subForm.submit(function(event){
      event.preventDefault(); // not working  here
      $.post($(this).attr('action'), $(this).serialize(), function(response){
            // do something here on success
        console.log(response) ;
      },'json');
      return false;  // not working here
    });
    return false ;  // not working here
  }

My form is defined as:

<form method="POST" id="signupForm" action="submitSignup.php" enctype="multipart/form-data" validate>
    ....
    <button type="button" onclick='submitForm();' id="ccInfoButton" style="" class="btn btn-primary buttonSignup" disabled >CREATE ACCOUNT NOW<i class="iconRequired icon-chevron-right"></i></button>
</form>

Shouldn’t using spread syntax not reference the original array?

I have an Object array in my state called names, i’m trying to make a copy of this array to another Object array in state called shuffledNames, but when i shuffle the shuffledNames using the code below, the original names changes the ids to match the new shuffled ids. See images below for an example. I’ve tryed using .concat(), .slice(). I do not know what to try anymore.

  handleSort = () => {
    let tempName = [...this.state.names];

    let shuffledNames = tempName;

    for (let i = shuffledNames.length; i-- > 1; ) {
      let j = Math.floor(Math.random() * i);
      let temp = shuffledNames[i];
      shuffledNames[i] = shuffledNames[j];
      shuffledNames[j] = temp;
    }

    shuffledNames.forEach((shuffledName, index) => {
      shuffledName.id = index;
    });

    this.setState({ shuffledNames: shuffledNames });
  };

This is my state before shuffling

This is my state after shuffling