64bit floating point math in JavaScript, why does division work better than multiplication in this situation

Recently I wanted to round numbers to an arbitrary amount for a stepping slider. I had this code

 steppedV = Math.round(v / step) * step

I found it’s not very good because of floating point math issues. For example v = 19.94 step = 0.1 returns 19.900000000000002

I thought I was kind of out of luck but then just for fun I tried this

 steppedV = Math.round(v / step) / (1 / step)

And surprisingly, for the test cases I’ve been using it’s producing better results. For the same inputs as above I get back 19.9

For all my cases that were not rounding to my test step values it’s all working now. Can someone who really groks how floating point math works explain why / (1 / step) produces more accurate results and * step does not? As someone who understands floating point math is this result intuitive? Would you have known to do the division of (1 / step) for a better result?

function test(start, end, inc, step) {
  const addRow = makeTable(step, 'div', 'mult');
  for (let v = start; v <= end; v += inc) {
    const steppedVMult = Math.round(v / step) * step;
    const steppedVDiv = Math.round(v / step) / (1 / step);
    addRow(v, steppedVDiv, steppedVMult);
  }
}

test(0, 2, 0.03, 0.1);
test(0, 0.2, 0.003, 0.01);
test(0, 0.02, 0.0003, 0.001);
test(0, 0.002, 0.00003, 0.0001);

function c(tag, children = [], text = '') {
  const e = document.createElement(tag);
  e.textContent = text;
  children.forEach(c => e.appendChild(c));
  return e;
}
  
function makeTable(...args) {
  const makeRow = arr => c('tr', arr.map(v => c('td', [], v)));

  const tbody = c('tbody');
  const table = c('table', [
    c('thead', [makeRow(args)]),
    tbody,
  ]);
  document.body.appendChild(table);
  return function(...args) {
    tbody.appendChild(makeRow(args));
  };
}
body { font-family: monospace; }
table { border-collapse: collapse; margin-bottom: 10px }
thead { font-weight: bold; }
td { border: 1px solid #888; padding: 3px; }

How do I create multiple events command in discord.js?

Thanks for checking out!

So, I have a command that depends on different events, such as ready, then messageCreate and I want it in only one command file.

What is the best approach for this?

I think of dispatching an event, then cleaning the listener once the task is ready (manual garbage collection).

  • Is this good practice?
  • How should I do this instead?

The way I have written it now is handling each function of the command for their respective event, but something feels off and the code itself doesn’t look good imo.

Please, for the sake of convenience, let me share these related files:

The command:
https://github.com/sum117/SDA_BOT/blob/master/src/bot/events/commandSystems/inviteTracker.js

The way I’m handling it atm:
Reference to line 8, the event handler…
https://github.com/sum117/SDA_BOT/blob/master/src/bot/index.js#L8

Gotta conflict with… itself in express

I’ve integrated for my bot APIs. I expected they will work very well, but the truth is no…
I still can’t figure out how the server gonna abort itself…
This is error output, and the code, screenshot. Just help me…

Error: Request aborted

    at onaborted (/home/runner/TModeration-Server/node_modules/express/lib/response.js:1052:15)
    at Immediate._onImmediate (/home/runner/TModeration-Server/node_modules/express/lib/response.js:1094:9) {
  code: 'ECONNABORTED'
}
// API server
const express = require('express')
const path = require("path")
const app = express()
const PORT = 443

app.get('/api/', (req, res) => {
  var options = {
    root: path.join(__dirname)
  };
  res.writeHead(200, {'Content-Type': 'text/plain'})
  const requiredFile = req.path.toLowerCase.replaceAll('https://', '').replaceAll('tmoderation-server.henry133.repl.co', '').replaceAll('/api/', '')
  res.sendFile(`./APIs/${requiredFile ?? "index.js"}`, options, function(err) { console.log(err) })
  res.end()
})

app.get('/', (req, res) => {
  var options = {
    root: path.join(__dirname)
  };
  res.writeHead(200, {'Content-Type': 'text/html'})
  res.sendFile("./html.txt", options, function(err) { console.log(err) })
  res.end()
})

app.listen(PORT || 443, () => {
  console.log(`APIs [BETA] is listening ${PORT}`)
})

image

javascript only works when embedded in html [duplicate]

I have a JavaScript function to toggle visibility of a password. The feature works correctly when the JS is embedded straight in the html with <script> tags, but does not work when I run it from a separate JS file in the static/hello/_js folder.

The console logs an error:

login.js:3 Uncaught TypeError: Cannot read properties of null (reading
‘addEventListener’)

HTML:

{% extends "hello/layout.html" %}

{% block style %}
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,[email protected],100..700,0..1,-50..200" />
{% endblock %}

{% block scripts %}
{% load static %}
<script src="{% static 'hello_jslogin.js' %}"></script>
{% endblock %}


{% block content %}
<hr>
<div class="form">
    <form>
        <h2 style="text-align:center">Login</h2>
        <div>
            <label for="username">Username:</label>
            <input type="text" name="username" id="username" class="field">
        </div>
        <br>
        <div>
            <label for="user-pw">Password:</label>
            <input type="password" id="user-pw" name="user-pw" class="password">
            <i id="visibilityBtn"><span id="icon" class="material-symbols-outlined">visibility_off</span></i>
        </div>
        <button style="text-align: center;">login</button>
    </form>
</div>

{% endblock %}

and the JavaScript:

const visibilityBtn = document.getElementById("visibilityBtn");
visibilityBtn.addEventListener("click", toggleVisibility);

function toggleVisibility() {
    const passwordInput = document.getElementById("user-pw");
    const icon = document.getElementById("icon")
   
    if (passwordInput.type === "password") {
        passwordInput.type = "text";
        icon.innerText= "visibility"
    } else {
        passwordInput.type = "password";
        icon.innerText = "visibility_off"
    }
}   

Why does this JavaScript code print “undefined” on the final

function checkAlliteration(){
try{
    let inputString = document.getElementById('alliter');
    let inputChar = document.getElementById('char');
    let count = getCount(inputString);
    let isValid = false;
    let finalScore;
    if(count < 3){
        document.getElementById('result').innerHTML='Invalid number of words';
        return;
    }else{
        isValid = validateSentence(inputString);
        if(isValid == false){
          document.getElementById('result').innerHTML='Invalide sentence';
          return;
         }else{
            finalScore = getScore(inputString,inputChar);
             document.getElementById('result').innerHTML='Your score is' + '' + finalScore;
             return;
    }
    }
  
// Get the value of char & alliter components
// Invoke getCount() method - will return the number of words. 
// IF the number of words in the sentence is <3, display the corresponding output statement in div with id 'result' 

// ELSE, invoke validateSentence() method - will return true / false. 
// IF false, display the corresponding output statement in div with id 'result' 

// ELSE, Invoke getScore() - will return the calculated score. 
// Display the corresponding output statement in div with id 'result'  

}catch(err){
    document.getElementById("result").innerHTML="Function checkAlliteration: "+err;
}

}
So every function have no problem the getScore will return a number, and the finalScore will get the score and return to html, but it’s kepp showing your score is undefined anyone has and idea?

How do I get a 4-digit year from fakerjs date.birthdate() when setting `max` and `min`

I’m trying to use the community fakerjs library to get a random birthdate. I want it to be within the last 70 years at the latest. In my output, though, I keep getting years like 79 and 12 instead of 1979 or 2012. I can only get a 2-digit year.

let date = faker.date.birthdate({ max: 70, min: 1 });
// 0037-08-27T13:35:09.312Z
date.getFullYear()
// 37

.birthdate() by itself works fine, it’s just when I use max and min that the problem shows up.

What am I doing wrong?

Detect whether firebase app is hosted by emulator or in production

I have a web app which currently uses Firestore as a database with Firebase Auth. I have it set up to try to connect to the Firebase emulators when in development, like so:

if(process.env.NODE_ENV === "development") {
    connectFirestoreEmulator(firestoreDb, "localhost", 8080);
}

I also use this technique to disable some in-browser testing when not in development.

This works fine when running a development server through Vite, which is what I have been using. However, I recently set up the project to run on Firebase hosting, and I found that process.env.NODE_ENV is not set when I run the hosting emulator. Is there another way to determine whether the app is being hosted from an emulator (i.e. for development) or on the real Firebase hosting service?

To clarify, I need to run this check in the app’s client-side code, which is to be hosted statically via Firebase hosting. I am NOT concerned with server-side Firebase Cloud Functions (see this question for answers on that).

Unexpected server response: 401

I am creating a code in which it will transform text to speech in discord, and i am getting a code this error when i run the command

Síntese de fala cancelada, Unable to contact server. StatusCode: 1006,
undefined Reason: Unexpected server response: 401 Você definiu a
chave do recurso de fala e os valores da região?

const { Command } = require("../..")
const { createAudioPlayer, createAudioResource ,joinVoiceChannel } = require('@discordjs/voice');

var sdk = require("microsoft-cognitiveservices-speech-sdk");

var key = "MyKey";
var region = "brazilsouth";
var audioFile = "audioFile.mp3";  

module.exports = class Speak extends Command {
  constructor(client) {
    super(client, {
      name: "speak"
    });
  }

  async run({ message }, args) {
    message.delete().catch(() => {})

    if (!args[0]) return message.channel.send("Digite qual mensagem deseja que eu fale!")

    const string = args.join(' ')
    
    const voiceChannel = message.member.voice.channel
    if (!voiceChannel) return message.channel.send("Entre em um canal de voz!")

    const speechConfig = sdk.SpeechConfig.fromSubscription(key, region);
    const audioConfig = sdk.AudioConfig.fromAudioFileOutput(audioFile);

    // speechConfig.speechSynthesisVoiceName = "pt-BR-FranciscaNeural"; 
    speechConfig.speechSynthesisVoiceName = "pt-BR-AntonioNeural"; 
    
    var synthesizer = new sdk.SpeechSynthesizer(speechConfig, audioConfig);

    synthesizer.speakTextAsync(string,
      function (result) {
        if (result.reason === sdk.ResultReason.SynthesizingAudioCompleted) {

        const connection = joinVoiceChannel({
          channelId: message.member.voice.channel.id,
          guildId: message.guild.id,
          adapterCreator: message.guild.voiceAdapterCreator
        });

        const player = createAudioPlayer()
        const resource = createAudioResource('E:\! [A]nglei\Projetos\Anglei 2.0\Meus Projetos\Bot Teste\audioFile.mp3')
        
        player.play(resource)
        connection.subscribe(player)

        } else {
          console.error("Síntese de fala cancelada, " + result.errorDetails +
            "nVocê definiu a chave do recurso de fala e os valores da região?");
        }
        synthesizer.close();
        synthesizer = null;
      },
    function (err) {
      console.trace("err - " + err);
      synthesizer.close();
      synthesizer = null;
    });
  }
}

How to send a Png or Jpeg image as binary to node.js server from react app?

I am trying to send a file from a react web app to node.js server.

I am starting off with an html input of type file, Once user uploads their file, I trigger a post request to my Node.js server.

Once in my Node.js server, I need to send a post request to a 3rd party API (Twilio)

3rd party API needs my file as binary data.

Note: from docs “The body or content of the POST must be the file itself in binary format.”

Here is React component below

import React, {Fragment, useState, useRef } from 'react'
import { Col, Button, Media, Card, CardBody } from 'reactstrap';
import {useSelector, useDispatch} from 'react-redux';
import { attachMMS } from '../../../actions/index';
import cloudUpload from '../../../assets/img/icons/cloud-upload.svg';

const InsertMMS = ({showFileModal, setShowFileModal, showInsertMMSModal, setShowInsertMMSModal, uploadMMS, setUploadMMS}) => {

    const InputFile = useRef(null)
    const [userMMS, setUserMMS] = useState()
    const [highlighted, setHighlighted] = useState(false)
    const dispatch = useDispatch();

    const attachMMSCreate = useSelector((state) => state.attachMMSCreate);

    const manualMMSUpload = (e) => {
      console.log("manualMMSUpload ran")
        e.preventDefault();
        if(e.target.files[0].name) {
           console.log("file", e.target.files[0])
          getBase64(e.target.files[0])
            setUserMMS(e.target.files[0].name)
        }
      }



      
      const getBase64 = (file) => {
        const reader = new FileReader();
        reader.readAsText(file)
        reader.onload = () => {
          setUploadMMS({file: file, fileType: file.type});
        }
      }

      const handleInputChange = ({ value, name }) => setUploadMMS({ ...uploadMMS, [name]: value });

      const onButtonClick = (e) => {
        e.preventDefault();
       InputFile.current.click();
      };
  

    return ( 
    <Fragment>
        <Card>
            <CardBody className="fs--1 font-weight-normal p-4">
      <h4 className="mb-1 mt-3 text-center"></h4>
      <div>
        <input 
          type="file" 
          onChange={(e) => manualMMSUpload(e)}
          accept=".gif, .png, .jpeg" 
          ref={InputFile}
          className="d-none" />
        <div className={`mb-2 p-3 border-dashed border-2x border-300 bg-light rounded-soft text-center cursor-pointer ${highlighted ? ' border-800' : ''}`}
          onClick={(e) => onButtonClick(e)}
          onDragEnter={() => {setHighlighted(true)}}
          onDragLeave={() => {setHighlighted(false)}}
          onDragOver={(e) => { e.preventDefault(); }}
          onDrop={(e) => { e.preventDefault(); }}
        >
        <Fragment>
          <Media className=" fs-0 mx-auto d-inline-flex align-items-center">
            <img src={cloudUpload} alt="" width={25} className="mr-2" />
          <Media>
            <p className="fs-0 mb-0 text-700">{userMMS ? userMMS : "Upload your File"}</p>
          </Media>
          </Media>
            <p className="mb-0 w-75 mx-auto text-500">Supports: .gif, .png, .jpeg </p>
        </Fragment>
            </div>
            </div>
        <p className="fs-0 text-center">multi-media message</p>
            <Col className="text-center">
                <Button disabled={!uploadMMS} color="primary" onClick={() => { return dispatch(attachMMS(uploadMMS)), setShowInsertMMSModal(!showInsertMMSModal), setShowFileModal(!showFileModal) }} className="my-3 text-white">
                {attachMMSCreate.loading ? "...processing" : "Attach MMS"}
                </Button>
            </Col>
        </CardBody>
    </Card>
  </Fragment>
  


  )
}

export default InsertMMS

Here is the Action being called from React making the POST request to Node.js server

  export const attachMMS = (uploadMMS) => async (dispatch) => {
                console.log("body of attachMMS in actions", uploadMMS)
                try {

                        dispatch({type: ATTACH_MMS_CREATE_REQUEST })
                        await axios({
                                url:"http://localhost:5000/mms",
                                method:"POST",
                                data: uploadMMS.file,
                                withCredentials: true
                              }).then(res =>  dispatch({type: ATTACH_MMS_CREATE_SUCCESS, payload: res}))   


                } catch(error) {
                        console.log(error)
                        dispatch({type: ATTACH_MMS_CREATE_FAIL,
                                payload:
                                error.message && error.response.data.message 
                                ? error.response.data.message :
                                error.message
                                })
                }
        }

Here is the Node.js route being triggered

module.exports = (router) => {

router.route('/mms').post(twilCtrl.createMediaMMSResource)

}

Here is the Node.js function being called



        const createMediaMMSResource = async (req, res) => {
            try {
            const { subActServiceSid, subActAuthToken, convoServiceSid} = req.user
            let mediaResource

                   await  axios({
                    url:`https://mcs.us1.twilio.com/v1/Services/${convoServiceSid}/Media`,
                    method:"POST",
                    data: req.body, // this needs to be the file itself in binary format
                    headers: {
                        "Content-Type": 'image/png'
                      },
                    auth: { username: subActServiceSid, password: subActAuthToken },
                    withCredentials: true
                    }).then(res => {
                        console.log("res from first post request to twilio with fileData", res.data)
                        return  mediaResource = {mediaUrl: res.data.url, serviceSid: res.data.service_sid, mediaSid: res.data.sid} 
                        })
                            res.status(201).json(mediaResource) 
            } catch(err) {
            console.log(err)
            }
        }

Here is the response I get from client….

Does anyone see the issue? I cant seem to understand how to send “Binary” data to node.js server…..

enter image description here

What is the difference between this two vuex codes and which one is better?

I’m aware that vuex state should be updated by mutation.
But, first code doesn’t use mutation to update vuex state.
How can this code work without mutation? And, which code is better to use?

setup() {
  const store = useStore();
  return {
    a: computed({
      get: () => store.state.a,
      set: (val) =>
        (store.state.a = val),
    }),
  };
setup() {
  const store = useStore();
  return {
    coordSystem: store.state.a
    updateA: (val) =>
      store.commit("updateA", val),
  };

How to test this component staying aligned with React Testing Library Principles?

I am testing a component and wondering what the best approach would be that would test the component without testing implementation details.

The component renders conditionally based on the width and isDropdown state, but not sure how to test how the DOM would look by changing these values or even if that would be the correct approach.

Here is the component:

import { useState } from 'react'
import useWindowDimension from '../../hooks/useWindowDimensions'
import { QueryType } from '../../constants'

type choiceProps = {
    type: QueryType
    isChosen: boolean
    setFeedChoice: (query: QueryType) => void
}

const FeedChoice = ({ type, isChosen, setFeedChoice }: choiceProps) => {
    return (
        <div
            className={isChosen ? 'feed-choice chosen' : 'feed-choice'}
            onClick={() => setFeedChoice(type)}
        >
            <img
                src={require(`../../../public/images/${type}${
                    isChosen ? '-fill' : ''
                }.svg`)}
            />
            <span>{type.charAt(0).toUpperCase() + type.slice(1)}</span>
        </div>
    )
}

type Props = {
    feedChoice: QueryType
    setFeedChoice: (query: QueryType) => void
}

const Feed = ({ feedChoice, setFeedChoice }: Props) => {
    const { width } = useWindowDimension()
    const [isDropdown, setDropdown] = useState<boolean>(false)

    const setChoice = (query: QueryType) => {
        setFeedChoice(query)
        setDropdown(false)
    }

    if (width !== null && width <= 600) {
        return (
            <div className="feed-row">
                {isDropdown ? (
                    <div>
                        <FeedChoice
                            type={QueryType.New}
                            isChosen={feedChoice === QueryType.New}
                            setFeedChoice={setChoice}
                        />
                        <FeedChoice
                            type={QueryType.Boost}
                            isChosen={feedChoice === QueryType.Boost}
                            setFeedChoice={setChoice}
                        />
                        <FeedChoice
                            type={QueryType.Comments}
                            isChosen={feedChoice === QueryType.Comments}
                            setFeedChoice={setChoice}
                        />
                        <FeedChoice
                            type={QueryType.Squash}
                            isChosen={feedChoice === QueryType.Squash}
                            setFeedChoice={setChoice}
                        />
                    </div>
                ) : (
                    <FeedChoice
                        type={feedChoice}
                        isChosen={true}
                        setFeedChoice={() => setDropdown(true)}
                    />
                )}
            </div>
        )
    } else {
        return (
            <div className="feed-row">
                <FeedChoice
                    type={QueryType.New}
                    isChosen={feedChoice === QueryType.New}
                    setFeedChoice={setFeedChoice}
                />
                <div className="divider"></div>
                <FeedChoice
                    type={QueryType.Boost}
                    isChosen={feedChoice === QueryType.Boost}
                    setFeedChoice={setFeedChoice}
                />
                <div className="divider"></div>
                <FeedChoice
                    type={QueryType.Comments}
                    isChosen={feedChoice === QueryType.Comments}
                    setFeedChoice={setFeedChoice}
                />
                <div className="divider"></div>
                <FeedChoice
                    type={QueryType.Squash}
                    isChosen={feedChoice === QueryType.Squash}
                    setFeedChoice={setFeedChoice}
                />
            </div>
        )
    }
}

export default Feed

Here is my initial test that is only testing if the text properly appears in the DOM, which it does:

import React from 'react'
import { screen, render } from '@testing-library/react'
import Feed from '../components/feed/feed'
import useWindowDimensions from '../hooks/useWindowDimensions'

test('should render all of the QueryTypes in the Feed', () => {
    render(<Feed />)
    
    
    expect(screen.getByText(/new/i)).toBeInTheDocument()
    expect(screen.getByText(/boost/i)).toBeInTheDocument()
    expect(screen.getByText(/comments/i)).toBeInTheDocument()
    expect(screen.getByText(/squash/i)).toBeInTheDocument()
})

Thanks!

Why is my useEffect hook updating too late?

I am trying to have an image and text update when I click a button, which it does, but the image is from the previous state. Is there a way to have it so that it changes instantly? Any help is appreciated. Using React btw.

function Footer({ spotify }) {
    const [{ item, playing }, dispatch] = useDataLayerValue();

    useEffect(() => {
        spotify.getMyCurrentPlaybackState().then((r) => {
            dispatch({
                type: "SET_PLAYING",
                playing: r.is_playing,
            });
    
            dispatch({
                type: "SET_ITEM",
                item: r.item,
            });
        });
    }, [spotify]);
    
    const handlePlayPause = () => {
        if (playing) {
            spotify.pause();
            dispatch({
                type: "SET_PLAYING",
                playing: false,
            });
        } else {
            spotify.play();
            dispatch({
                type: "SET_PLAYING",
                playing: true,
            });
        }
    };

    return (
        <div className='footer'>
            <div className="footer__left">
                <img className="footer__albumLogo"
                    src={item?.album.images[0].url}
                    alt={item?.name}
                    key={item?.album.images[0].url}/>
                {item ? (
                    <div className="footer__songInfo">
                        <h4>{item.name}</h4>
                        <p>{item.artists.map((artist) => artist.name).join(", ")}</p>
                    </div>
                ) : (
                    <div className="footer__songInfo">
                        <h4>No song is playing</h4>
                        <p>...</p>
                    </div>
                )}
            </div>
        </div>
    )
}

export default Footer

I think that the issue is within the “div className=”footer__left”” but it may be an entirely different issue.

BuildFire.JS WebRTC – Cannot access camera and mic

I am trying to start video chat app inside the widget builder in buildfire.js using WebRTC. I am getting the following error message:

69a6d1ba-ed1f-4f05-8835-7f70168acf27:1 Uncaught (in promise) 
bt {gum: {…}, name: 'gum.permission_denied', message: 'User denied permission to use device(s): audio, video', stack: 'Errorn    at new bt (https://meet.bingewave.com/li…bingewave.com/libs/lib-jitsi-meet.min.js:2:509715'}
gum:
constraints: {video: {…}, audio: {…}}
devices: (2) ['audio', 'video']
error: DOMException: Permission denied
[[Prototype]]: Object
message: "User denied permission to use device(s): audio, video"
name: "gum.permission_denied"
stack: "Errorn    at new bt (https://meet.bingewave.com/libs/lib-jitsi-meet.min.js:2:269189)n    at https://meet.bingewave.com/libs/lib-jitsi-meet.min.js:2:509715"
[[Prototype]]: Error

I’m not being prompted for access to my camera or microphone and the error message says permission has been denied, how do I allow buildfire.js to access camera and mic?