Number Overflow in Javascript

How does this happen?

console.log(84.8 + 0.1) => 84.89999999999999

I know about number overflow when reaching Number.MAX_VALUE but I cant find any information why javascript struggles with such an easy addition.

Unfortunately I don“t know what to google.

CK-editor: block deletion of span element

I have created a inline widget with refference from here

enter image description here

I wrote a function to prevent the deletion when user tries to. this works fine when user tries to backspace and delete the span widget.

editor.listenTo( editor.editing.view.document, 'delete', event => {
    const ranges = event.currentTarget.selection.getRanges(); // multiple ranges are possible.
    for ( const range of ranges ) { 
        for ( const value of range.getWalker( {
            ignoreElementEnd: true
        } ) ) {
            if ( value.item.is( 'element', 'span' ) ) {
                console.log( value.item );
                event.stop(); // stop deletion when span is found.
            }
        }
    }
} );

But when user click the span (select) and press some key, the item get deleted and the delete event is not get triggering.

Is there any way i can block the user selecting the span element from CK-editor. I have tried using user-select:none and pointer-events:none option in css. but its still able to select via arrow key. Is there any way to avoid replacing if some user click on the span and try to write something ?

Calculate sum of dynamic property of array of objects fetched from a form in Javascript

0:

items:

Sobhan PId: “1”
Sobhan PName:
“Sobhan P”
Sobhan PScore: 100

1:

items:

Sobhan PId: “5”
Sobhan PName: “Sobhan P”
Sobhan PScore: 300

2:

items:

RajeshId: “5”
RajeshName: “Rajesh”
RajeshScore: 300

Properties are dynamic based on the form but need to calculate the score of each individual property like Rajesh to total score

Properties are dynamic based on the form but need to calculate the score of each individual property like Rajesh to total score

Issue with Java program execution and input handling in a web-based code submission platform

I am currently building a basic web-based platform for Java coders, where users can submit their code to solve a given problem statement. I have implemented the front-end code using** HTML and JavaScript**, and the back-end server-side code using Express.js and child_process. However, I am facing issues with executing Java programs that require user input during runtime.
**
Here is a summary of my setup:**

Front-end: I have a form with a textarea where users can enter their Java code. Upon submission, the code is sent to the server for execution.
Server-side: The server receives the code, writes it to a temporary Java source file, and then uses spawn to execute the Java program. If the code compilation is successful, it proceeds to execute the compiled Java class.

Issue: The execution is working fine for Java programs without user input. However, for programs that require user input during runtime, I am not able to provide the input from the server side and receive the output on the front-end.
Here is an example of a Java program that requires user input:

import java.util.Scanner;

public class HelloWorld {
    public static void main(String[] args) {
        int num1, num2, sum;
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter First Number: ");
        num1 = sc.nextInt();
        System.out.println("Enter Second Number: ");
        num2 = sc.nextInt();
        sc.close();
        sum = num1 + num2;
        System.out.println("Sum of these numbers: " + sum);
    }
}

Here is the Front End Code and Backend server code.

Front End code

<!DOCTYPE html>
<html>
<head>
  <title>Code Submission Platform</title>
  <style>
    #codeForm {
      margin-top: 20px;
    }
    label {
      display: block;
      margin-bottom: 10px;
    }
    textarea {
      width: 100%;
      height: 200px;
    }
    button {
      margin-top: 10px;
    }
    #result {
      margin-top: 20px;
    }
  </style>
</head>
<body>
  <h1>Code Submission Platform</h1>


  <form id="codeForm">
    <label for="code">Enter your code:</label>
    <textarea id="code" name="code" placeholder="Enter your code here"></textarea>
    <button type="submit">Submit</button>
  </form>

  <div id="result"></div>

  <script>
    const form = document.getElementById('codeForm');
    const resultDiv = document.getElementById('result');

    form.addEventListener('submit', function(e) {
      e.preventDefault();

      // Get the code from the textarea
      const code = document.getElementById('code').value;

      // Send the code to the backend API
      // Replace `API_URL` with the actual URL of your backend API
      fetch('http://localhost:3000/compile', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ code })
      })
      .then(response => response.json())
      .then(data => {
        // Display the result in the resultDiv
        resultDiv.innerHTML = `<h2>Result:</h2><pre>${data.result}</pre>`;
      })
      .catch(error => {
        console.error('Error:', error);
        resultDiv.innerHTML = '<h2>Error:</h2><p>Something went wrong. Please try again later.</p>';
      });
    });
  </script>
</body>
</html>

And here is the Backend code.

const express = require('express');
const { spawn } = require('child_process');

const app = express();
const port = 3000;

app.use(express.json()); // Parse JSON request bodies

app.use(function(req, res, next) {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
  next();
});

// Endpoint to handle code submission
app.post('/compile', (req, res) => {
  const { code } = req.body; // Assuming the code is sent as a JSON object with a "code" property

  if (!code) {
    res.status(400).send({ error: 'Code is missing' });
    return;
  }

  // Create a temporary Java source file
  const sourceFilePath = '/Users/shubham/Desktop/Coding Tool/HelloWorld.java';
  const fs = require('fs');
  fs.writeFileSync(sourceFilePath, code);

  // Run the Java compiler
  const compiler = spawn('javac', [sourceFilePath]);

  // Handle the compiler output
  compiler.stdout.on('data', data => {
    console.log(`Compiler output: ${data}`);
  });

  compiler.stderr.on('data', data => {
    console.error(`Compiler error: ${data}`);
  });

  compiler.on('close', code => {
    if (code === 0) {
      // Execute the compiled Java class file
      const execution = spawn('java', ['-cp', '/Users/shubham/Desktop/Coding Tool', 'HelloWorld']);

      let executionOutput = '';

      execution.stdout.on('data', data => {
        executionOutput += data.toString();
      });

      execution.stderr.on('data', data => {
        console.error(`Execution error: ${data}`);
      });

      execution.on('close', code => {
        console.log('Sending response:', executionOutput);
        res.send({ result: executionOutput });
      });
    } else {
      console.log('Sending response: Compilation failed!');
      res.send({ result: 'Compilation failed!' });
    }
  });
});

// Start the server
app.listen(port, () => {
  console.log(`Server running on port ${port}`);
});



I have tried passing the input from the front-end to the server and then sending it to the Java program, but I’m not getting any output in response.

I would appreciate any insights or suggestions on how to handle user input for Java programs in my web-based code submission platform. How can I modify my server-side code to handle user input during runtime and receive the output on the front-end?

Thank you in advance for your help!

I was Expecting the Output 10 as result of First number 5 and Second Number 5 and returned back to frontend, but this inputs should be stored in server side, and if there is program with no input require it should work as it is.

how can i make it conform to setstate rules?

enter image description here

function App() {
  const cards = useSelector(selectCards)
  const point = useSelector(selectPoint)
  const status = useSelector(selectCardStatus)
  const dispacth = useDispatch()
  useEffect(() => {
    dispacth(randomCard())  }, [dispacth])

  const handleReload = () => {
    dispacth(reload())
  }
  dispacth(winCard())
}

react-dom.development.js:86 Warning: Cannot update a component (App) while rendering a different component (App). To locate the bad setState() call inside App, follow the stack trace as descri
i am getting error how can i solve it?
How can I run dispatch without any errors?

HTML Password Input Field with partial hidden content

I need a password-like input field with the following behavior:

When the field is rendered, the current contents must be hidden with password style * excluding the last 5 digits which needs to be revealed (i.e. *****11111). The original data still needs to be preserved and pass data validation for a valid telephone number.

Any idea on how to achieve this behavior using a regular password input field or similar? Thanks

Not rendering Salix’s counter example

Using the example given in Salix’s github, I’ve been unable to correctly render the counter app.

I have used the code provided to create the view, update and init functions. Then I have created the app using the following function.

SalixApp[Model] counterApp(str appId = "counterApp") = makeApp(appId, init, view, update);

and created the web application using

App[Model] counterWebApp() 
      = webApp(counterApp(), |file:///.../index.html|, |file:///...|); 

Also, I have used the necessary scripts in the HTML file.

Some other things: I have, as far as I know, updated the correct paths, and the appId, the string in the new Salix(“”) function, and the div id are all the same.

Yet, when I run the counterWebApp, it renders a blank page and gives me the following error message:

Uncaught TypeError: Cannot read properties of undefined (reading 'edits')
    at patchDOM (salix.js:257:30)
    at render (salix.js:84:3)
    at Object.step [as success] (salix.js:73:3)
    at j (jquery-1.11.0.min.js:2:27136)
    at Object.fireWith [as resolveWith] (jquery-1.11.0.min.js:2:27949)
    at x (jquery-1.11.0.min.js:4:22244)
    at XMLHttpRequest.b (jquery-1.11.0.min.js:4:26298)

Going to http://localhost:9051/counterApp/init shows me the all the HTML elements I’ve defined in the view function.

What am I doing wrong?

What I tried and what I was expecting is mentioned in the post above.

Comparing arbitrarily nested objects and arrays by value Javascript [duplicate]

I have two pieces of data i need to compare, which could consist of any combination of nested objects and arrays, for example:

let myObject = {
    a: [
        { x: 1, y: 2 },
        { x: 3, y: 4 }
    ],
    b: [1, 2, 3]
}

If i created a second object (say myObject2) defined exactly the same as above (in reality this second object is coming from localStorage), and check myObject == myObject2, it will be false. How can i compare this kind of data by value, such that if the property names/values and array elements all match, it returns true, otherwise false?

react-native-iap Issue with setting IOS In App Purchase

I have this code and it’s working on Android. but For IOS it is not.
I created a new In app purchase Item with product Id in app store connect, and it saved under drafts. I used the same id in getProducts but it didn’t work. What I am doing wrong ??

Also I’m getting an error in my catch sku is required for IOS purchase

import { useEffect } from 'react';
import { useRef } from 'react';
import {
  initConnection,
  purchaseErrorListener,
  purchaseUpdatedListener,
  flushFailedPurchasesCachedAsPendingAndroid,
  finishTransaction,
  requestPurchase,
  getProducts,
} from 'react-native-iap';
import { Platform } from 'react-native';
import { useCallback } from 'react';
import { useNavigation } from '@react-navigation/native';

import { useSaveInAppPurchaseMutation } from '../store/queries/paymentAPI';

const useReactNativeIAP = ({ productId, postId, handleFinish }) => {
  const navigation = useNavigation();
  let purchaseUpdateSubscription = useRef(null);
  let purchaseErrorSubscription = useRef(null);
  const [savePurchase] = useSaveInAppPurchaseMutation();

  //Get the current OS
  const appType = Platform.OS;

  const getProductsList = useCallback(async () => {
    try {
      const res = await getProducts({
        skus: ['boost_ad_for_a_month'],
      });
      console.log('RES:: ', res);
    } catch (err) {
      console.warn(err);
    }
  }, [productId]);

  useEffect(() => {
    const fetchData = async () => {
      const connection = await initConnection();
      if (connection) {
        await getProductsList();
      }

      try {
        if (Platform.OS === 'android') {
          await flushFailedPurchasesCachedAsPendingAndroid();
        }
      } catch (error) {
        console.warn('flush error', error.code, error.message);
      }

      purchaseUpdateSubscription.current = purchaseUpdatedListener(
        async (purchase) => {
          const receipt = purchase.transactionReceipt;
          if (receipt) {
            const savePurchaseResponse = await savePurchase({
              receipt,
              productId,
              postId,
              appType,
            });
            finishTransaction({ purchase, isConsumable: true });
            if (savePurchaseResponse?.order?.items?.[0]?.postId) {
              handleFinish();
            }
          }
        }
      );

      purchaseErrorSubscription.current = purchaseErrorListener((error) => {
        console.warn('purchaseErrorListener', error);
      });
    };

    fetchData();

    return () => {
      if (purchaseUpdateSubscription?.current) {
        purchaseUpdateSubscription.current?.remove();
        purchaseUpdateSubscription.current = null;
      }

      if (purchaseErrorSubscription) {
        purchaseErrorSubscription?.current?.remove();
        purchaseErrorSubscription.current = null;
      }
    };
  }, [
    appType,
    getProductsList,
    handleFinish,
    navigation,
    postId,
    productId,
    savePurchase,
  ]);

  const purchase = async () => {
    try {
      await getProductsList();
      await requestPurchase({
        skus: [productId],
        andDangerouslyFinishTransactionAutomaticallyIOS: false,
      });
    } catch (err) {
      console.warn(err);
    }
  };

  return {
    purchase,
    getProductsList,
  };
};

export default useReactNativeIAP;

Could the issue be is that my In-App Purchase is in Draft section in app store connect, if yes what should I do to change that ?

Host SvelteKit project in Microsoft IIS

I’ve been trying to deploy a svelte application into an IIS server my company has provided. I’ve tried using this adapter, but i couldn’t manage to make it work.

Should I keep on trying on maybe suggest some other solution, like express?

Thanks for the help.

Function to capitalize first three letters on each word within given array JavaScript

thanks in advance for your help. I wrote a function that takes in a single word and capitalizes the first three letters. Now I need to run this same function on an array of words, so that it returns each word with the first three letters capitalized. I see there’s a lot of people asking how to capitalize the first letter on each word of a sentence, but this is not the same thing. I have to use the function I already wrote so when i console.log it it looks like this:

console.log(applyAll(['str1', 'str2', 'str3', 'str4'], capitalizeThreeLetters));

I tried doing this using a for loop which returns every word together. In my research I saw the forEach() method could be used to run a function on array elements but I cannot figure out how to apply it. Appreciate a nudge in the right direction.


//Function that takes in str returns it with three first letters capitalized

function capitalizeThreeLetters(str){

  let capFirst = str[0].toUpperCase();
  let capSecond = str[1].toUpperCase();
  let capThird = str[2].toUpperCase();

  let splitStr = str.slice(3);

  let wholeStr = capFirst + capSecond + capThird + splitStr;
  return wholeStr;
}

console.log(capitalizeThreeLetters('testing')); // => returns 'TESting'
console.log(capitalizeThreeLetters('again')); // => returns 'AGAin'



//Function that takes in a string array and applies capitalizeThreeLetters function to each array element so each word is returned with first three letters capitalized

function applyAll(arr){
  
  for (let i = 0; i < arr.length; i++){
  return capitalizeThreeLetters(arr);
  }
}  

console.log(applyAll(['mai', 'brian', 'jeho', 'han'], capitalizeThreeLetters)); 
// => returns 'MAIBRIANJEHOhan'
// => should return ['MAI', 'BRIan', 'JEHo', 'HAN']

How to change the font in tables? setFont() only changes the title font

I am writing a Vue method to generate a PDF file of my data. I am trying to apply the font type ‘newFontType’ to the text on the table.

        generatePDF() {
            let doc = new jsPDF({ orientation: 'l', format: 'a4' });
            doc.addFileToVFS('NEWFONT.TTF', NEWFONTS);
            doc.addFont('NEWFONT.TTF', 'newFontType', 'normal');
            doc.setFont('newFontType');
            doc.setFontSize(20);

            let header = ['id', 'name', 'quantity'];
            const title = 'All Data';
            const titleWidth = (doc.getStringUnitWidth(title) * doc.internal.getFontSize()) / doc.internal.scaleFactor;
            const xPos = (doc.internal.pageSize.getWidth() - titleWidth) / 2;
            const yPos = 20;
            doc.text(title, xPos, yPos);
            doc.setFont('newFontType', 'normal');
            doc.table(10, 30, this.data, header);

            doc.save('Report1' + '.pdf');

            doc = null;
        },

I tried doc.table(10, 30, this.data, header,styles: { font:’newFontType’}); but it doesnt work
I need help please. Thank you.

Saving and Downloading Image Files with videojs-record Plugin

I’m currently working with the videojs-record plugin for capturing videos and taking snapshots using a webcam in my web application. I’ve successfully implemented the recording functionality, and I’m able to save the recorded video files directly and offer them as a download to users.

However, I’m facing a challenge when it comes to saving and downloading the captured image files. With the videojs-record plugin, I can capture snapshots, but I’m unsure how to save these snapshots as image files on the server and provide a download link to users.

Here’s a simplified version of my code:

<video id="my-video" class="video-js"></video>
<button id="captureImage">Capture Image</button>

<script>
document.addEventListener("DOMContentLoaded", function() {
  const captureImageButton = document.getElementById("captureImage");
  let options = {
    plugins: {
      record: {
        image: true,
        imageOutputFormat: "image/jpeg",
        debug: true
      }
    }
  };
  let player = videojs("my-video", options);

  player.ready(function() {
    player.record().getDevice();
  });

  captureImageButton.addEventListener("click", function() {
    player.record().snapshot();
  });

  player.on("finishRecord", function() {
    // Logic to save the video file works fine
    // Need assistance on saving and downloading the captured image file
  });
});
</script>

I’m looking for guidance on how to save the captured image files as individual image files (e.g., JPEG or PNG) on the server and then offer a download link to users. Ideally, I’d like to trigger the download automatically upon capturing the image, but a manual download link would also be acceptable.

Any insights or suggestions on how to accomplish this would be greatly appreciated. Thank you in advance for your help!

i tried using player.record().saveAs({'image': 'file.jpg'});
because i used it for video (player.record().saveAs({'image': 'file.jpg'});) and it worked for that.

BambooHR API retrieve data

I am trying to get all the data from bambooHR. I use method GET and used “https://api.bamboohr.com/api/gateway.php/companydomain/v1/employees/directory” as the URL in appscript. The data does appear but when I try to include the birthdate, gender, address1. It is just blank. Is there other way, I can get these data?

I tried method POST and “https://api.bamboohr.com/api/gateway.php/companydomain/v1/reports/custom” but I get 404 error.

By the way, still newbie to this.

Any help would greatly be appreciated.

Thank you.

guide on how to get the data

How can I make my chrome extension constantly listen for a keyword like Alexa?

I have absolutely no javascript experience so please forgive my probably very awful code; I am painfully struggling through this project and have finally met a road block I cant seem to solve.

I want to use speechRecognition in my chrome extension to constantly listen for a keyword, in this case, “Spect.” Once the keyword is recognized, a second speech recognition fires and captures the user’s spoken question/prompt. Right now, the ListenerRecognition object runs for one cycle once the user changes tabs before stopping. I want to make it constantly run, listening for the keyword just like Alexa/Google Home does.

This is my content script:

    //speechRecognition.js

//initial recognition, listening for keyword "spect"
let ListenerRecognition = new webkitSpeechRecognition() || new SpeechRecognition();
//second recognition, will capture user's response
let recognition = new webkitSpeechRecognition() || new SpeechRecognition();

recognition.continuous = false;
recognition.lang = "en-US";
recognition.interimResults = false;
recognition.maxAlternatives = 10;

grammar = "#JSGF V1.0; grammar activation; public <activation> = [spect];";

speechRecognitionList = new webkitSpeechGrammarList();
speechRecognitionList.addFromString(grammar, 1);
ListenerRecognition.grammars = speechRecognitionList;

ListenerRecognition.continuous = false;
ListenerRecognition.lang = 'en-US';
ListenerRecognition.interimResults = false;
ListenerRecognition.maxAlternatives = 1;

recognition.onresult = function (event) {
  const transcript = event.results[0][0].transcript;
  chrome.runtime.sendMessage({ transcript: transcript });
  chrome.runtime.onMessage.addListener((message) => {
    if(message.TTSComplete == "TTS Complete"){
      recognition.stop();
      ListenerRecognition.start();
    }
  });
};

recognition.addEventListener("speechend", (event) => {
  var audio = new Audio(chrome.runtime.getURL("spectEnd.mp3"));
  audio.play();
});



ListenerRecognition.onresult = function (activationEvent) {
  const ListenerTranscript = activationEvent.results[0][0].transcript;
  chrome.runtime.sendMessage({ListenerTranscript: ListenerTranscript });
  if(activationEvent.results[0][0].transcript == "spect" || activationEvent.results[0][0].transcript == "expect")
  {
    var audio = new Audio(chrome.runtime.getURL("spectStart.mp3"));
    audio.play();
    ListenerRecognition.stop();
    recognition.start();
  };
};

ListenerRecognition.start();

Using a simple loop to restart the ListenerRecognition object every time it stops doesn’t seem to work because the recognition thinks is already running.

On top of constantly listening, I realize that the ListenerRecognition will probably need to be implemented in a way that ensures it is only running once at a time; I’m thinking that everytime the user switches tabs, I need to stop it on the previous tab and restart it on the current tab.

There’s also issues with the two speechRecognition objects being declared every time the user goes back to a tab, causing: Uncaught SyntaxError: Identifier ‘ListenerRecognition’ has already been declared

Any tips or recommendations would be very much appreciated!