Why I have different results between logging JSON.parse to console and logging parsed object

I have a JSON string like this:

{
  "operationSettings": {
    "guidelines": [
      {
        "standards": {
          "thresholdValue": "${first_threshold}"
        }
      }
    ]
  }
}

and console.log(JSON.parse(json)) prints me an object with ${first_threshold} value in operationSettings.guidelines[0].standards.thresholdValue, but operationSettings.guidelines[0].standards.thresholdValue is empty when I’m trying to parse this string to object and write it to the console like this:

const parsedJson = JSON.parse(json)
console.log(parsedJson)

This is a React project with TypeScript.

Please anyone explain me why do I get results like this and how to get value in parsed object.

First page entity call is overwritten when FCL opens second page in middle column

Object page [ProgramDetails page] makes an entity call by default whenever loaded. We navigate from this page to another page in 2 column layout, once the navigation occurs both the pages reloads the data and make necessary calls. But the object page entity call is overwritten and unable to pass correct parameters.

Problems:

  1. Can I restrict the reload and use the same session for first page?
  2. Can I define the parameter name in entity call url?
    ex:
    original call
    GET Program (ID=b73c75c2-a52f-4948-914e-36a08f534b09)?$select=ID,description&$expand=DraftAdministrativeData($select=DraftIsCreatedByMe,DraftUUID),type($select=id,name)

current call happening in first page when second page navigation occurs
GET ProgramCycles(b73c75c2-a52f-4948-914e-36a08f534b09)?$select=ID,description&$expand=DraftAdministrativeData($select=DraftIsCreatedByMe,DraftUUID),type($select=id,name)

In the url, can I modify it to pass it in the below format for params
(ID=xxx)
instead of (xxx)

The pattern and navigation is defined in the manifest directly

How to disable sockets in a jest unit test?

Is there a way to disable all sockets in a jest unit test? In python, I use pytest-socket to get hermetic tests; if I accidentally forget to mock something that talks to the network (or there’s something that’s doing so without my knowledge), this will catch it and cause my test to fail. I’m looking for something similar for jest.

most simple IF gives unexpected results

I’m new to Javascript and try to create a small script for HTML, using Firefox on Win 10. Simple idea on a simple level:
I have a WHILE loop, and inside this loop I’m using two counters: one is counting up to the end, the other counter should only count to 16 and then begin at 0 again. Here is the great code:

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <script>function makeSVG() {
  let zaehler = 0;
  let farbzaehler = 0;
  // Hauptschleife
   while (zaehler < 20) {
             window.alert("Farbe: " + farbzaehler);
             if (farbzaehler = 5) {
             farbzaehler = 0;
             }
             window.alert("zahl: " + zaehler);
            zaehler = zaehler + 1;
            farbzaehler = farbzaehler + 1;
  } 
  
    document.getElementById("demo").innerHTML = "Gezeichnet: " + zaehler + " Elemente";
    
  } 
</script> </head>
  <body>
     <input value="Symbole zeichnen" onclick="makeSVG()" type="button">
    <p id="demo"></p>
    
  </body>
</html>

The counter called “farbzaehler” begins with 0, first step to 1 – and then always stays on 1. I see that the IF causes the problem, because when it is removed it counts up endless. But I don’t understand what’s wrong with the IF. I suppose it is a real stupid formatting or syntax error, but I can’t see it.

Thanks in advance for advice!

Solidity and Javascript – Optimize Gaz passing a large UINT8Array as a parameter

I have a very simple smart contract that stores data.

The data has already been binary encoded in Javascript,

const data: UInt8Array = await compress(customBinaryEncoder(userData));

With an array size of 2000, I end up with a ridiculous amount of gaz.

How to make the best usage of uint256 solidity?

const optimizeForUint256 = (data: UInt8Array): DataFormat => {}

const Uint256toUInt8 = (data: any): UInt8Array => {}

I will then edit the contract method to accept DataFormat instead of uint8[].


 function addPatches( uint8[] memory data) public returns (bool  ok) {
     require(userIds[msg.sender] > 0, "must Be registered");
     uint64 id =  userIds[msg.sender];
     records[id].records.push(data);
     ok = true;
     return ok;
 }


No need to decode the data in solidity, it is stored as is.

How do you extend a superclass property object in a subclass in JavaScript and get TypeScript to not complain?

Given this code:

class Foo {
  data = { x: 1 };
}

class Bar extends Foo {
  override data = { ...super.data, y: 1 };
}

TypeScript complains on the super.data part:

Class field ‘data’ defined by the parent class is not accessible in the child class via super.

And in practice, it doesn’t even work.

console.log(new Foo().data)
// {x: 1}
console.log(new Bar().data)
// {y: 1}

is it possible to scrape the info behind a yahoo chart [closed]

a chart showing on the summary page will show events (ratings and earnings) as a colored dot. when hovering a bubble will display the full info. Is it possible to get that data? where should I see it in the web developer tool: which tab and what do I filter for?
I am pasting a pic just as an example, anybody can lookup any stock on yahoo. I am not asking about libraries. I know the libraries that exist for html scraping. If people who have good knowledge of html can tell me where the data is I will scrape it myself.
chart with events

Redirecting after chosing an option in select tag

I bring you a question about a <select> tag I am working for a website. I believe that the code I am writing here should be okay, but considering that I am quite new to js (I mainly know the basics of html and css, though it has been a while since I have worked with front-end web design :p), it is not surprising that it isn’t working.

Basically, I have a <select> tag with different language options, and when clicking on one, you should be redirected to the page in the language you have selected. My attempt, with the little knowledge I have, was to get the info of the select tag, retrieving the value in the var direction to then open the link to the desired href.

Here is the code of the html (I post here only the header of basic_en.html, where the <select> is found):

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0"> 

        <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Symbols+Outlined" />
        <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Symbols+Outlined" />

        <link rel="stylesheet" href="style.css">
        <script src="app.js"></script>
        <title>Website</title>
    </head>
    <body>
        <div class="header">
            <nav>
            <ul class="sidebar">
                <li onclick=hideSidebar() class="item-nav">
                    <a>
                        <span class="material-symbols-outlined">
                            close
                        </span>
                    </a>
                </li>
                <li class="item-nav">
                    <h4><a href="basic_en.html">Home</a></h4>
                </li>
                <li class="item-nav">
                    <h4><a href="#">CV</a></h4>
                </li>
                <li class="item-nav">
                    <h4><a href="#">Contact</a></h4>
                </li>
                <li class="item-nav select-container">
                    <select id="lang-box">
                        <option class="item-lang" value="basic_en.html" onclick=changeLang()>EN</option>
                        <option class="item-lang" value="basic_es.html" onclick=changeLang()>ES</option>
                        <option class="item-lang" value="basic_fr.html" onclick=changeLang()>FR</option>
                    </select>
                </li>
            </ul>
            <ul class="nav">
                <li class="item-nav">
                    <h4><a href="basic_en.html">Name Surname</a></h4>
                </li>
                <li class="item-nav hide-maxwidth">
                    <h4><a href="#">CV</a></h4>
                </li>
                <li class="item-nav hide-maxwidth">
                    <h4><a href="#">Contact</a></h4>
                </li>
                <li class="item-nav select-container hide-maxwidth">
                    <select id="lang-box">
                        <option class="item-lang" value="basic_en.html" onclick=changeLang()>EN</option>
                        <option class="item-lang" value="basic_es.html" onclick=changeLang()>ES</option>
                        <option class="item-lang" value="basic_fr.html" onclick=changeLang()>FR</option>
                    </select>
                </li>
                <li onclick=showSidebar() class="item-nav menu-btn">
                    <a>
                        <span class="material-symbols-outlined">
                            menu
                        </span>
                    </a>
                </li>
            </ul>
            </nav>
        </div>

The CSS, the document style.css:

*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
.header{
    color: white;
    width: 100%;
}
nav{
    background-color: black;
    width: 100%;
    height: 6.5rem;
    position: fixed;
    z-index: 68;
}
.nav{
    display:flex;
    justify-content: flex-end;
    align-items: center;
    width: 100%;
}
.item-nav{
    list-style: none;
    margin-right: 2rem;
    font-size: 1.25rem;
}
.item-nav a{
    text-decoration: none;
    color: white;
}
.item-nav:first-child{
    margin-right: auto;
    margin-left: 2rem;
    font-size: 4rem;
}
.sidebar{
    position: fixed;
    top: 0;
    right: 0;
    height: 100dvh;
    height: 100vh;
    width: 180px;
    z-index: 69;
    background-color: black;
    color: white;
    display: none;
    flex-direction: column;
    align-items: flex-start;
    justify-content: flex-start;
    gap: 1rem;
    float: right;
    padding: 1rem;
}
.sidebar ul{
    width: auto;
}
.menu-btn{
    display: none;
}
.select-container{
    position: relative;
    width: 2rem;
}
#lang-box{
    border: none;
    appearance: none;
    width: 100%;
    color: white;
    background-color: black;
    cursor: pointer;
    font-family: Cabin;
    font-size: 1.25rem;
}
.item-lang{
    background-color: black;
    border-radius: 0;
}
@media only screen and (max-width: 930px){
    .hide-maxwidth{
        display: none;
    }
    .menu-btn{
        display: block;
    }
}

And the little JS involved in app.js:

/* Here is where I tried the redirection */
function changeLang(){
    var select = document.getElementById('lang-box');
    var direction = select.options[select.selectedIndex].value;
    window.location.href = direction;
}
/* Functionality of sidebar (and yes, I know it does not close when the viewport is too big, I am working on it hahaha)*/
function showSidebar(){
    const sidebar = document.querySelector('.sidebar');
    sidebar.style.display = 'flex';
}
function hideSidebar(){
    const sidebar = document.querySelector('.sidebar');
    sidebar.style.display = 'none';
}

If you could indicate me what is wrong as well as any further advice to improve on JS (or in css as well), I would greatly appreciate it. Thanks in advance 🙂

empty videos are uploading in bunny.net in javascript

I am uploading videos in bunny.net stream with JavaScript videos are uploading success fully but videos are empty and corrupted.

please help me it is very important to complete it thanks

here is my code:

const fileInput = document.getElementById('videoFile');
           
            let file = fileInput.files[0];
            console.log(file);
            video_name = file.name;
            let video;
            const toBase64 = file => new Promise((resolve, reject) => {
                const reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onload = () => resolve(reader.result);
                reader.onerror = error => reject(error);
            });
async function Main() {
                video = await toBase64(file);
            }
            
           video =  Main();
        
            const options = {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                accept: 'application/json',
                AccessKey: 'e3214df7-7dba-4a74-b93649716004-454b-46c3'
            },
            body: JSON.stringify({ 'title': video_name }),
            
         };

        result = fetch('https://video.bunnycdn.com/library/390820/videos', options)
        .then(res => res.json())
        
        .then(res => {
               videoId = res.guid;
               console.log(videoId);
                const options = {
                method: 'PUT',
                headers: {
                    AccessKey: 'e3214df7-7dba-4a74-b93649716004-454b-46c3',
                    'Content-Type': 'application/octet-stream',
                },
                data: video,
                };

                fetch(`https://video.bunnycdn.com/library/390820/videos/${videoId}`, options)
                .then(res => res.json())
                .then(res => console.log(res))
                .catch(err => console.error(err));
            })
        .catch(err => console.error(err));

want solution of that its important

JS `os` method not returning any data in Vite project

My goal is to collect and graph CPU usage for the host. I have a simple Vite project and am using vite-plugin-node-polyfills to try to use the os JS method. However, it just returns an empty object. I don’t have any console errors. Why isn’t the method able to access the underlying host?

vite-config.js:

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import nodePolyfills from 'vite-plugin-node-polyfills'

// https://vite.dev/config/
export default defineConfig({
  plugins: [
    react(), 
    nodePolyfills({
      globals: {
        Buffer: true, 
        global: true,
        process: true,
      },
      protocolImports: true,
    })],
})

My various console logs/dirs to test the data:

  console.dir(os.cpus, { depth: null })
  let cpus1 = os.cpus().length
  let avg = os.loadavg()[0]/cpus1
  let load = os.loadavg()
  console.log("load "+load)

Failed React test with console message: “Cannot find module ‘react-router-dom'”

I’m making a unit test in a React application (that i created with the command “create-react-app” without using any framework or build tool), that i am developing for a university project, using Jest and React Testing Library. One of the modules that i’m importing in the test file is the one below

import { BrowserRouter } from "react-router-dom";

I have this dependency installed in my package.json file, but i keep receiving the message below every time i try to start the test

Test suite failed to run
                                                                                                 
    Cannot find module 'react-router-dom' from 'src/App.test.js'                                 
                                                                                                 
      1 | import React from "react";                                                             
      2 | import { render, screen } from "@testing-library/react";                               
    > 3 | import { BrowserRouter } from "react-router-dom";
        | ^
      4 | import App from "./App";

I’ve tried to reinstall my dependencies, but it didn’t work. Here is my package.json file:

{
  "name": "apoiaacao",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "axios": "^1.7.9",
    "bootstrap": "^5.3.3",
    "cra-template": "1.2.0",
    "react": "^18.2.0",
    "react-confirm-alert": "^3.0.6",
    "react-dom": "^18.2.0",
    "react-router-dom": "^7.1.5",
    "react-scripts": "^5.0.1",
    "react-toastify": "^11.0.3",
    "web-vitals": "^4.2.4"
  },
  "scripts": {
    "start": "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": {
    "@testing-library/jest-dom": "^6.6.3",
    "@testing-library/react": "^16.2.0",
    "eslint": "^8.57.1",
    "eslint-config-prettier": "^10.0.2",
    "jest": "^27.5.1",
    "prettier": "3.5.2",
    "prettier-eslint": "^16.3.0"
  }
}

I don’t know why i can’t run the test properly. I’ve seen some posts with problems similar to mine, but none of the solutions in the comments of those posts solved my problem. Maybe the only solution is to do a transition of my project to a Vite + React application.

How can I save a randomly generated array to an object property in js?

This is what I’m working with and I have no idea what I’m doing wrong here but I’m trying to assign dna to the mockUpStrand value and have it stay the same when I run the code each time but every time I run it the value of dna changes I just can’t figure out how to keep it the same

const returnRandBase = () => {
  const dnaBases = ['A', 'T', 'C', 'G']
  return dnaBases[Math.floor(Math.random() * 4)] 
}

const mockUpStrand = () => {
  const newStrand = []
  for (let i = 0; i < 15; i++) {
    newStrand.push(returnRandBase())
  }
  return newStrand
}

const pAequorFactory = (num, arr) => {
  return {
    _specimenNum: num,
    _dna: arr
    }
}

const ex1 = pAequorFactory(1, mockUpStrand());

console.log(ex1._dna);

First time I logged to the console the array was [‘G’, ‘C’, ‘T’, ‘T’, ‘A’, ‘G’, ‘A’, ‘C’, ‘C’, ‘T’, ‘T’, ‘T’, ‘G’, ‘C’, ‘A’]

Second time it was [‘A’, ‘C’, ‘G’, ‘A’, ‘C’, ‘G’, ‘C’, ‘C’, ‘G’, ‘C’, ‘C’, ‘G’, ‘G’, ‘C’, ‘C’]

And it’s different every time

Cypress Tests failing in Headless mode for API execution

I am developing an API testing backend using Cypress with cy.request. I am aware that cy.request natively uses built-in promises (Cypress.Chainable), so there is no need to handle it with JavaScript promises.

However, my requirement is to call test APIs with single calls, without chaining .then conditions.

Currently, my code works properly in Cypress UI mode. But in headless mode, the second request fails with the error: “Cypress test was stopped while running this command.” I suspect the issue is related to JavaScript promise handling and asynchronous behavior.

Despite trying multiple solutions, I haven’t been able to fix this issue. I need to make this work using a promise-based approach. Please help me or suggest a fix.

headless run command : npx cypress run –headless –spec ‘pathtofile’

//following is the full working code with a public API

const newPet= {
    "name": "jkysssssss",
    "data": {
       "year": 2017,
       "price": 4589,
       "CPU model": "Intel eeeeeee",
       "Hard disk size": "1 TB"
    }
}


export function makeRequest(requestOptions :any) {
  return new Promise((resolve, reject) => {
      // Make the request using cy.request with the provided requestOptions
      cy.request(requestOptions).then((res) => {
          if (!res || !res.body) {
              return reject(new Error('No response body returned from request.'));
          }
          
          // Ensure response body is an object
          if (typeof res.body !== 'object' || res.body === null) {
              res.body = { data: res.body };
          }

          // Add status to the response
          res.body.status = res.status;

          // Log the response
          cy.log(JSON.stringify(res.body));

          // Resolve the promise with the response body
          resolve(res.body);
      })
  });
}


describe('API Tests', () => {
    it('should make a POST request and handle the response', async () => {
        const requestOptions = {
            method: 'POST',  // HTTP method
            url: 'https://api.restful-api.dev/objects',  // API URL
            headers: {
                'Content-Type': 'application/json',
            },
            body: newPet,
        };

   //request calls
      await  makeRequest(requestOptions);
    await  makeRequest(requestOptions);

    });
});

Why doesn’t the GSAP animation here work?

I am trying to animate this SVG logo on my website, but it doesn’t seem to work. Here is the code:

import { useEffect, useRef } from 'react'
import gsap from 'gsap-trial'
import DrawSVGPlugin from 'gsap-trial/DrawSVGPlugin'
import LogoS from '../../../assets/images/logo-s.png'
import './index.scss'

const Logo = () => {
  const bgRef = useRef()
  const outlineLogoRef = useRef()
  const solidLogoRef = useRef()

  useEffect(() => {
    gsap.registerPlugin(DrawSVGPlugin)

    gsap
      .timeline()
      .to(bgRef.current, {
        duration: 1,
        opacity: 1,
      })
      .from(outlineLogoRef.current, {
        drawSVG: "0%",
        duration: 20,
      })

    gsap.fromTo(
      solidLogoRef.current,
      {
        opacity: 0,
      },
      {
        opacity: 1,
        delay: 4,
        duration: 4,
      }
    )
  }, [])

  return (
    <div className="logo-container" ref={bgRef}>
      <img
        className="solid-logo"
        ref={solidLogoRef}
        src={LogoS}
        alt="JavaScript,  Developer"
      />

      <svg
        width="559pt"
        height="897pt"
        version="1.0"
        viewBox="0 0 559 897"
        xmlns="http://www.w3.org/2000/svg"
      >
        <g
          className="svg-container"
          transform="translate(0 457) scale(.1 -.1)"
          fill="none"
        >
          <path
            ref={outlineLogoRef}
            d="*svg paths*"
          />
        </g>
      </svg>
    </div>
  )
}

export default Logo

The CSS code for the SVG has the necessary stroke values so I’m pretty sure that isn’t the problem:

.svg-container {
  stroke: #ffd700;
  stroke-width: 10;
}

What I see on the page is the logo fading in (the opacity going from zero to one) after a while, so it seems to be skipping that animation step.

Google apps script, web app invokes CORS policy

I’ve been working on a Website, and wanted to use Google Sheets as my database for some god-aweful reason. In the Google Apps Script, I have a switch statement within the doGet method to get the path info.
Like so:

function doGet(e)
{
   let output = "";
   path = e.pathInfo.split("/");
   switch(path[0])
   {
      case "Employees":
         if(path.length > 1)
         {
            output = getEmployeeByName(path[1]);
         }
         else
         {
            output = getAllEmployees();
         }
      break;
      case "Tasks":
         output = getAllTasks();
      break;
   }
   return ContentService.createTextOutput(JSON.stringify(output)).setMimeType(ContentService.MimeType.JSON);
}

Then, in my front end, using React.js, I try to fetch the URL link taken from the deployment.

 try
 {
  fetch(this.url +"/Employees", {
    redirect: "follow",
    method: "GET",
    headers: {
      "Content-Type": "text/plain;charset=utf-8",
    },
  })
 }
 catch (err)
 {
  console.log(err);
  return "Something messed up: ";
 }

The problem is that this above call gets blocked by CORS policy, but removing the extra path (And just calling fetch(this.url)) doesn’t. I’m not entirely sure how to fix CORS errors, but I can confirm everything else works (Using the url and path in a web browser returns the right data).