Adding two decimals in javascript and getting NaN [closed]

Hi I am having problems with math in javascript. I’m trying to make a calculator and have succeded in making +,-,* and / for integers. But when i try to add two decimals together it is returned to my siplay as NaN which I understand stands for Not A Number. I was wondering why I get this and if there is a solution to this problem. Thanks!

I tried adding two decimals together and was expecting to reacive the answer as a decimal, but what i got was returend as NaN which I understand to be not a number.

Why does the useEffect depending on the socket not have access to the updated state on the first re-render?

I have 2 useEffect’s in my React component. One of them (#1) has an empty dependency array and is responsible for fetching a list from my API. Thereafter, state is updated and the FlatList re renders perfectly. The other useEffect (#2) hook depends on a socket which emits any new items that have been added to the list from my API. However, this useEffect seems to have no idea that the state has been updated so when I try to use state and append the newly emitted item I only get back the new item. Adding further new items works fine since on the 2nd re-render, useEffect #2 has access to the updated state which contains the list from my API.

Example:

const [items, setItems] = useState()

useEffect(() => {
    (async () => {
        try {
            const response = await axios.get(`${getItemsUrl}`)
            //component re renders and all items are displayed. Thereafter, itemAdded event is emitted whenever a new item is added. 
            setItems(response.data)
        } catch (err) {
            console.log(err.response.data)
        }
    })()
}, [])

useEffect(() => {
    function handleItemAdded(newItem) {
        //Problem: items will be empty when the first newItem is received from the socket even though setItems was called in useEffect #1 and those initial items were already rendered on screen in a FlatList. As such, component re renders and only newItem is displayed.  
        setItems([newItem, ...items])
    }
    socket.on('itemAdded', handleItemAdded)
    return () => {
        socket.off('itemAdded', handleItemAdded)
    }
}, [socket])

Turn on/off button for a script/function in chrome extension

I am making a grade calculator extension. I am trying to make a checkbox turn on/off button for my extensition. By default it remain off and when turn on it should remain turn on untill i manually press the button again to turn off. When i turn on it does’t get turn on and when the popup page goes dispear it turn off. basically i am trying to run a script/ function when the button is turn on and not when it off. I am not trying to implement extension turn on/off button. i just want to run a script or function.

popup.html:

<!DOCTYPE html>
<html>
  <head>
    <title>Uni Grade Calulate</title>
    <meta charset="utf-8" />
    <link
      href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
      rel="stylesheet"
    />
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div class="wrapper">
      <div class="wrapper-center">
        <label class="switch">
          <input type="checkbox" id="toggleSwitch" checked />
          <div class="switch--toggle"></div>
        </label>
      </div>
    </div>
  </body>
</html>

content1.js:

chrome.storage.sync.get('toggleState', function(data) {
  const toggleSwitch = document.getElementById('toggleSwitch');
  toggleSwitch.checked = data.toggleState || false;
  updateExtensionState(toggleSwitch.checked);
});

document.getElementById('toggleSwitch').addEventListener('change', function(event) {
  const toggleState = event.target.checked;
  updateExtensionState(toggleState);
  chrome.storage.sync.set({ 'toggleState': toggleState });
});

function updateExtensionState(enabled) {
  if (enabled) {

    alert('Extension is enabled');
  } else {
    
    alert('Extension is disabled');
  }
}

manifest.json:

{
   "manifest_version": 3,
   "name": "UCP Grade Calculate",
   "version": "1.0.1",
   "description": "Uni Grade Calculate is an extension to calculate the grades of any course.",
   "icons": {
     "128": "icons/gradeblue128.png",
     "16": "icons/gradeblue16.png",
     "48": "icons/gradeblue48.png"
   },
   "action": {
     "default_popup": "popup.html",
     "default_title": "UCP Grade Calculate"
   },
   "content_scripts": [
     {
       "matches": [
         "https://uniwebsite.com/*"
       ],
       "js": [
         "content1.js"
       ]
     }
   ],
   "permissions": [
     "storage",
     "tabs"
   ]
 }

I tried search the web use chatgpt but did’nt get the right method to solve this problem.

How to autoclose a Leaflet popup with timer when mouse move out marker

It’s possible to set an autoclose timer for a popup on a marker in leaflet.

var marker1 = L.marker([46.26734, 12.328876], {icon: myIcon4}).on('mouseover', function(e){var popup = L.popup().setLatLng(e.latlng).setContent('Luoghi, Cose, Strade<br>Diga del Vajont').openOn(mappa_percorsi);}).on('click', function(e){var popup = L.popup().setLatLng(e.latlng).setContent('<a class="image-popup-no-margins hover-title" href="https://atorinfriul.it/html/gpx/Luoghi_Cose_Strade__Diga_Vajont_NOT_MINIMIZED.php"     Target="_blank" title="Diga del Vajont">   <img loading="lazy"  src="https://atorinfriul.it/html/images/luoghi_cose_strade/Fumetto-diga-del-vajont.jpg" style="width:150px;" alt="Responsive image"></a> <div class="hover-image"><img loading="lazy"  src="https://atorinfriul.it/html/images/luoghi_cose_strade/Fumetto-diga-del-vajont.jpg" alt="Responsive image"></div>').openOn(mappa_percorsi);}).addTo(LuoghiCoseStrade);

In this example, overing marker, open a popup with this message “Luoghi, Cose, Strade – Diga del Vajont”.
Clicking on marker, a new popup is show, with an image inside it, and overing image, open a modal of image zoomed up and clicking open image on a new tab.

Problem is, that if an user over the marker (opening popup) then move on rest of map, popup stay on until a new marker is overed or a click on the map is done.

That’s why I want to add a timer.

I have tried severals solutions without benefits
Putting this code, I obtain to close popup, but loose possibility, after clicking to navigate in secondary popup (that one with image).

marker1.on('mouseout', function (e) {mappa_percorsi.closePopup();});

I tryed to use this, but get an error (my js and leaflet knowledge is too limited to solve)

setTimeout(function() { popup.close();}, 5000);

Any suggestion is wellcome.

Thanks

Translating input into 12 different languages using Microsoft Translator, js, and HTML

Problem:
I am trying to translate a few words into 12 languages. I’ve been translating what I need with Google Sheets, thought it takes forever because I have to copy and past each language result into where I want it. What would save me a lot of time is if I was able to have an input field that would translate the input sting into each of the 12 languages at the push of a button.

I got a Microsoft Translator Key and region last night. I have downloaded Visual Studio 2022. I’ve been using the browser link in Visual Studio and uploading the code to Blogger. I dont code. I have a basic understanding of HTML and CSS.

I just want to input a word or two, and have other languages result below after I push the ‘Translate’ button.

Thought with the code below, nothing results. I type in a word, press the button, and nothing happens. Can anyone help me out?

<!DOCTYPE html>
<html>
<body>

<h2>Text Translation</h2>

<p><input type="text" id="myText" placeholder="Enter text to translate"></p>

 <button id="B1" onclick="translateText()">Translate</button>

<p id="zh"></p>
<p id="es"></p>
<p id="el"></p>
<p id="ja"></p>
<p id="uk"></p>
<p id="de"></p>
<p id="hi"></p>
<p id="ko"></p>
<p id="te"></p>
<p id="ar"></p>
<p id="he"></p>
<p id="am"></p>

<script>
    // Language codes according to ISO 639-1 codes
    var languages = ['zh', 'es', 'el', 'ja', 'uk', 'de', 'hi', 'ko', 'te', 'ar', 'he', 'am'];

    async function translateText() {
        var text = document.getElementById("myText").value;

        var subscriptionKey = "key";
        var endpoint = "https://api.cognitive.microsofttranslator.com/";
        var region = "region;

        languages.forEach(async function (lang) {
            var response = await fetch(endpoint + 'translate?api-version=3.0&from=en&to=' +     lang, {
                method: 'POST',
                headers: {
                    'Ocp-Apim-Subscription-Key': subscriptionKey,
                    'Ocp-Apim-Subscription-Region': region,
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify([{ 'myText': text }])
            });

            var data = await response.json();
            var translatedText = data[0].translations[0].text;
            document.getElementById(lang).innerHTML = `Translation in ${lang}:     ${translatedText}`;
            B1.addEventListener('enter',translatedText)
        });
    }
</script>

</body>
</html>`your text`

How can I resolve ‘Billing hard limit has been reached’ error while fine-tuning with OpenAI despite having paid and not reaching card limit?

I am currently finetuning using openai and i keep facing this error yet i have paid and have not reached my card limit
error: {
message: ‘Billing hard limit has been reached’,
type: ‘invalid_request_error’,
param: null,
code: ‘billing_hard_limit_reached’
}

i tried fixing the error using a new api key but it did not worktext

useMatch for multilpe patterns to test on in react-router-dom

I have the following array:

const tabsList = [
  { 
    pathPattern: 'users/'
    label: 'Manage users'
  },
  {
    pathPattern: 'users/:id',
    label: 'Edit user profile'
  }
] 

I need a method from react-router-dom to tell me which of the above array entries matches the current pathname.

Based on that, I will be able to color the active list item in my component styles.

I found the method useMatch() which looks like does almost what I want, however, it does not accept an array, it only accepts one string pattern to use for comparision.

// example: current path is /users/82374023854321
const isAllUsersMatch = useMatch('/users') // null
const isUserIdMatch = useMatch('/users/:id') // { ...PathMatch<string> } 

it works, but it’s not good, I have to create a separate variable like that for every item in the array.

Is there something like the following in react-router-dom?

const tabsList = [
  { 
    pathPattern: 'users/'
    label: 'Manage users'
  },
  {
    pathPattern: 'users/:id',
    label: 'Edit user profile'
  }
] 
const activeListItem = tabsList.some((listItem)=> doesItMatch(listItem.pathPattern))

I would have done this with the hook, but in react you can’t use a hook inside a callback, so the following would not work:

// const activeListItem = tabsList.some((listItem)=> doesItMatch(listItem.pathPattern))
const activeListItem = tabsList.some((listItem)=> useMatch(listItem.pathPattern)) // ERROR

i am having this error in my Qbcore (fivem) server on the qb-multicharacter script

i am having this error in my Qbcore (fivem) server on the qb-multicharacter script

it was working normally in the past days but today started facing this problem

TypeError: Cannot read properties of undefined (reading ‘firstname’) (@qb-multicharacter/html/vue.js:6)

i reinstalled the qb-multicharacter script but nothing fixed am getting the same error

error

this is the script link in github in case you need to take a look in the vue.js

qb-multicharacter github

(i did not make any changes on my sctript files)

Thanks!

i reinstalled the qb-multicharacter script but nothing fixed am getting the same error

it should not be stuck on the loading characters screen it must show a list of characters the player have.

How to transfer data from parent to child only after clicking the button that is in the child. REACT

As in the title, I would like to send props.pk from ExpenseItem to ExpenseDelete only when the button in ExpenseDelete is pressed. I tried a couple of things myself but it didn’t work quite the way I wanted and didn’t look very good.

ExpenseDelete.js

import "./ExpenseDelete.css";

const ExpenseDelete = () => {
  return (
    <form>
      <button className="delete-button" type="submit">
        Delete
      </button>
    </form>
  );
};

export default ExpenseDelete;

ExpenseItem.js

import "./ExpenseItem.css";
import ExpesneDate from "./ExpenseDate";
import Card from "../UI/Card";
import ExpenseDelete from "./ExpenseDelete";

const ExpenseItem = (props) => {

  return (
    <li>
      <Card className="expense-item">
        <ExpesneDate date={props.date} />
        <div className="expense-item__description">
          <h2>{props.title}</h2>
        </div>
        <div className="expense-item__price">${props.amount}</div>
        <ExpenseDelete />
      </Card>
    </li>
  );
};

export default ExpenseItem;

How can I make scrollIntoView() work in Chrome and iOS Safari for a scrollable options list with local storage?

Horizontal scroll doesn’t work, especially in Chrome and iOS Safari

I am currently working on creating a scrollable option list within the settings screen of the drawer. I would like the previously selected option to be automatically scrolled to the center when the list is opened again. (I am using local storage to reflect the selection.)

I have implemented the following code, and it works as expected in Firefox, but scrolling does not occur in Chrome and iOS Safari (although the .theme-input:checked + .theme-swatch selector is working correctly, indicating that the selection itself is done correctly). Additionally, in Firefox, it works as expected when the page is reloaded, but it does not work when the HTML file is initially opened or when accessing the server in a new tab.

<aside class="settings" id="settings">
  <header class="settings__header"><label class="settings-close" for="settingsSwitch"></label></header>
  <div class="settings__container">
      <div class="settings__page">
          <ul class="theme-list">
              <li class="theme-list__item"><input class="theme-input" type="radio" name="theme" id="themeWhite" value="white"><label class="white theme-swatch" for="themeWhite" title="White"></label></li>
              <li class="theme-list__item"><input class="theme-input" type="radio" name="theme" id="themeBlack" value="black"><label class="black theme-swatch" for="themeBlack" title="Black"></label></li>
              <!-- 以下11個 -->
          </ul>
      </div>
  </div>
</aside>
<main class="main">
</main>
.settings-input {
    display: none;
}
.settings {
    overflow: auto;
    position: fixed;
    top: 0;
    left: 0;
    z-index: 40;
    width: 100%;
    height: 100vh;
    transition: all .5s ease-in-out 0s;
    transform: translateX(100%);
}
.settings-input:checked + .settings {
    transform: translateX(0);
}
.theme-list {
    display: flex;
    overflow-x: scroll;
    gap: 1rem;
}
.theme-swatch {
    display: inline-block;
    width: 70px;
    height: 125px;
    background: var(--background-gradient);
    border-radius: 10px;
}
window.addEventListener('load', function() {
    if (window.matchMedia( '(max-width: 600px)' ).matches) {
        const themeModes = ['themeFirts', 'themeSecond', 'themethird'];
        const themeUls = document.getElementsByClassName('theme-list');
        themeModes.forEach((mode, index) => {
            const themes = document.getElementsByName(mode);
            const themeUl = themeUls[index];
            themes.forEach(theme => {
                if (theme.checked) {
                    const selectedSwatch = theme.nextElementSibling;
                    selectedSwatch.scrollIntoView({inline: 'center'});
                }
            });
        });
    }
});

Cause scrollIntoView() is a relatively recent method, I tried replacing the line include scrollIntoView with below but didn’t make a difference.

const swatchRect = selectedSwatch.getBoundingClientRect();
const ulRect = themeUl.getBoundingClientRect();
const xpos = swatchRect.left - (ulRect.left + (ulRect.width / 2)) + themeUl.scrollLeft + (swatchRect.width / 2);
themeUl.scrollLeft = xpos;

When inspecting with Chrome’s debugger, both swatchRect and ulRect have all their values set to DOMRect {x: 0, y: 0, width: 0, height: 0, top: 0, ...}. However, when I retrieve the elements and use getBoundingClientRect() in the console, it returns a DOMRect with correct integer values.

Is this a specific issue with WebKit browsers? Or could it be a fundamental problem, such as the aside element not being within the visible area during loading, which prevents scrolling?
I hope I’m not simply doing stupid…

Minified React error #423 and #418 (Math.random)

I’m trying to A/B test some ads on my React / GatsbyJS website. For that I render the ads depending if a random number is bigger or smaller than .5

I’m receiving a Minified React error #423 and Minified React error #418 error, because I’m using const randomNr = Math.random(), which React doesn’t like because the output will be different on render than on hydration.

I can’t find a simple workaround to fix this issues. I tried using useEffect, useState or useLayoutEffect, but that breaks the script of the ads. Since my method works and doesn’t break anything, I could simply ignore it, but I want to remove the error for SEO reasons. Any ideas?