How to send a Blob with other type of data to NodeJS ExpressJS

I searched all the last day an API to send Datas, from Javascript Client Side to the my NodeJS server with express, code below.

app.post('/microphone', express.raw({type: "*/*", limit: '1000000mb' }), function(req, res)
{    
    var buffer = req.body.buffer;

    var nbrVoice = req.body.nbrVoice;
    var codeUser = req.body.codeUser;
    
    var dirUsers = "users/"+codeUser+"/";

        
    fs.appendFileSync(( dirUsers +nbrVoice+ '_microphone.wav'), buffer );

      res.send( "Okay wav file saved );

});

I have a server with expressjs and I want to send a DataView or a Blob with two number

[blob,  codeUser, nbrVoice ]

I tried with xmlhttprequest, a modern version of that call fetch but that not worked and i am blocked with the raw binary data to string to buffer datas on the server.

if someone have an idea I search a code without jquery.

What is the GraphQL standard / best practice for field duplication?

Say in my app I have something like this:

user {
// fields
}

and say I repeat this over 50+ times. sometimes just with a couple of fields like

user {
 id
 name
}

but sometimes with maybe 10/20+. Is the best practice to merely do an analysis of the app and decide (arbitrarily?) if a field appears more than half the number of times then it needs to be pulled into a fragment?

Also say just id and name appear a lot, is that worth pulling into a fragment by itself?

Is it better to pull more stuff into fragments at the expense of requesting fields that are not needed in some of the queries?

WebGL Support – Pyramid Position Points Not Lining Up Properly

below you will see my web gl .js file and .html and initshader.js files are correct so I did not attach. I am needing to create a pyramid that rotates about the x, y, z axis with the click function.

I am fairly sure I know where the issue in the code is and have marked that area. I have tried changing the points multiple different times and still cannot get the pyramid to line up as expected in photo.

expect output

  • .js file:
                "use strict";
                
                var canvas;
                var gl;
                
                var numPositions  = 12;
                
                var positions = [];
                var colors = [];
                
                var xAxis = 0;
                var yAxis = 1;
                var zAxis = 2;
                
                var axis = 0;
                var theta = [0, 0, 0];
                
                var thetaLoc;
                
                window.onload = function init()
                {
                    canvas = document.getElementById("gl-canvas");
                
                    gl = canvas.getContext('webgl2');
                    if (!gl) alert("WebGL 2.0 isn't available");
                
                    colorPyramid();
                
                    gl.viewport(0, 0, canvas.width, canvas.height);
                    gl.clearColor(1.0, 1.0, 1.0, 1.0);
                
                    gl.enable(gl.DEPTH_TEST);
                
                    //
                    //  Load shaders and initialize attribute buffers
                    //
                    var program = initShaders(gl, "vertex-shader", "fragment-shader");
                    gl.useProgram(program);
                
                    var cBuffer = gl.createBuffer();
                    gl.bindBuffer(gl.ARRAY_BUFFER, cBuffer);
                    gl.bufferData(gl.ARRAY_BUFFER, flatten(colors), gl.STATIC_DRAW);
                
                    var colorLoc = gl.getAttribLocation( program, "aColor" );
                    gl.vertexAttribPointer( colorLoc, 4, gl.FLOAT, false, 0, 0 );
                    gl.enableVertexAttribArray( colorLoc );
                
                    var vBuffer = gl.createBuffer();
                    gl.bindBuffer(gl.ARRAY_BUFFER, vBuffer);
                    gl.bufferData(gl.ARRAY_BUFFER, flatten(positions), gl.STATIC_DRAW);
                
                
                    var positionLoc = gl.getAttribLocation(program, "aPosition");
                    gl.vertexAttribPointer(positionLoc, 4, gl.FLOAT, false, 0, 0);
                    gl.enableVertexAttribArray(positionLoc);
                
                    thetaLoc = gl.getUniformLocation(program, "uTheta");
                
                    //event listeners for buttons
                
                    document.getElementById( "xButton" ).onclick = function () {
                        axis = xAxis;
                    };
                    document.getElementById( "yButton" ).onclick = function () {
                        axis = yAxis;
                    };
                    document.getElementById( "zButton" ).onclick = function () {
                        axis = zAxis;
                    };
                
                    render();
                }
                
                function colorPyramid()
                {
                    triple(1, 0, 3); //the issue is with these points
                    triple(2, 3, 0);
                    triple(3, 1, 2);
                    triple(0, 2, 1);
                }
                
                function triple(a, b, c)
                {
                    var vertices = [
                        vec3(-0.5, -0.2722,  0.2886),
                        vec3(0.0,  -0.2772,  -0.5773),
                        vec3(-0.5,  -0.2722,  0.2886),
                        vec3(0.0, 0.5443,  0.0)
                    ];
                
                    var vertexColors = [
                        vec4(0.0, 0.0, 0.0, 1.0),  // black
                        vec4(1.0, 0.0, 0.0, 1.0),  // red
                        vec4(1.0, 0.0, 1.0, 1.0),  // magenta
                        vec4(0.0, 1.0, 1.0, 1.0)  // cyan
                    ];
                
                    // We need to parition the quad into two triangles in order for
                    // WebGL to be able to render it.  In this case, we create two
                    // triangles from the quad indices
                
                    //vertex color assigned by the index of the vertex
                
                    var indices = [a, b, c];
                
                    for ( var i = 0; i < indices.length; ++i ) {
                        positions.push( vertices[indices[i]] );
                        //colors.push( vertexColors[indices[i]] );
                
                        // for solid colored faces use
                        colors.push(vertexColors[a]);
                    }
                }
                
                function render()
                {
                    gl.clear( gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
                
                    theta[axis] += 2.0;
                    gl.uniform3fv(thetaLoc, theta);
                
                    gl.drawArrays(gl.TRIANGLES, 0, numPositions);
                    requestAnimationFrame(render);
                }
                
  • .html file:
<!DOCTYPE html>
<html>

<script id="vertex-shader" type="x-shader/x-vertex">
#version 300 es

in  vec4 aPosition;
in  vec4 aColor;
out vec4 vColor;

uniform vec3 uTheta;

void main()
{
    // Compute the sines and cosines of theta for each of
    //   the three axes in one computation.
    vec3 angles = radians(uTheta);
    vec3 c = cos(angles);
    vec3 s = sin(angles);

    // Remeber: thse matrices are column-major
    mat4 rx = mat4(1.0,  0.0,  0.0, 0.0,
            0.0,  c.x,  s.x, 0.0,
            0.0, -s.x,  c.x, 0.0,
            0.0,  0.0,  0.0, 1.0);

    mat4 ry = mat4(c.y, 0.0, -s.y, 0.0,
            0.0, 1.0,  0.0, 0.0,
            s.y, 0.0,  c.y, 0.0,
            0.0, 0.0,  0.0, 1.0);


    mat4 rz = mat4(c.z, s.z, 0.0, 0.0,
            -s.z,  c.z, 0.0, 0.0,
            0.0,  0.0, 1.0, 0.0,
            0.0,  0.0, 0.0, 1.0);

    vColor = aColor;
    gl_Position = rz * ry * rx * aPosition;
    gl_Position.z = -gl_Position.z;
}
</script>

<script id="fragment-shader" type="x-shader/x-fragment">
#version 300 es

precision mediump float;

in vec4 vColor;
out vec4 fColor;

void
main()
{
    fColor = vColor;
}
</script>

<script type="text/javascript" src="../SmithLarisa Project 4/utility.js"></script>
<script type="text/javascript" src="../SmithLarisa Project 4/initShaders.js"></script>
<script type="text/javascript" src="../SmithLarisa Project 4/MV.js"></script>
<script type="text/javascript" src="../SmithLarisa Project 4/SmithLarisaPyramid.js"></script>

<body>
<canvas id="gl-canvas" width="512" height="512">
Oops ... your browser doesn't support the HTML5 canvas element
</canvas>

<br/>

<button id= "xButton">Rotate X</button>
<button id= "yButton">Rotate Y</button>
<button id= "zButton">Rotate Z</button>

</body>
</html>

I have tried changing the points multiple different times in the bolded area and still cannot get the pyramid to line up as expected in attached photo.

Please support anyway you can 🙂

getComputedStyle and getBoundingClientRect give different width results when the element is scaled

After applying scale on an element, the width of the child elements calculated by getComputedStyle and getBoundingClientRect are different, why does this happen and which value is correct?

Here is a minimal implementation:

https://codepen.io/lai9fox/pen/wvVMyOq

const child = document.getElementById("child");
const getComputedStyleWidth = getComputedStyle(child).width;
const getBoundingClientRectWidth = child.getBoundingClientRect().width;

const span = document.createElement("span");
span.innerText = `
  width for getComputedStyle: ${getComputedStyleWidth}
  width for getBoundingClientRect: ${getBoundingClientRectWidth}
  `;
document.body.appendChild(span);
#parent {
  width: 500px;
  transform: scale(2);
  transform-origin: 0 0;
}

#child {
  background: yellow;
}
<div id="parent">
  <div>
    <div id="child">
      child
    </div>
  </div>
</div>

proj4js converts EPSG 3946 into EPSG 4326, but the points are not located well

I have a .json file of points to put on a Leaflet map and I have used the proj4js to convert them from the EPSG 3946 projection into the WGS84 EPSG 4326 one. All worked, but the points are not located where they should be: they are about 8 degrees latitude more towards south and a little bit more towards east. The same points look fine on QGIS, they place where they should be.

This is the .js script :

var pTransfo;

$.getJSON('transfo.json',function(data){
    
    proj4.defs("EPSG:3946", "+proj=lcc +lat_1=43 +lat_2=49 +lat_0=46.5 +lon_0=6 +x_0=1700000 +y_0=6200000 +datum=RGF93 +units=m +no_defs +towgs84=0,0,0");

    var fromProj = proj4('EPSG:3946');
    var toProj = proj4('EPSG:4326');
    
    function convertCoordinates(coordinates) {
    
    var convertedCoords = proj4(fromProj, toProj, [coordinates[0], coordinates[1]]);
    console.log('Coordonnées originales :', coordinates);
    console.log('Coordonnées converties :', convertedCoords);
    return [convertedCoords[0], convertedCoords[1]];
}

    data.features.forEach(function(feature) {
        if (feature.geometry.type === "Point") {
            feature.geometry.coordinates = convertCoordinates(feature.geometry.coordinates);
        }
});

And I have already added this line in the html : after the jquery and leaflet line.

Why this delay of location ?

Thank you!

How to Query virtual column in Typeorm

I have this entity declaration with the virtual column slugWithUuid. How can I query this kind of column within a query.

@Entity()
export class Course extends DefaultCredential {
  @Column({ type: 'varchar', length: 75 })
  title: string;

  @Column({ type: 'varchar', length: 50 })
  slug: string;

  @Column({ type: 'json', nullable: true })
  additionalInfoJSON: any;

  slugWithUuid: string;
  @AfterLoad()
  setCustomProperty() {
    this.slugWithUuid =
      this.slug + '-' + JSON.parse(this.additionalInfoJSON)?.uuid;
  }

  @BeforeInsert()
  insertShortUUID() {
    const shortUUID = generateUUID(6);
    const additionalInfo = {
      ...this.additionalInfoJSON,
      uuid: shortUUID,
    };
    this.additionalInfoJSON = JSON.stringify(additionalInfo);
  }
}

This is an example of my query:

async findBySlug(slug: string) {
    const entity = await this.repos.findOne({
      where: { slugWithUuid: slug }
    });

    if (!entity) {
      throw new NotFoundException('Entity not found with this slug');
    }
    return entity;
  }

Is there any other way to declare this virtual column to be able to filter it within a query, because this query return me this error for the moment:

[Nest] 637270 – 10/03/2024, 9:37:42 AM ERROR [ExceptionsHandler]
Property “slugWithUuid” was not found in “Course”. Make sure your
query is correct. EntityPropertyNotFoundError: Property “slugWithUuid”
was not found in “Course”. Make sure your query is correct.

How can I Simulate OpenAI being down?

I’m using deno and the package openai to create an OpenAI object as such:

const myOpenAI = new OpenAI();

After this, I use multiple services of openAI, that of course, fail ungracefully when OpenAI is down.
I want to catch failures on the API in order to gracefully do stuff around OpenAI.

The problem:
I’ve managed to produce try/catch statements around my code. The problem is: How can I test them?

Is there an easy way to simulate, OpenAI being down?

Possible solutions: I’ve tried

  • Creating a function that just throws the error: works but diverts the flow of the code, and doesn’t test my function call

  • Producing typos on the openAI call: which seem to instead of throwing errors, produce failures on the build before even running that code.

  • Instead of passing the openAI response, producing undefined or {}: Big no-no, this breaks my typescript :,(

    Anyone has tried another approach that is slick and could be useful?

Accessing iFrame Content using JavaScript

I have a website, abc.com, in which I load an iframe from a publisher, let’s say hello.com. The content from hello.com is loaded in an iframe, I want to extract content of that iframe using JS. Is it possible? Is it possible to at least get the screenshot using JS?

The CORS on hello.com does not allow any other site to access content though. My assumption was as the content is loaded on client in an iframe, can we do something using JS?

X axis not showing on d3 graph

Hello I’m currently creating a line chart that takes in as x values the seconds in my .csv file and takes in as y values the value of the signal that represents a patients electrodermal activity.

I’ve followed the d3 code from this page https://d3-graph-gallery.com/graph/line_basic.html but for some reason the g element representing x-axis does not show even when appended to the svg element

I’m using react with d3 so svg variable is a reference to the svg element i’m rendering here is my code:

useEffect(() => {
        console.log("state updated");
        console.log(sprSheet);

        if(sprSheet.length != 0){
            let max_signal = d3.max(sprSheet, (row) => row['raw_signal']);
            let min_signal = d3.min(sprSheet, (row) => row['raw_signal']);
            let min_sec = sprSheet[0]['time'];
            let max_sec = sprSheet[sprSheet.length - 1]['time'];

            console.log(`max signal: ${max_signal}`);
            console.log(`min_signal: ${min_signal}`);
            console.log(`max_sec: ${max_sec}`);
            console.log(`min_sec: ${min_sec}`);

            // const width = 'clamp(500px, 75vw, 1260px)';
            // const height = '250px';
            const margin = {top: 10, right: 30, bottom: 30, left: 60, }
            const width = 1024 - margin["left"] - margin["right"];
            const height = 512 - margin["top"] - margin["bottom"]; 

            // recall translate takes in x and y coordinates of how much
            // to move the element along the x and y axis respectively
            const svg = d3.select(svgRef.current)
            .attr("width", width + margin.left + margin.right) // still is 768 since we add back the subtracted values from margin top and margin bottom
            .attr("height", height + margin.top + margin.bottom) // still is 486 since we add back the subtracted values from margin top and margin bottom
            // .attr("viewBox", [0, 0, width * 1.5, height * 1.5])
            .append("g")
            .attr("class", "cartesian-plane")
            .attr("transform", `translate(${margin["left"]}, ${margin["top"]})`); // this is the g element which draws the line

            // x here is a callback function
            let x = d3.scaleTime()
            .domain([min_sec, max_sec])
            .range([0, width]);

            // we create a g element which will draw the x-axis
            svg.append('g')
            .attr("class", "x-axis")
            .attr('transform', `translate(0, ${height})`)
            .call(d3.axisBottom);
            
            // y here is also callback function
            let y = d3.scaleTime()
            .domain([0, max_signal])
            .range([height, 0]);

            // we create a g element which will draw the y-axis
            svg.append("g")
            .attr("class", "y-axis")
            .call(d3.axisLeft(y));
      
            // Set the gradient
            svg.append("linearGradient")
            .attr("class", "line-gradient")
            .attr("id", "line-gradient")
            .attr("gradientUnits", "userSpaceOnUse")
            .attr("x1", 0)
            .attr("y1", y(0))
            .attr("x2", 0)
            .attr("y2", y(max_signal))
            .selectAll("stop")
            .data([
                {offset: "0%", color: "#c78324"},
                {offset: "50%", color: "#ab229d"},
                {offset: "100%", color: "#2823ba"}
            ])
            .enter().append("stop")
            .attr("offset", (d) => d["offset"])
            .attr("stop-color", (d) => d["color"]);
      
            // Add the line
            svg.append("path")
            .datum(sprSheet)
            .attr("fill", "none")
            .attr("stroke", "url(#line-gradient)" )
            .attr("stroke-width", 2)
            .attr("d", d3.line()
                .x((d) => x(d['time']))
                .y((d) => y(d['raw_signal']))
            )

        }else{

            console.log('spreadsheet input mounted');
        }

Here’s also a picture of how the react app renders the d3 graph:
enter image description here

How do I solve this Javascript loop? [duplicate]

What will be the output of the following JavaScript code?

let a = 5;
let i;
for (i = 0; i < 3; i++) {
  console.log(a);
}

Stuck on this javascript question for a class. The answer is either 555 or error, but I truly have no idea what the answer is or why. Error because a isn’t anywhere in the for/equation?

Any help or insight is appriciated.

Firestore, can not get all docs in a sub-collection if the docs have subcollection

My firestore has below data

  • /users/<id>/cards/<card-id>
  • /users/<id>/holdings/<card-id>/<date>/<data>

I can get all card ids with /users/<id>/cards/<card-id>, but I can not get the same info from /users/<id>/holdings/<card-id>

const existing_card_ids = new Set();
try {
  const docRef = db.collection("users").doc(userId);
  const collections = await docRef.listCollections();
  if (collections.length == 0) {
    return existing_card_ids;
  }
  for (const collectionRef of collections) {
    if (collectionRef.id == "cards") { // <-- NOTICE this line
      const docs = await collectionRef.get();
      docs.forEach((doc) => {
        existing_card_ids.add(doc.id);
      });
      break;
    }
  }
} catch (error) {
  console.log(error);
}

return existing_card_ids;

check the highlighted line, If I check the collection id is “holdings”, then the same code will not work.

I searched many different ways in SO and also asked Gemini, Chatgpt. Anyone knows why this is failing?

How to implement a header show-hide animation depending on the scroll direction in react?

The header should slide up with some animation and be hidden when scrolling down the page. When scrolling up, the header should slide down and be visible.

When scrolling up the style should be translateY(0) otherwise the DOM element should be translateY(-200px).

Here are some of the elements that I needed for the implementation:

  • The useEffect hook
  • The useRef hook
  • Setting up listeners for the scroll eventwindow.addEventListener(‘scroll’, handleScroll)
  • Removing listeners for the scroll event:window.removeEventListener(‘scroll’, handleScroll)
  • Keeping track of the previous scroll position in a variable

Below is my code, you can also view it here.

App.js

import React, { useEffect, useRef } from "react";
import "./styles.css";
/*import Header from "./components/Header";*/

const Header = () => {
  const navShowHide = useRef(null);

  useEffect(() => {
    const handleScroll = (e) => {
      navShowHide.current;
    };

    window.addEventListener("scroll", handleScroll);

    return () => {
      window.removeEventListener("scroll", handleScroll);
    };
  }, []);

  return (
    <>
      <div
        style={{
          color: "white",
          padding: 20,
          backgroundColor: "green",
        }}
        className="headershow"
        ref={navShowHide}
      >
        <h1>Header</h1>
      </div>
    </>
  );
};

export default function App() {
  return (
    <>
      <Header />
      <div
        className="App"
        style={{
          height: 2000,
        }}
      >
        <h1>Hello CodeSandbox</h1>
        <h2>Start editing to see some magic happen!</h2>
      </div>
    </>
  );
}

styles.css

.headershow {
  transform: translateY(0);
}

.headerhide {
  transform: translateY(-100%);
}

JavaScript repetion [duplicate]

I am building a landing page, and I have a doubt.

Maybe, the question seems silly, but I want to learn how can I do this.

I built a menu, and when the user click at one of the elements of menu, I want that this menu close.

And I made it with the code of the images that I put here. How can I make this code cleaner?

const mobileItem = document.querySelector('.Item')

mobileItem.addEventListener('click', () => {
  navList.classList.remove('show-menu');

});

const mobileItem1 = document.querySelector('.Item1')

mobileItem1.addEventListener('click', () => {
  navList.classList.remove('show-menu');

});
const mobileItem2 = document.querySelector('.Item2')

mobileItem2.addEventListener('click', () => {
  navList.classList.remove('show-menu');

});
const mobileItem3 = document.querySelector('.Item3')

mobileItem3.addEventListener('click', () => {
  navList.classList.remove('show-menu');

});
<div class="container">
  <div class="logo">
    <img src="./images/LogoNewTech.png" alt="">
  </div>
  <div class="menu-toggle" id="mobile-menu">
    <span class="mobile-item"></span>
    <span class="mobile-item"></span>
    <span class="mobile-item"></span>
  </div>

  <nav>
    <ul class="nav-list">
      <li><a href="#sobre" class="Item">Sobre nós</a></li>
      <li><a href="#produtos" class="Item1">Produtos</a></li>
      <li><a href="#servicos" class="Item2">Serviços</a></li>
      <li><a href="#contato" class="Item3">Contato</a></li>
    </ul>
  </nav>
</div>