Problems with Vtex orders

I’m a marketing partner of an ecommerce company, and I’m having problems with the accounting of results on the vtex io platform. Despite having the correct origins in the orderform, the orders are not accounted for correctly and we are having a very large discrepancy in results, because the vtex io platform does not recognize our origin.

We use utms to do this tracking. Has anyone seen this problem and knows how I can solve it?

I’ve checked the utms forms in checkout but it still doesn’t work

Why does using Array.prototype.slice during iteration behave unexpectedly?

Given an array, I want to generate its “prefixes”, meaning for an array of size N, I want one array containing the first element, an array containing the first two, an array containing the first three, and so on until I get a copy of all N items in the array.

const arr = [1,2,3,4,5]

for (const i in arr) console.log(i, arr.slice(0, i))
// 0, Array []
// 1, Array [ 1 ]
// 2, Array [ 1, 2 ]
// 3, Array(3) [ 1, 2, 3 ]
// 4, Array(4) [ 1, 2, 3, 4 ]

The above is slightly wrong, since at i=0 I want [1], and at i=4 I want [1,2,3,4,5]. So I modified it to use i + 1, which results in completely unexpected behavior:

for (const i in arr) console.log(i, arr.slice(0, i+1))
// 0, Array [ 1 ]
// 1, Array(5) [ 1, 2, 3, 4, 5 ]
// 2, Array(5) [ 1, 2, 3, 4, 5 ]
// 3, Array(5) [ 1, 2, 3, 4, 5 ]
// 4, Array(5) [ 1, 2, 3, 4, 5 ]

I observed this in the JS console in Firefox, as well as Edge.

Why does it apparently jump straight to an array of length 5 on the second iteration? I confirmed that manually calling arr.slice(0, 3) returns [1, 2, 3] as expected, so why does calling it inside the for loop change the behavior?

How to draw a scatter plot with curves using javascript

I’m collecting datapoints, [temperatureC, humidity%, datetime].

I want to plot these in a diagram – with temperature on the x-axis and humidity on the y-axis.

I also want to draw these zones as you can see in this image – especially those three made out of curves.

Mapping these to an approximation – probably some kind of inverse exponential curve is one thing – but I’m specifically looking for any good libraries or charting tools for plain javascript or React that could handle this.

I’ll gladly take any tips.

Mold Index

Problem with FFmpeg breaking when streaming the entire screen and switching tabs

I’m working on a screen recording and streaming setup where the user records their entire screen and streams it to Twitch. The setup works fine initially, but when I switch tabs during recording, the stream breaks on the backend, and I get the following FFmpeg errors:

FFmpeg STDERR: [matroska,webm @ 0x7f9dcb904580] EBML header parsing failed
[in#0 @ 0x7f9dcb904380] Error opening input: Invalid data found when processing input
Error opening input file -.
Error opening input files: Invalid data found when processing input

My frontend code captures the screen and microphone and streams it via a WebSocket to the backend, where FFmpeg processes the stream. Below is my relevant frontend code:

const startRecording = async () => {
    try {
        const screenStream = await navigator.mediaDevices.getDisplayMedia({
            preferCurrentTab: true,
            systemAudio: 'include',
            surfaceSwitching: 'include',
            monitorTypeSurfaces: 'include',
            video: {
                displaySurface: 'browser',
                height: 720,
                width: 1280,
                frameRate: { ideal: 24, max: 30 },
            },
        });

        screenStream.getVideoTracks()[0].onended = () => {
            console.log('Screen sharing ended. Stopping the recorder.');
            stopRecording();
        };

        const micStream = await navigator.mediaDevices.getUserMedia({
            audio: true,
        });

        const combinedStream = new MediaStream([
            ...screenStream.getVideoTracks(),
            ...micStream.getAudioTracks(),
        ]);

        const recorder = new MediaRecorder(combinedStream, {
            mimeType: 'video/webm; codecs=vp8,opus',
            videoBitsPerSecond: 3 * 1024 * 1024,
        });

        const timeslice = 1000;

        recorder.ondataavailable = async (event) => {
            if (socket?.current?.connected && event.data.size > 0) {
                console.log('Sending chunk data:', socket.current.id);
                socket?.current.send(event.data);
                recordedChunks.current.push(event.data);
            } else if (!socket?.current?.connected) {
                handleSocketDisconnection();
            }
        };

        mediaRecorder.current = recorder;
        recorder.start(timeslice);
        setIsRecording(true);
    } catch (error) {
        console.log('Error starting screen recording:', error);
        toast.error('Failed to start screen recording: ' + error);
    }
};

const stopRecording = () => {
    if (socket?.current && mediaRecorder) {
        mediaRecorder?.current?.stop();
        socket.current.close();
        setIsRecording(false);
        downloadRecordedVideo();
    }
};

And here’s my backend code with FFmpeg settings for Twitch streaming:

const inputSettings = [
    '-f', 'webm', '-i', '-', '-v', 'error', '-analyzeduration', '1000000', '-probesize', '5000000',
];

const twitchSettings = (twitch) => {
    return [
        '-c:v', 'libx264', '-preset', 'veryfast', '-tune', 'zerolatency',
        '-g', '60', '-b:v', '2500k', '-maxrate', '3000k', '-bufsize', '8000k',
        '-r', '30', '-vf', 'tpad=stop_mode=clone:stop_duration=2',
        '-c:a', 'aac', '-ar', '44100', '-b:a', '96k',
        '-use_wallclock_as_timestamps', '1', '-async', '1',
        '-err_detect', 'ignore_err', '-reconnect', '1',
        '-reconnect_streamed', '1', '-reconnect_delay_max', '5',
        '-y', '-f', 'flv', twitch,
    ];
};

Problem: When switching tabs during screen sharing, it seems like the frame rate drops or the stream gets interrupted, leading to FFmpeg errors like EBML header parsing failed and Invalid data found when processing input. I suspect this happens because the browser deprioritizes resources when the tab is not active, which might lead to corrupt chunks being sent to FFmpeg.

Questions:

  1. Could switching tabs during screen capture be causing the issue by disrupting the frame rate or dropping frames?
  2. Is there a way to ensure FFmpeg doesn’t break due to these interruptions?
  3. Any suggestions on handling the stream more reliably when switching tabs or optimizing the FFmpeg setup for this scenario?

I tried adjusting the bitrate, frame rate, and buffer size but still experienced the same issue. I’m trying to figure out if the issue is related to how browsers handle screen capture when tab switching or something specific with FFmpeg handling the video stream.

Any insights would be greatly appreciated.
Thanks in advance!

HTML to PDF in react application

i have a problem using html2canvas and jsPDF to save HTML as pdf file. I want to save my html as .pdf in my react application.

import { useContext, useEffect, useState, useRef } from "react";
import html2canvas from "html2canvas";
import jsPDF from "jspdf";
export default function Component() {
const pdfRef = useRef();
async function downloadPDF() {
  const element = pdfRef.current;

  console.log(element.innerHTML); // Sprawdź zawartość elementu
  if (!element.innerHTML) {
    console.log("Element is empty");
    return;
  }
    setTimeout(async () => {
  try {
    console.log("Starting PDF generation");
    const canvas = await html2canvas(element);
    console.log("Canvas generated");
    const imgData = canvas.toDataURL('image/png');
    console.log("Image data generated");
    const pdf = new jsPDF();
    pdf.addImage(imgData, 'PNG', 0, 0);
    pdf.save("download.pdf");
    console.log("PDF generation completed");
  } catch (error) {
    console.log("Error during PDF generation:", error);
  }
}, 1000);};
return (
<>
<div ref={pdfRef}><h1>dupsko</h1></div>
<button onClick={downloadPDF}>generate pdf</button></>
}

Last log is “image data generated” and error:
Error during PDF generation: Error: Incomplete or corrupt PNG file
at new a (png.js:205:1)
at globalThis.webpackHotUpdatemyapp../node_modules/jspdf/dist/jspdf.es.min.js.t.processPNG (png_support.js:310:1)
at Object.P (addimage.js:368:1)
at globalThis.webpackHotUpdatemyapp../node_modules/jspdf/dist/jspdf.es.min.js.e.addImage (addimage.js:853:1)
at main.bde0929a13abc8746106.hot-update.js:131:13

I was trying with html2pdf.js -> but as result i got empty pdf’s. What im doing wrong or waht should I check?

CORS error while fetching favicons from external API

I have one frontend only project in which I am using third party api from duckduckgo to fetch favicon for given website URL. Now whenever we try to fetch favicon for fake/non-existing hostname it return 404 error with default fallback icon. now I am unable to catch exact point when it is returning 404 error. In below code catch block never gets executed because API is always returning the fallback favicon.

export const getFaviconLink = (bookmarkLink: string) => {
    try {
        const linkHost = new URL(bookmarkLink).hostname;
        return `https://icons.duckduckgo.com/ip3/${linkHost}.ico`;
    } catch {
        return "https://placehold.co/24/202124/FFF?text=>";
    }
};

Above utility is being used in my code like this

<img src={getFaviconLink(link)} className={styles.favicon} />

I also tried using the fetch with Promise (code below) and tried to subscribe to external API from frontend and it is giving me CORS policy error which is expected from the third party API.

Any solutions for this? or do I have to create a could function for this?

const fetchFavicon = async () => {
  try {
    const linkHost = new URL(link).hostname;
    const faviconUrl = `https://api.faviconkit.com/${linkHost}/64`;

    const response = await fetch(faviconUrl);

    if (response.ok) {
      setFaviconUrl(faviconUrl);
    } else {
      setFaviconUrl('https://placehold.co/24/202124/FFF?text=>');
    }
  } catch (error) {
    console.error('Network error fetching favicon:', error);
    setFaviconUrl('https://placehold.co/24/202124/FFF?text=>');
  }
};

In html canvas how to convert black and white mask to black and transparent mask?

Is it possible in canvas to convert black/white mask to black/transparent mask?
I searched everywhere and the only way is to use pixel manipulation which is too slow.

Basically I want this transformation:

var ac = a.getContext('2d');
var g = ac.createLinearGradient(25, 0, 75, 0);
g.addColorStop(0, 'black');
g.addColorStop(1, 'white');
ac.fillStyle = 'white';
ac.fillRect(0, 0, 100, 100);
ac.fillStyle = g;
ac.fillRect(25, 25, 50, 50);

var bc = b.getContext('2d');
var g = bc.createLinearGradient(25, 0, 75, 0);
g.addColorStop(0, 'black');
g.addColorStop(1, '#00000000');
bc.fillStyle = g;
bc.fillRect(25, 25, 50, 50);
body {
  background-color: pink;
}

canvas {
  outline: 1px solid cyan;
}
Convert this:<canvas id="a" width="100" height="100"></canvas>
to this:<canvas id="b" width="100" height="100"></canvas>

The closest I got is using multiply:

var a = document.getElementById('a'),
    m = document.getElementById('m'),
    c = document.getElementById('c');

// green image
a.context = a.getContext('2d');
a.context.fillStyle = 'green';
a.context.fillRect(0, 0, 100, 100);

// black and white mask
m.context = m.getContext('2d');
m.context.fillStyle = 'white';
m.context.fillRect(0, 0, 100, 100);

var g = m.context.createLinearGradient(25, 0, 75, 0);
g.addColorStop(0, 'black');
g.addColorStop(1, 'white');

m.context.fillStyle = g;
m.context.fillRect(25, 25, 50, 50);

// result
c.context = c.getContext('2d');
c.context.drawImage(a, 0, 0);
c.context.globalCompositeOperation = "multiply";
c.context.drawImage(m, 0, 0);
body {
  background-color: cyan;
}
Green image:
<canvas id="a" width=100 height=100 style="outline: 1px solid cyan;"></canvas>
Black and white mask:
<canvas id="m" width=100 height=100 style="outline: 1px solid cyan;"></canvas>
Result:
<canvas id="c" width=100 height=100 style="outline: 1px solid cyan;"></canvas>

But the problem with this is that there is no intermediary step where I have access to black/transparent canvas.

Drop down menu through url session create

Through paypal it is possible to create buttons with a dropdown selection.

Example : https://www.paypal.com/ncp/payment/[token]

dropdown example

I am having hard time implementing the same through a session url, as I’d need to also include custom Ids for the whole process, and backend logic.

When creating a normal monthly sub I use:

const response = await fetch('https://api-m.paypal.com/v1/billing/subscriptions', {
        method: 'POST',
        headers: {
            Authorization: `Bearer ${accessToken}`,
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            plan_id: 'P-08L0057...', 
            custom_id: `${customId}`, 
            application_context: {
                brand_name: 'Sub',
                locale: 'en-US',
                shipping_preference: 'NO_SHIPPING',
                user_action: 'SUBSCRIBE_NOW',
            },
        }),
    });

    const data = await response.json();
    return data;

Is there a similar way, but to display a dropdown with selectable options instead?
Or do I have to make the dropdown myself and then creating an order based on that?

  const response = await fetch('https://api-m.paypal.com/v2/checkout/orders', {
        method: 'POST',
        headers: {
            Authorization: `Bearer ${accessToken}`,
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            intent: 'CAPTURE',
            purchase_units: [
                {
                    amount: {
                        currency_code: 'EUR',
                        value: '6.75',
                        breakdown: {
                            item_total: { 
                                currency_code: 'EUR', 
                                value: '6.75'
                            }
                        }
                    },
...

The problem with this approach is that it stacks up all the options I’m trying to give.

Blurred or virtual background in webcam feed

I have a page that currently uses a React <Webcam /> component for a webcam feed. However, this component does not have the option to blur the background or use a virtual background.

I am trying to use MediaPipe’s image segmentation API to do this now. However, the SelfieSegmentation was deprecated in 2023, and I am unable to find updated starter code using their new API. Below was the code I was going to use with SelfieSegmentation. How can I implement a virtual background or blurred background using the current MediaPipe API (or a similar API)?

import React, { useRef, useEffect } from 'react';
import Webcam from 'react-webcam';
import * as selfieSegmentation from '@mediapipe/selfie_segmentation';

function WebcamBackground() {
  const webcamRef = useRef(null);
  const canvasRef = useRef(null);

  useEffect(() => {
    const webcam = webcamRef.current;
    const canvas = canvasRef.current;

    if (webcam && canvas) {
      const ctx = canvas.getContext('2d');

      const segmenter = new selfieSegmentation.SelfieSegmentation({
        modelSelection: 1, // Select the model (0 for general, 1 for landscape)
      });

      const processVideo = async () => {
        const image = await webcam.getScreenshot();

        const segmentation = await segmenter.send({ image });

        canvas.width = webcam.video.videoWidth;
        canvas.height = webcam.video.videoHeight;

        ctx.drawImage(webcam.video, 0, 0);

        const mask = segmentation.segmentationMask;

        ctx.globalCompositeOperation = 'destination-out';
        ctx.putImageData(mask, 0, 0);

        ctx.globalCompositeOperation = 'destination-over';
        ctx.fillStyle = 'green'; // Replace with your desired background color or image
        ctx.fillRect(0, 0, canvas.width, canvas.height);
      };

      const interval = setInterval(processVideo, 100);

      return () => {
        clearInterval(interval);
        segmenter.close();
      };
    }
  }, []);

  return (
    <div>
      <Webcam ref={webcamRef} />
      <canvas ref={canvasRef} />
    </div>
  );
}

export default WebcamBackground;

How to calculate offset on collision between two rectangles based on their relative positions?

I am working on a collision detection system where a moving rectangle (movingRect) collides with a stationary rectangle (steadyRect). Upon collision, I want to calculate an offset that should be applied to the steady rectangle to resolve the collision. The goal is to push the steady rectangle by the minimal amount needed to separate it from the moving rectangle, while keeping the direction of the offset consistent with their relative positions.

Here’s the function I’m currently using. COLLISION_THRESHOLD is the maximum distance between elements that will not trigger the collision. If the element moves closer, the collision is registered.

function getCollisionOffset(movingRect: DOMRect, steadyRect: DOMRect) {        
        const movingCenter = {
            x: movingRect.left + movingRect.width / 2,
            y: movingRect.top + movingRect.height / 2
        };
        const steadyCenter = {
            x: steadyRect.left + steadyRect.width / 2,
            y: steadyRect.top + steadyRect.height / 2
        };
        const vector = {
            x: steadyCenter.x - movingCenter.x,
            y: steadyCenter.y - movingCenter.y 
        };

        const b1 = Math.abs(vector.x);
        const b2 = (movingRect.width / 2) + (steadyRect.width / 2) + COLLISION_THRESHOLD;
        const c1 = Math.abs(vector.y);
        const c2 = (movingRect.height / 2) + (steadyRect.height / 2) + COLLISION_THRESHOLD
        
        return { 
            x: (Math.abs(vector.x) / b2 * b1) * Math.sign(vector.x),
            y: (Math.abs(vector.y) / c2 * c1) * Math.sign(vector.y) 
        }; 

    }

It offsets the element in the right direction, but the offset is always too big.

How to run a k6 script with multiple payloads using fs module?

I’m trying to run a k6 script that uses multiple payloads stored in JSON files. I want to read these files using the fs module and send them as part of my HTTP requests. However, it seems that the fs module is not supported in k6.

I understand that k6 does not support the fs module. How can I achieve the same functionality in k6? Is there an alternative way to load multiple payloads from JSON files in k6?

Error: can’t access property “pipelineSteps” this.requestMonitor is undefined

Tengo un problema con este mensaje molesto que me aparece en la consola del navegador cada que doy click al viewport,

no tengo he instalado nada en mi aplicación y sale el mensaje, también inicie otro proyecto desde cero y sigue saliendo el mimos problema.
elimine y reinstale el node y no se soluciono, no se a que se debe el mensaje.
el mensaje completo es.

Error: can't access property "pipelineSteps", this.requestMonitor is undefined

tampoco me da la ubicación de donde proviene ese mensaje.

módulos globales

version modulos del proyecto

  • angular 18.2.0
  • typescript ~5.5.2

Angular routing not working inside remote application in MFE

I am using Angular MFE to launch remote application from shell . When I click on menu from shell application , I am trying to load the remote app route.
First time it is launching successfully whatever remote route I give in shell application. But once remote application loaded , when I click on any button to navigate between remote application modules, it is changing only the URL in the browser but component not rendering.

Note: If I launch remote app separately it is working fine

Please anyone suggest how to handle remote app routing inside shell application.

Map function not returning the expected column (3rd) from array

I’m having an issue retrieving email addresses from the 3rd col in an array (obtained from a Gsheet) using filter and map functions. The call is printing an empty array in the log. Can someone please explain what I’m doing wrong?

Here is the function:

/**
 * Retrieves email addresses from a sheet based on selected names from a form.
 *
 * @param {object} e - Form submit event object.
 * @return {string} - A comma-separated string of email addresses.
 */
function getEmailAddresses(e) {
  // Get the responses from the form.
  const responses = e.response.getItemResponses();

  // Extract the selected names from the checkboxes.
  const eList = responses.find(item => item.getItem().getTitle() === 'E List').getResponse();

  // Get the spreadsheet and sheet.
  const ss = SpreadsheetApp.openById("SHEET_ID");
  const shet = ss.getSheetByName('ECI');

  const data = shet.getRange(2, 1, shet.getLastRow()-1, 3).getValues();

  // Logger.log(data);

  // Filter the data based on selected names and extract email addresses.
  // Assuming first name is in column 1 and last name in column 2
  // Assuming email is in column 3
  const emailAddresses = data.filter(row => eList.includes(`${row[0]} ${row[1]}`)).map(row => row[2]);
  Logger.log(emailAddresses);

  // Return the email addresses as a comma-separated string.
  return emailAddresses.join(',');
}