Fancybox disable preload option does not work?

As I understand it, the “preload” in Fancybox means when I click open slide 2, it will automatically download and load slide 1 and slide 3, such that when I switch to prev or next slide, there will be no loading time. But either set preload to be true or false, I see that when I open one slide, the next slide is still fetched. Not sure if I set something incorrectly

<a data-fancybox="gallery" href="https://sample-videos.com/img/Sample-jpg-image-100kb.jpg" data-type="iframe" data-preload="false">
            <img src="https://sample-videos.com/img/Sample-jpg-image-50kb.jpg">
</a>
<a data-fancybox="gallery" href="https://sample-videos.com/img/Sample-png-image-200kb.png" data-type="iframe" data-preload="false">
            <img src="https://sample-videos.com/img/Sample-png-image-100kb.png">
</a>
<a data-fancybox="gallery" href="https://sample-videos.com/gif/1.gif" data-type="iframe" data-preload="false">
            <img src="https://sample-videos.com/gif/3.gif">
</a>

<script>
        Fancybox.bind("[data-fancybox]", { });
</script>

Cannot create a key using the specified key usages error when generating ECDSA keys using subtle crypto

I’m trying to generate ECDSA keys using subtle crypto without any external libraries (it’s important to me), but getting “Cannot create a key using the specified key usages.” error. Can anyone advise on what’s wrong with the below approach?

async function generateECDSAKeyFromSeed(seed) {
    // Convert the seed to an ArrayBuffer
    const enc = new TextEncoder();
    const seedBuffer = enc.encode(seed);

    // Step 1: Derive key material from seed using PBKDF2
    const baseKey = await crypto.subtle.importKey(
        'raw',
        seedBuffer,
        { name: 'PBKDF2' },
        false,
        ['deriveBits', 'deriveKey']
    );

    const salt = crypto.getRandomValues(new Uint8Array(16)); // Random salt
    const derivedBits = await crypto.subtle.deriveBits(
        {
            name: 'PBKDF2',
            salt: salt,
            iterations: 100000,
            hash: 'SHA-256',
        },
        baseKey,
        256
    );

    // Step 2: Import derived key material as a private key
    const privateKey = await crypto.subtle.importKey(
        'raw',
        derivedBits,
        { name: 'ECDSA', namedCurve: 'P-256' },
        true,
        ['sign']
    );

    // Step 3: Extract public key from private key
    const publicKey = await crypto.subtle.exportKey('jwk', privateKey);

    return {
        privateKey: privateKey,
        publicKey: publicKey
    };
}

// Example usage
generateECDSAKeyFromSeed("your_seed_value").then(keys => {
    console.log("Private Key:", keys.privateKey);
    console.log("Public Key:", keys.publicKey);
}).catch(x => {
    debugger;
    console.error(x);
});

There seems to be a bug in Firefox js engine

I made a code that emulates the behavior of the readline() function in This CodinGame exercise.
The code is the following:

 function* cutie(txt){
    const x=txt.split("n")
    const w=x.reduce((a,b)=>b.length>a?b.length:a,0)
    yield x.length+" "+w
    for(const i of x){yield i}
}

function readline(){
    return XX.next().value
}
XX=cutie(`##########
#S.......#
##.#####.#
##.#.....#
##########`)

For some strange reason that is beyond me, it works in Firefox’s console (when calling separately), and in Node.js v16.20.2, but it still gives undefined in the following code:

function* cutie(txt) {
  const x = txt.split("n")
  const w = x.reduce((a, b) => b.length > a ? b.length : a, 0)
  yield x.length + " " + w
  for (const i of x) {
    yield i
  }
}

function readline() {
  return XX.next().value
}
XX = cutie(`##########
#S.......#
##.#####.#
##.#.....#
##########`)

function setNb(x, y, val) {
  if (grid[y][y] === null) {
    grid[y][x] = val
  } else {
    grid[y][x] = val < grid[y][x] ? val : grid[y][x]
  }
  if (y - 1 > 0 && grid[y - 1][x] === null) setNb(x, y - 1, val + 1)
  if (x - 1 > 0 && grid[y][x - 1] === null) setNb(x - 1, y, val + 1)
  if (y + 1 < grid.length && grid[y + 1][x] === null) setNb(x, y + 1, val + 1)
  if (x + 1 < grid[y].length && grid[y][x + 1] === null) setNb(x + 1, y, val + 1)
}

var inputs = readline().split(' ');
const w = parseInt(inputs[0]);
const h = parseInt(inputs[1]);
let grid = [],
  start
for (let i = 0; i < h; i++) {
  let b = readline()
  grid.push(b.split("").map(a => a == "." ? null : a))
  if (b.indexOf("S") != -1) {
    start = {
      x: b.indexOf("S"),
      y: i
    }
  }
}
setNb(start.x, start.y, 0)
console.log(grid.map(a => a.map(b => isNaN(b) ? b : b.toString(36).toUpperCase()).join("")).join("n"))

The code will not run because I made a mistake in the recursion. But in the Firefox console on an about:blank tab, the code dies before it could reach the recursion.

What could be the issue?

Error displaying [object HTMLParagraphElement] in javascript

I’m new to javascript, I have an error displaying [object HTMLParagraphElement] instead of the chat content in the real-time chat function.

<script>
 // Configure Pusher
 Pusher.logToConsole = true;
 var pusher = new Pusher('...', {
     cluster: '...',
     encrypted: true
 });

 // Replace with actual sender and receiver IDs
 var senderId = 1;
 var receiverId = 2;

 // Subscribe to the private channel for the receiver
 var channel = pusher.subscribe(`private-chat-${receiverId}`);
 channel.bind('new_message', function (data) {
     var messageHistory = document.getElementById('message-history');
     var message = document.createElement('div');
     message.className = `message ${data.senderId === senderId ? 'sent' : 'received'}`;

     // Create and set message content
     var messageContent = document.createElement('p');
     // Ensure data.message is a string before assigning to textContent
     messageContent.textContent = `${String(data.message)} (Sent at ${data.sentAt})`;

     message.appendChild(messageContent);
     messageHistory.appendChild(message);
     messageHistory.scrollTop = messageHistory.scrollHeight; // Scroll to the bottom
 });

 // Load message history on page load
 document.addEventListener('DOMContentLoaded', function () {
     fetch(`/history/${senderId}/${receiverId}`)
         .then(response => response.json())
         .then(messages => {
             var messageHistory = document.getElementById('message-history');
             messages.forEach(message => {
                 var msgDiv = document.createElement('div');
                 msgDiv.className = `message ${message.senderId === senderId ? 'sent' : 'received'}`;

                 // Create and set message content
                 var msgContent = document.createElement('p');
                 // Ensure message.messageContent is a string before assigning to textContent
                 msgContent.textContent = `${String(message.messageContent)} (Sent at ${new Date(message.sentAt).toLocaleString()})`;

                 msgDiv.appendChild(msgContent);
                 messageHistory.appendChild(msgDiv);
             });
             messageHistory.scrollTop = messageHistory.scrollHeight; // Scroll to the bottom
         })
         .catch(error => console.error('Error loading message history:', error));
 });

 // Handle sending messages
 document.getElementById('send-button').addEventListener('click', function () {
     var messageContent = document.getElementById('message-input').value;

     fetch('/send', {
         method: 'POST',
         headers: {
             'Content-Type': 'application/json'
         },
         body: JSON.stringify({
             senderId: senderId,
             receiverId: receiverId,
             messageContent: messageContent
         })
     })
         .then(response => response.json())
         .then(data => {
             console.log(data);

             // Display the sent message in the chat history immediately
             var messageHistory = document.getElementById('message-history');
             var message = document.createElement('div');
             message.className = 'message sent';

             // Create and set message content
             var messageContent = document.createElement('p');
             // Ensure messageContent is a string before assigning to textContent
             messageContent.textContent = `${String(messageContent)} (Sent at ${new Date().toLocaleString()})`;

             message.appendChild(messageContent);
             messageHistory.appendChild(message);
             messageHistory.scrollTop = messageHistory.scrollHeight; // Scroll to the bottom

             // Clear the input field
             document.getElementById('message-input').value = '';
         })
         .catch(error => console.error('Error:', error));
 });
</script>

I tried using innerhtml but it still doesn’t work

How to stop webpack copyplugin from renaming files?

I have a folder called “Static” which includes the below files

enter image description here

I am using the copy-webpack-plugin to copy these files to a dist folder. For some reason the files are being renamed after running webpack. Below is what I see in dist folder:

enter image description here

Below is what I see when I run Webpack

enter image description here

This is problematic for Chrome as it expects to see manifest.json file name when testing Chrome extension.

Webpack.js

module.exports = {
  plugins: [
    new CopyPlugin({
      patterns: [
        {
          from: path.resolve('src/static'),
          to: path.resolve('dist')
        }
      ]
    }),
  ]
};

Why is this happening and how can I prevent renaming? It is strange because for another project I have the same set up and the renaming does not occur.

How can I conditionally render a React component if a sessionStorage variable does not exist in Next.js?

I have an <Authenticated> component that is used to render all of my authenticated routes. I want to prevent rendering the page until I have checked a token stored in sessionStorage.

'use client';

export const Authenticated = ({ children }) => {
  const token = typeof window !== 'undefined' ? sessionStorage.getItem('token') : null;

  if (!token) {
    return <></>;
  }

  return (
    <main>{children}</main>
  );
}

This works but I get this hydration error:

Uncaught Error: Hydration failed because the initial UI does not match what was rendered on the server.

Is there a better way to do this?

Numbers not appearing when I click on their button

I’m trying to make a calculator and I have completed the html and css files so far however, whenever I click on a number button it is not displaying in the display. I am not sure where I went wrong, it most likely is a easy fix that I am just not seeing.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cute Calculator</title>
    <link rel="stylesheet" href="style.css"/>
 </head>
 <body>
    <div id="calculator">
        <input id="display" readonly>
        <div id="keys">
            <button onclick="appendToDisplay('+')" class="op-button">+</button>
            <button onclick="appendToDisplay('7')">7</button>
            <button onclick="appendToDisplay('8')">8</button>
            <button onclick="appendToDisplay('9')">9</button>
            <button onclick="appendToDisplay('-')" class="op-button">-</button>
            <button onclick="appendToDisplay('4')">4</button>
            <button onclick="appendToDisplay('5')">5</button>
            <button onclick="appendToDisplay('6')">6</button>
            <button onclick="appendToDisplay('*')" class="op-button">*</button>
            <button onclick="appendToDisplay('1')">1</button>
            <button onclick="appendToDisplay('2')">2</button>
            <button onclick="appendToDisplay('3')">3</button>
            <button onclick="appendToDisplay('/')" class="op-button">/</button>
            <button onclick="appendToDisplay('0')">0</button>
            <button onclick="appendToDisplay('.')">.</button>
            <button onclick="calculate()">=</button>
            <button onclick="clearDisplay()" class="op-button">C</button>
        </div>
    </div>
    <script src="index.js"></script>
 </body>

</html>

body{
    margin:0;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background: url("./calckitty.jpg");
    background-size: cover;




}

#calculator{
    font-family: Arial, Helvetica, sans-serif;
    background: url("./kitty2.jpg");
    border-radius: 15px;
    max-width:500px;
    overflow:hidden;

}

#display{
    width:100%;
    padding:20px;
    font-size: 5rem;
    text-align: left;
    border:none;
    background: url("./kittytop.jpg");
    opacity: 90%;
    color:white;

}

#keys{
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 5px;
    padding: 20px;
}

button{
    width:100px;
    height:100px;
    border-radius: 50px;
    border: 1.5px solid pink;
    background-color: hsl(26, 93%, 89%);
    color: rgb(128, 118, 118);
    font-size: 2rem;
    font-weight: bold;
    cursor: pointer;

}

button:hover{
    background-color: hsl(332, 60%, 77%);
}

button:active{
    background-color: hsl(332, 60%, 83%);
}

.op-button{
    background-color: hsl(327, 44%, 35%);
}

.op-button:hover{
    background-color: hsl(327, 59%, 45%);
}

.op-button:active{
    background-color: hsl(57, 54%, 58%);
}
const display = document.getElementById("display");

function appendToDisplay(input){
 display.value += input;
 console.log;
 
}

function clearDisplay(){

}

function calculate(){

}

I went through my html file, made sure the .js and .html file were linked, they were and then I went back to make sure my ids were correct and they are.

How do I get the Photopea API to work as described?

According to the documentation for the Photopea API, the “script” parameter of the JSON configuration object “should be executed after loading each file (can be long)”

However, when I test the following simple JSON object within the Playground page, it appears that the script is trying to run BEFORE the files have fully loaded:

{
    "files": [ 
        "https://www.photopea.com/api/img2/pug.png",
        "https://www.photopea.com/api/img2/pug.png"
    ],
    "environment": {
        
    },
    "script" : "app.documents[1].rotateCanvas(90);"
}

The script attempts to rotate the canvas of the 2nd document, which presumably fails because the script executes before the 2nd file has loaded.

How, using the API, can I get the script to run only AFTER all the documents have loaded?

Why does my Node.js server occasionally hang when using async/await with event listeners?

I’m developing a Node.js server that listens to a stream of events from a message queue (like RabbitMQ or Kafka). I’m using async/await to handle asynchronous operations within my event listeners. However, I’ve noticed that occasionally the server seems to hang—no new events are processed, and no errors are thrown.

Here’s a simplified version of my code:

const { EventEmitter } = require('events');
const eventEmitter = new EventEmitter();

eventEmitter.on('data', async (message) => {
  try {
    await handleMessage(message);
  } catch (error) {
    console.error('Error handling message:', error);
  }
});

function startListening() {
  // Simulate receiving messages
  setInterval(() => {
    eventEmitter.emit('data', { content: 'New message' });
  }, 1000);
}

startListening();

handleMessage Function:

async function handleMessage(message) {
  // Simulate asynchronous processing
  await new Promise((resolve) => setTimeout(resolve, 2000));
  console.log('Processed message:', message.content);
}

After running for a while, the server stops processing new messages.
No error messages are logged.
CPU and memory usage remain normal.

Debugging: Added console logs before and after the await in handleMessage to see where it might be getting stuck.

Error Handling: Ensured that all promises have .catch handlers or are within try/catch blocks.

Concurrency Limits: Thought it might be due to overwhelming the event loop, so I considered implementing a concurrency limit but am unsure how to proceed.

  1. Is using async functions directly in event listeners a bad practice in Node.js?
  2. What could cause the event listener to hang without throwing errors?
  3. How can I modify my code to handle asynchronous event processing more reliably?

How to implement RSA encryption on the frontend

So, as the title says, I’m trying to implement a service on the client with SvelteKit that encrypts the user data sent to the server made with Express.

I’m trying to do achieve this with the RSA encryption that I found in several forums.

The thing is, on the backend, it works perfectly fine:

Encryption:

import { constants, publicEncrypt } from 'node:crypto';
import { readFileSync } from 'node:fs';

export const encryptData = (data: string) => {
  const publicKey = readFileSync('public.pem');
  const encryptedData = publicEncrypt(
    {
      key: publicKey,
      padding: constants.RSA_PKCS1_OAEP_PADDING,
      oaepHash: 'sha256',
    },
    Buffer.from(data),
  );
  return encryptedData.toString('base64');
};

Decryption:

import { constants, privateDecrypt } from 'node:crypto';
import { readFileSync } from 'node:fs';

export const decryptData = (data: string) => {
  const privateKey = readFileSync('private.pem');
  const decryptedData = privateDecrypt(
    {
      key: privateKey,
      padding: constants.RSA_PKCS1_OAEP_PADDING,
      oaepHash: 'sha256',
    },
    Buffer.from(data, 'base64'),
  );
  return decryptedData.toString();
};

But in the frontend I can’t find a way to get the server receiving the data and parsing it to a JSON. This is the last code I tried to implement:

Encryption:

import axios from 'axios';

async function retrieveRsaKey() {
  const BACKEND = import.meta.env.VITE_SERVER_URL;
  const PUBLIC_RSA_KEY = await axios.get(BACKEND + '/public_rsa').then((res) => res.data);
  return PUBLIC_RSA_KEY;
}

export async function encryptData (data: {[key:string]: unknown}) {
  const parsedData = JSON.stringify(data)
  const crypto = new Crypto;
  crypto.subtle.encrypt({name: "RSA-OAEP"}, await retrieveRsaKey(), parsedData)
}

Do you know can I achieve this? I’ve been searching for this topic for about two days and couldn’t find anything working with JS or TS only. Some even rely on PHP or Python to make the encryption.

What I have tried?

  • Use the “web crypto api”
  • Search for packages that imitate the functions in “node:crypto”

What am I expeting?

  • A service that receives a JSON with the information of an user that creates an encrypted message for the server with the PUBLIC RSA KEY.

Javascript flask tutorial

I am going through a tutorial, but it is not working and I can’t figure out why.

It is “Python + JavaScript – Full Stack App Tutorial”

https://www.youtube.com/watch?v=PppslXOR7TA

I downloaded the files whole sale, but when I use ‘npm run dev’ command it says

usage: vite [options]

A simple and minimal static site generator.

positional arguments:
{init,new,build,serve}
Options to help create, build and serve your project.

options:
-h, –help show this help message and exit
-v, –version show program’s version number and exit
PS C:Usersjudewdesktopusing python to interact with pdf and excel project!!! kevings program websiteold one for 1.5 hours can’t make workzzdowloadedfrontend>

When I try to go through the whole thing myself, it has a problem with line 70 is ContactList.jsx

{contacts.map((contact) => (

error is
Uncaught TypeError: Cannot read properties of undefined (reading ‘map’)

It looks like contact doesn’t exist, and it is empty because I am just starting the program, but I have no idea what the problem could be.

Getting rasterized text in html canvas

I have main canvas on which I draw another canvas which had a text written on it. When I saw the results, it appears that the text is rasterized and not smooth.

Here is the code I tried :-

Code :-

const mainCanvas = document.querySelector('.main');
const mainCanvasContext = mainCanvas.getContext('2d');

const backgroundCanvas = document.createElement('canvas');
const backgroundCanvasContext = backgroundCanvas.getContext('2d');

const run = async () => {
  backgroundCanvasContext.font = '500 300px MatterSQ';
  ctx.fillStyle = 'white';
  ctx.fillText(text, 1920 / 2, 30);

  mainCanvasContext.drawImage(backgroundCanvas, 0, 0, mainCanvas.width, mainCanvas.height);
};

run();

Here is the HTML and CSS setup:

<canvas class="main"></canvas>
.main {
  width: 800px;
  aspect-ratio: 16 / 9;
  background: blue;
}

Problem: The final text canvas draw on the main canvas has blurry / rasterized text

Here is the Final Result :-
enter image description here

How to add js/css style to svelte-kit project

I have a js effect called color changin in codepen and i dont how implement it into my svelte-kit project like I tried to implementing this directly into app.css and app.html but it didn’t work I dont how to implement it into svelte-kit project and there is my project structure.
enter image description here

implementing that effect into my project properly

Handling delayed API responses with multiple button clicks [closed]

I’m working on an e-commerce product page where users can add items to their cart by clicking an “Add to Cart” button. Here’s the issue I’m facing:

When a user clicks the “Add to Cart” button, an API call is made to update the cart on the server. However, sometimes the server response is delayed due to high traffic. During this delay, if the user clicks the button multiple times, multiple requests are sent, causing the product to be added multiple times.

This leads to two main problems:

  • The same product gets added multiple times.
  • The user doesn’t get immediate feedback, so they keep clicking.

I haven’t yet added any handling to prevent multiple requests or feedback for the user. I’m wondering what the best way is to:

  • Disable the button until the request is completed,
  • Handle the situation in case the user clicks too fast or the server responds slowly.
  • Any suggestions or best practices on how to handle this?

I did same in my previous project but that time worked.

Please advice me remix template [closed]

I am new to remix (not to js and web dev though) and gonna write my first project on it.
My stack is:

  • taiwind (which is see pretty everywhere. GOOD)
  • vite (good)
  • typescript
  • mysql (bad because I haven’t found any template supporting it. BAD)
  • no specific CI/Deploy pipeline (and not gonna to invest dev time now)
  • session-cookie based user auth
  • zero knowledge in client side testing (please advice some test framework for beginner)
  • own hosting with nodejs and pm2 behind nginx.
    I see that there is no template with this stack and either one requires adjustements.
    What would you advice to take for customization to fit my needs