populate my throw object with error message in json response

I want to populate my error object {'status': response.status, 'msg': ''} with the error message present in the JSON Response of the API if there is any, otherwise throw the error object without any message.
But throw {'status': response.status, 'msg': ''} statement is hit before the json_response promise is evaluated and everytime i get the empty message.

How can I populate the message attribute in my error object?


    return await fetch(url.toString(), {
        method: 'post',
        headers: get_headers(url, request_body),
        body: JSON.stringify(request_body)
    })
        .then((response) => {
            console.log(`API Status: ${response.status} API ${url.toString()}`)

            if (!response.ok) {
                // response.json()
                //     .then(json_response => {
                //         console.log(json_response)
                //         logger.error(json_response)
                //         throw {'status': response.status, 'msg': json_response?.errorMessage?.message}
                //     })
                //     .catch((e)=>{
                //         throw e
                //     })
                throw {'status': response.status, 'msg': ''}
            }

            return response.json()
        })
        .then((json_response) => {
            return json_response

        })
}

Why do i not get a 3d array in javascript when i use nester for loops?

I am trying to log a 3d array to the console in javascript, then clone it, and log the clone. if this is the only code i write, it works perfectly fine, but once i start to process the cloned 3d array within a 4x nested for loop, even after I’ve logged both of them, they start to break. they no longer display as 3d arrays in the console. They display as 1d arrays of length 64. Surely what i do here on line 4 should never affect the output of line 3? is this an issue with my code? or with chrome? or with javascript? my apologies if this is a bad question, I am new to the language.

`function thetaStep(state) {

console.log(state);
let temporaryState = state;

for (let x = 0; x < 5; x++) {
    for (let y = 0; y < 5; y++) {         
        for (let z = 0; z < 64; z++) {
            temporaryState[x, y, z] = state[x, y, z]
            for (let c = 0; c < 5; c++) {
                temporaryState[x, y, z] = temporaryState[x, y, z] ^ state[(x - 1) % 5, c, z] ^ state[(x + 1) % 5, c, z + 1];
            }
        }
    }
}

return temporaryState;

}`

I should clarify that “state” is a 3d array, where each item in the innermost array is a 1 or a 0.

When this nested for loop is in my code, the state prints incorrectly, but when i remove it, it works.

Fetch with SQL query works if query contains “LIMIT x”, but not if fetch call contains url + “?limit=x”

I have a web app hosted within Google Cloud, written in JavaScript. I’m using the fetch function to get data from a sql database also hosted within Google Cloud. If the code where that function is called looks like this:

const response = await fetch(‘/v1/replacements’, {etc})

And the code where the query is held looks like this:

const getReplacements = ‘SELECT
etc etc etc LIMIT 50’

Then it works fine. But I need that limit to work as a variable, plus I want to add an offset.

When I change those two lines to

const response = await fetch(‘/v1/replacements?limit=50′, {etc})’

and

const getReplacements = ‘SELECT etc etc etc’ (there’s no limit here this time)

Then I don’t get a response from SQL.

I’ve also tried using

fetch(‘/v1/replacements’ + new URLSearchParams({limit: 50}))

to no avail. Any ideas?

Is there a way I can connect to a MERN app from a different network?

My question is pretty straight forward. I am able to connect to my MERN app inside my local network by adding rules to allow incoming connections to the necesary ports (9901 for my server, 3000 for my client, and 27017 for my database), then deactivating the Firewall on my active internet connection on my computer.
Can I do something similar but that allows connections coming from outside of my local network? Let’s say, through a use of a VPN for example.

I can´t see the react app online with the npm run start [closed]

anybody knows why I can´t see the react app online with the npm run start? the react app

I´m speckthing contributions or suggestions if possible!because I don´t know what I do wrong. I only use the template and everythin works but when I start adding components something happend. whe yo run the npm run start you see the web blanck, but the /demo and /single happend too. I think the problem is in the index.js or layout.js

How exactly we can implement smartbanner.js package to show the smart app banner for android?

I tried many app banner for my app, apple meta tags and android meta tags but nothing worked. iOS meta tags worked fine but the android meta tags are worse and time wasting as they are totally misleading docs. Then i came to know about smartbanner.js npm package.

I need to add meta tags of smartbanner as mentioned in the docs then i need to add 2 smartbanner.js files in the. And all these should be inside <head> tag of the app. So I did the same thing.

See code below for header.js file ->

 <head>
... <sly data-sly-test.disableScripts="${pageProperties.disableScripts}" />
  <title data-sly-test="${!pageModel}">
    ${pageModel.metaTitle}
  </title>
  <meta name="title" content="${pageModel.metaTitle}" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta name="apple-itunes-app" content="app-id=7887, app-argument=https://apps.apple.com/app/app_id">

  <!-- Start SmartBanner configuration -->
<meta name="smartbanner:title" content="Smart Application">
<meta name="smartbanner:author" content="SmartBanner Contributors">
<meta name="smartbanner:price" content="FREE">
<meta name="smartbanner:price-suffix-apple" content=" - On the App Store">
<meta name="smartbanner:price-suffix-google" content=" - In Google Play">
<meta name="smartbanner:icon-apple" content="icon.png">
<meta name="smartbanner:icon-google" content="icon.png">
<meta name="smartbanner:button" content="VIEW">
<meta name="smartbanner:button-url-apple" content="https://apple_app_url">
<meta name="smartbanner:button-url-google" content="https://play.google.com/store/apps/details?id=com.google_app_id">
<meta name="smartbanner:enabled-platforms" content="android,ios">
<meta name="smartbanner:close-label" content="Close">
<!-- End SmartBanner configuration -->

<link rel="stylesheet" href="./smartbannerFiles/smartbanner.min.css">
<script src="./smartbannerFiles/smartbanner.min.js"></script>

  <sly data-sly-test="${disableScripts}">
    <meta name="google-site-verification" content="abckjasnaklsjn" />
  </sly>
  
  <link
    rel="manifest"
    href="/etc.clientlibs/manifest.json"
  /> .....
</head>

I pasted the 2 files smartbanner.min.css and smartbanner.min.js from the npm smartbanner.js code itself.

Not really sure, if i just need to give the path of these 2 files in the app along with the meta tags then what is the need to install this banner package? And If this is not the way to implement (Like pasting these 2 min files) then how should I implement this package?

I just want to show the App Banner for android users, Either use any official meta tags or any npm package, any suggestion would be helpful, please help me sort this out.

NOTE : I Can’t see any banner not even any error from the above code.

D3.js Uncaught TypeError: m.selectAll is not a function

I’m trying to create the following graph, the axes are plotted correctly.

But when I try to draw the line, the following error appears Uncaught TypeError: m.selectAll is not a function.

I’ve already researched a lot, tried several “solutions”, but nothing worked.

function drawPowerProfileChart(xAxis, data) {

    const width = window.innerWidth;

    if (window.innerHeight < 600) {
        var height = window.innerHeight - 150;
    } else if (window.innerHeight >= 600 && window.innerHeight < 767) {
        var height = window.innerHeight - 500;
    } else if (window.innerHeight >= 767 && window.innerHeight < 916) {
        var height = window.innerHeight - 200;
    } else if (window.innerHeight >= 916 && window.innerHeight < 1180) {
        var height = window.innerHeight - 650;
    } else if (window.innerHeight >= 1180 && window.innerHeight < 1440) {
        var height = window.innerHeight - 750;
    } else {
        var height = window.innerHeight;
    }

    const marginRight = 20;
    const marginBottom = 20;
    const marginLeft = 40;

    const svg = d3.select("#power-profile-chart")
        .append("svg")
        .attr("viewBox", [0, 0, width, height])
        .attr("style", "max-width: 100%; height: auto;");

    const yAxisScale = d3.scaleLinear()
        .domain([0, d3.max(data, d => d.value)])
        .range([height - marginBottom, 0]);
    
    const y = d3.axisLeft()
        .scale(yAxisScale);

    const xAxisScale = d3.scaleSymlog()
        .domain(d3.extent(data, d => d.interval))
        .constant(5)
        .range([1, width - marginLeft - marginRight]);
    
    const x = d3.axisBottom()
        .scale(xAxisScale)
        .tickValues(xAxis.map(function(i) { 
            return i.interval;
        }))
        .tickFormat(function(l) {
            var label = xAxis.find(function(i) {
                return i.interval === l; 
            });

            return label ? label.label : l;
        });

    svg.append("g")
        .attr("transform", `translate(${marginLeft},${height - marginBottom})`)
        .call(x);
    
    svg.append("g")
        .attr("transform", `translate(${marginLeft},0)`)
        .call(y);
    
    const line = d3.line()
        .x(d => x(d.interval))
        .y(d => y(d.value));

    svg.append("path")
        .datum(data)
        .attr("fill", "none")
        .attr("stroke", "steelblue")
        .attr("stroke-width", 1.5)
        .attr("d", line);

    return svg.node();
}

Basic, the same code here:

Example

Node.js/Express File Download Returns 0-Byte Plaintext Files

When I trigger a file download from my frontend (utilizing a React app and an async Redux action for the download), the download initiates but the resulting file is always 0 bytes and is of a plaintext format, not matching the original file’s content or MIME type.

Here’s the core part of my download implementation in the Express backend:

const express = require('express');
const fs = require('fs');
const path = require('path');
const app = express();

const UploadFolder = '/path/to/uploads'; // Adjusted to my actual upload folder path

app.get('/download/:filename', async (req, res, next) => {
  const { filename } = req.params;
  const filePath = path.join(UploadFolder, filename);

  if (!fs.existsSync(filePath)) {
    return res.status(404).json({ error: 'File not found' });
  }

  res.setHeader('Content-Type', 'application/octet-stream');
  res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);

  const readStream = fs.createReadStream(filePath);
  readStream.pipe(res);

  readStream.on('error', (error) => {
    console.error(`Error reading file: ${error}`);
    next(error);
  });
});
  • I’ve verified the file paths and ensured the files exist and are accessible by the server.
  • I’ve checked that the MIME type and headers are set correctly before piping the file stream.
  • I’ve tried using res.download(filePath) as an alternative, but the issue persists.
  • I’ve tried to detect the mime type and the file size and set them as content-type and content-length

Why is the “<" in my javascript for loop breaking my code?

I am trying to add an event listener to a series of links on a page which is generated by an xml config file. I can add the listener to a single link with no problem, but when I try to use the for loop to add it to all of them, it breaks the xml package and the page won’t load. I think what’s happening is that it’s interpreting the < in (i=0; i<selBtn.length; i++) as an opening tag, which then breaks the closing < /script> tag, but I’m not sure how to fix it!

Where am I going wrong?

<script>
document.addEventListener("DOMContentLoaded", function() {

    var selBtn = document.getElementsByClassName("SelectItemButton");
    console.log(selBtn);

    for (i = 0; i < selBtn.length; i++) {
        selBtn[i].addEventListener('click', selectItem);
    }

    function selectItem() {
        alert("You selected me!");

    }
});
</script>

Editing to add the error message I get from the xml package:

XmlPackage Exception: Exception=Last Trace Point=[]. No stylesheet was loaded.
System.ArgumentException: Last Trace Point=[]. No stylesheet was loaded. at AspDotNetStorefrontCommon.XmlPackage2.TransformString() at AspDotNetStorefrontCommon.AppLogic.RunXmlPackage(XmlPackage2 p, Parser UseParser, Customer ThisCustomer, Int32 SkinID, Boolean ReplaceTokens, Boolean WriteExceptionMessage)

Css properties with conditional styles and falsy values

I’m looking for the answer to the question how should I use styles with conditional operators.

What code example would be the best? Can we use non css values such as: undefined, null, false, etc.?

margin: isOpen ? '10px' : undefined
margin: isOpen ? '10px' : 'initial'

Is it okay to use it in that way? (so we pass ‘undefined’ and ‘null’ as a css property)

margin: isOpen ?? '10px'

and one more (so we pass every falsie value)

margin: isOpen && '10px'

or maybe this

margin: isOpen ? '10px' : ''

As context we can say we wanna use it in react style porp, or in styled-components

Failed to load resource: the server responded with a status of 404 () index12312.js

I have an error when I deploy on my http:://develop.example.com

When I do the pr to my develop branch to bring new changes to my develop.example.com url when realoding the web page, the entire screen appears blank with the following error

“Failed to load resource: the server responded with a status of 404 ()”

After reloading the page again I am back to how I was before.

I don’t know what the problem itself is.

I have PWA installed within the website.

This is the error –> enter image description here

This is my structure –> enter image description here
This is my HTML –> enter image description here

More info…
I am deploying to AWS S3

The error is a little more detailed, according to this it tells me that the file is not in
Error Image —> enter image description here

Any suggestions?

I need that when I start the page after a deploy it does not leave the screen blank

Mercedes API Has been blocked by CORS policy

I try to get data with Mercedes API, but I have CORS policy problem.
I use Vue js, my website is hosted on firebase.

API Docs : https://developer.mercedes-benz.com/products/vehicle_specification/docs#

async function getVehicleSpecifications() {
  const apiKey = 'MY API KEY'; // Hidden for the screenshoot
  const locale = 'fr_FR';
  const url = `https://api.mercedes-benz.com/vehicle_specifications/v1/vehicles/${vin.value}?locale=${locale}`;

  try {
    const response = await axios.get(url, {
      headers: {
        'x-api-key': apiKey,
        'accept': 'application/json',
      },
    });

    vehicleSpecifications.value = response.data;
    console.log(response.data); 
  } catch (error) {
    console.error('Erreur réseau ou de serveur :', error);
  }
}

screenshot of the errors

How can I insert whole numbers in between elements with decimals in an array?

I am passing an object with 5 arrays to my function. One of the functions is called ‘Indexes’. What this function is doing is filling in the array with zeros in ascending order, all other arrays follow the Indexes array as their index so if Indexes array is [1,3] it will fill it with [1,2,3] and all arrays will have 0 in position 2.

My problem is when Indexes contains .5 (work related, so I have to roll with it), if I have [43, 44.5, 45] I want to get [43, 44, 44.5, 45]. But the way I wrote my code seems to skip with whole numbers completely, and I think I am making it more complicated for myself than it needs to be.

Heres the function


function fillMissingValues(csv) {
    const indexes = csv.Indexes;
    const allReads = csv['All reads'];
    const trimmedByAdapterOrQuality = csv['Trimmed by Adapter or Quality'];
    const trimmedByAdapter = csv['Trimmed by adapter'];
    const trimmedByQuality = csv['Trimmed by quality'];

    const filledIndexes = [];
    const filledAllReads = [];
    const filledTrimmedByAdapterOrQuality = [];
    const filledTrimmedByAdapter = [];
    const filledTrimmedByQuality = [];

    let lastIndex = 0;
    for (let i = 0; i < indexes.length; i++) {
        const index = indexes[i];
        const value = allReads[i];
        const taq = trimmedByAdapterOrQuality[i];
        const ta = trimmedByAdapter[i];
        const tq = trimmedByQuality[i];

        while (lastIndex < index) {
            filledIndexes.push(lastIndex);
            filledAllReads.push(0);
            filledTrimmedByAdapterOrQuality.push(0);
            filledTrimmedByAdapter.push(0);
            filledTrimmedByQuality.push(0);
            lastIndex++;
        }

        filledIndexes.push(index);
        filledAllReads.push(value);
        filledTrimmedByAdapterOrQuality.push(taq);
        filledTrimmedByAdapter.push(ta);
        filledTrimmedByQuality.push(tq);
        lastIndex++;
    }

    // Fill the remaining indexes with zeros
    const maxIndex = Math.max(...indexes);
    while (lastIndex <= maxIndex) {
        filledIndexes.push(lastIndex);
        filledAllReads.push(0);
        filledTrimmedByAdapterOrQuality.push(0);
        filledTrimmedByAdapter.push(0);
        filledTrimmedByQuality.push(0);
        lastIndex++;
    }

    const filledCSV = {
        Indexes: filledIndexes,
        'All reads': filledAllReads,
        'Trimmed by Adapter or Quality': filledTrimmedByAdapterOrQuality,
        'Trimmed by adapter': filledTrimmedByAdapter,
        'Trimmed by quality': filledTrimmedByQuality
    };

    return filledCSV;
}

Example of passing data,

data = {
        Indexes:[ 3, 4, 6.5, 8]
        'All reads': [1, 2, 3, 4],
        'Trimmed by Adapter or Quality': [1, 2, 3, 4],
        'Trimmed by adapter': [1, 2, 3, 4],
        'Trimmed by quality': [1, 2, 3, 4],
}

so output should be

data = {
        Indexes:[0, 1, 2, 3, 4, 5, 6, 6.5, 7, 8]
        'All reads': [0, 0, 0, 1, 2, 0, 0, 3, 0, 4],
        'Trimmed by Adapter or Quality': [0, 0, 0, 1, 2, 0, 0, 3, 0, 4],
        'Trimmed by adapter': [0, 0, 0, 1, 2, 0, 0, 3, 0, 4],
        'Trimmed by quality': [0, 0, 0, 1, 2, 0, 0, 3, 0, 4],
}

Socket Freeze Issue During High Data Volume in Node.js Application

I’m having a problem with a Node.js application. This application is a client that reads data from a TCP connection using net.socket. When there’s a sudden surge in data volume, the socket appears to freeze, preventing further data arrival. After a period of being stuck, the socket unlocks, and the previously withheld data starts arriving, as if it had been temporarily held back and then released.

const connect = require('node:net').connect
const PassThrough = require('node:stream').PassThrough

const TELNET_HOST = process.env.TELNET_HOST
const TELNET_PORT = process.env.TELNET_PORT

const broadcaster = new PassThrough()
const socket = connect(
  {
    host: TELNET_HOST,
    port: TELNET_PORT,
    onread: {
      buffer: Buffer.alloc(32 * 1024),
      callback: (nread, buffer) => socket.emit('data', buffer.subarray(0, nread)),
    },
  },
  () => console.info('Connected')
)

socket.on('data', (data) => broadcaster.write(data))

Can you help me to code the section with same functionality

Here is the website : https://email.uplers.com/portfolio/ which have this section that i want to code in my react app for frontend

here is the screenshot which section I referring :
enter image description here

when i click on left side thumbnail the image show in right side div how to do it ?
its some kind of NPM module or library?

can you please advice me how to code this section.