Why does my MetaMask-connected dApp use the wrong account for transactions?

I’m building a dApp using MetaMask and ethers.js v6, but my connectToContract function consistently retrieves the wrong active signer address. MetaMask shows the correct account (0x629F260166655cFD9471F55c9BD97B59ea329F97), but getSigner().getAddress() returns a different address (0x494B66970dE582967BD39BfBC03E049849b59B15). I’ve ensured I’m calling eth_requestAccounts before connecting. How can I ensure my dApp uses the correct MetaMask account?

Parsing and decoding socket stream to create HTML video&audio

I have a socket stream constantly sending me partial Binary data as image below,
enter image description here

When I am console.log() this data it appears as something as base64 as sample below,

AAAAZG1vb2YAAAAQbWZoZAAAAAAAfPOgAAAATHRyYWYAAAAcdGZoZAAAADgAAAACAAAAFQAAAPICAAAAAAAAFHRmZHQBAAAAAAABk8M0zYoAAAAUdHJ1bgAAAAEAAAABAAAAbAAAAPptZGF0ISmEVZ6ND2MRAANN1GiIIklXQDem76zqqo2EiHkWiR+uXJysLrZje6a1GXMBmUDur7+YXmqXN+YS8gJoa4AbTGj7+mhrEF6/ukUgOSiw8WVJO13cmCkXn5T1K6Qqycqf44mCxIyZ5JS5XPtcgkgC8NOaFAl8iZMMWOC8wkqCjgYISASB4o4YXRiX3gnZriKVLNARKgjppNYYWXUeqkr+F3douFTAb5EQmOeaCjkEGRpIN76X3cM8rqVrBoLNRJS8IdgNTtQ4ZOF+bJLVEDJAToO+/spvj9q4LIqEnLAegZzxJtvbgxghs9Kz/n4AAAAAAocAAABkbW9vZgAAABBtZmhkAAAAAAB886IAAABMdHJhZgAAABx0ZmhkAAAAOAAAAAEAAAAoAAAEUgEBAAAAAAAUdGZkdAEAAAAAAAGTwzTNoAAAABR0cnVuAAAAAQAAAAEAAABsAAAEWm1kYXQAAABIQZtmCMf/Im1rWeR69T8zkFAmfAfoK8NKFi88JYLf32iLNVjzErZ/jjpHs3mHQ+sQ/ipPrzUWwp1LnhIG2lxoYcZ7SxPjTeSAAAABEUEBsm2YIQf/wsIlmx/ckvbQeYSAoxgV0yy9OJub+vzs7P8rfaX8r/qwRhUpt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w5uIRbi8TgfPLtK2kslgjQQno22YV8mLQUeLJv1iTSINAmMz6t6L1Uh0WVgy+qncooflaGq2U1eIAK2vttOPlha2uuQrqKkBsOl8RJ4flLS6tEUqzEC2ePJfHmIAP4vp8TxSxjsAAAAvQQAlKbZglf8AKXFDs2tqEIh0VAKRnoKFzIy+i66Mc/tlCT9Om9glbz5BUacpJegAAAAZQQAtmbZglf8AAjVa7iVvO/r/qGsYP7ZfBgAAACBlZ3djAAABk8M0zaAABikyhkOHIAAAAZPDNM5S

When I parse this data with atob() it returns a chunk string always starts with dmoof mfhd prefix which I believe it’s something about MP4 encoding.
enter image description here

What I also know about this data has vc: h264 ac: aac encoding and avc1.42E01E, mp4a.40.2 codecs in order for me to decode it.

I’ve tried multiple methods including hls.js, jmuxer (https://github.com/samirkumardas/jmuxer) MediaSource() but couldn’t be successful to create video&audio stream in my HTML page.

This code below is the most closest try I got,

<video id="video" controls autoplay></video>
<script>
    // Convert base64 string to ArrayBuffer
    function base64ToArrayBuffer(base64) {
      const binaryString = atob(base64);
      const bytes = new Uint8Array(binaryString.length);
      for (let i = 0; i < binaryString.length; i++) {
        bytes[i] = binaryString.charCodeAt(i);
      }
      return bytes.buffer;
    }

    class VideoStreamHandler {
      constructor() {
        this.mediaSource = null;
        this.sourceBuffer = null;
        this.videoElement = document.getElementById('video');
        this.queue = [];
        this.isInitialized = false;

        // Bind methods to maintain correct context
        this.onSourceOpen = this.onSourceOpen.bind(this);
        this.processQueue = this.processQueue.bind(this);
      }

      init() {
        this.mediaSource = new MediaSource();
        this.videoElement.src = URL.createObjectURL(this.mediaSource);
        this.mediaSource.addEventListener('sourceopen', this.onSourceOpen, false);
      }

      onSourceOpen() {
        try {
          // Use a more generic codec string
          this.sourceBuffer = this.mediaSource.addSourceBuffer('video/mp4; codecs="avc1.42E01E, mp4a.40.2"');
          
          // Add event listeners to handle buffer updates
          this.sourceBuffer.addEventListener('updateend', this.processQueue);
          
          this.isInitialized = true;
          this.processQueue();
        } catch (e) {
          console.error('Error creating SourceBuffer:', e);
        }
      }

      processQueue() {
        if (this.queue.length > 0 && !this.sourceBuffer.updating) {
          const arrayBuffer = this.queue.shift();
          try {
            this.sourceBuffer.appendBuffer(arrayBuffer);
          } catch (error) {
            console.error('Error appending buffer:', error);
          }
        }
      }

      handleVideoStream(base64Data) {
        const arrayBuffer = base64ToArrayBuffer(base64Data);

        if (!this.isInitialized) {
          this.init();
        }

        // Always queue the buffer
        this.queue.push(arrayBuffer);

        // Try to process the queue
        if (!this.sourceBuffer.updating) {
          this.processQueue();
        }
      }
    }

    // Create a global instance of the handler
    const videoStreamHandler = new VideoStreamHandler();

    // Listen for video stream messages
    window.addEventListener('message', (msg) => {
      if (msg.data.action === 'VIDEO_STREAM') {
        var b64data = msg.data.data;
        videoStreamHandler.handleVideoStream(b64data);
      }
    });
  </script>

It updates the src attribute of the video tag with a blob url as,

<video id="video" controls="" autoplay="" src="blob:http://localhost/603a5c88-9aed-4f18-800f-885805fc1d5b"></video>

But it returns the error of

Error appending buffer: InvalidStateError: Failed to execute 'appendBuffer' on 'SourceBuffer': This SourceBuffer has been removed from the parent media source.

for the part of the code,

this.sourceBuffer.appendBuffer(arrayBuffer);

as image below,
enter image description here

I am not really experienced of http live streaming side of web development, can’t wait to hear your suggestions to try to achieve creating video&audio from the data. Thanks.

Also implemented the solution of https://stackoverflow.com/questions/24102075/mediasource-error-this-sourcebuffer-has-been-removed-from-the-parent-media-sour
as below,

<video id="video" controls autoplay></video>

  <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
  <script>
    // Convert base64 string to ArrayBuffer
    function base64ToArrayBuffer(base64) {
      const binaryString = atob(base64);
      const bytes = new Uint8Array(binaryString.length);
      for (let i = 0; i < binaryString.length; i++) {
        bytes[i] = binaryString.charCodeAt(i);
      }
      return bytes.buffer;
    }

    var mediaSource = new MediaSource();
    var buffer;
    var queue = [];

    var video = $('#video')[0];
    video.src = window.URL.createObjectURL(mediaSource);

    mediaSource.addEventListener('sourceopen', function(e) {
      video.play();

      buffer = mediaSource.addSourceBuffer('video/mp4; codecs="avc1.42E01E, mp4a.40.2"');

      buffer.addEventListener('updatestart', function(e) { console.log('updatestart: ' + mediaSource.readyState); });
      buffer.addEventListener('update', function(e) { console.log('update: ' + mediaSource.readyState); });
      buffer.addEventListener('updateend', function(e) { console.log('updateend: ' + mediaSource.readyState); });
      buffer.addEventListener('error', function(e) { console.log('error: ' + mediaSource.readyState); });
      buffer.addEventListener('abort', function(e) { console.log('abort: ' + mediaSource.readyState); });

      buffer.addEventListener('update', function() { // Note: Have tried 'updateend'
        if (queue.length > 0 && !buffer.updating) {
          buffer.appendBuffer(queue.shift());
        }
      });
    }, false);

    mediaSource.addEventListener('sourceopen', function(e) { console.log('sourceopen: ' + mediaSource.readyState); });
    mediaSource.addEventListener('sourceended', function(e) { console.log('sourceended: ' + mediaSource.readyState); });
    mediaSource.addEventListener('sourceclose', function(e) { console.log('sourceclose: ' + mediaSource.readyState); });
    mediaSource.addEventListener('error', function(e) { console.log('error: ' + mediaSource.readyState); });

    // Listen for video stream messages
    window.addEventListener('message', (msg) => {
      if (msg.data.action === 'VIDEO_STREAM') {
        var b64data = base64ToArrayBuffer(msg.data.data);
        if (buffer.updating || queue.length > 0) {
          queue.push(b64data);
        } else {
          buffer.appendBuffer(b64data);
        }
      }
    });
  </script>

The same issue still persist,
enter image description here

So please re-open my question, I am also seeking for other resolutions other than MediaSource() if possible..

Parsing and decoding socket stream to create HTML video&audio – HLS

I have a socket stream constantly sending me partial Binary data as image below,
enter image description here

When I am console.log() this data it appears as something as base64 as sample below,

AAAAZG1vb2YAAAAQbWZoZAAAAAAAfPOgAAAATHRyYWYAAAAcdGZoZAAAADgAAAACAAAAFQAAAPICAAAAAAAAFHRmZHQBAAAAAAABk8M0zYoAAAAUdHJ1bgAAAAEAAAABAAAAbAAAAPptZGF0ISmEVZ6ND2MRAANN1GiIIklXQDem76zqqo2EiHkWiR+uXJysLrZje6a1GXMBmUDur7+YXmqXN+YS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Jk8WKuJN9q/P3rhi/VB9AucFHt54Ib8cfS1GuopjDJGP5T0RmwvtWUBP3tEZwG0IGZ7nt5BC8LTsPqPzZD/MgybWAdeu65lOS3AAAAD3QQBX5tmCV/8BAjuEzqGAgRTDCDEJkhNuKUWg4YqWV3cDLk8wzIABpBP91qOptVP9MxsSHfSp2+Zo9PG9f7mAjSLRK39s8H9wDGKnDa8rbCaWzMaCpWbpAota7e+AuBmgwR0fYs0E9E3yrpX7F6vAm5+8+NarmqxCwsDjukTFC8md41BMz1reOYWPizpp7aRVA8W2QsJXdnaxTxmptg+IMm6Tw1nqu3nIVTHOQjfvRsmABHaEqPBvmR/FuyyaKPLj/XWYtAhr129J1Qm9x02xs1hHLI6kalUooR1lssVaFBRT6I/Qf7MOfJi8u9D/zTbRdKWC7RBqCAAAAMBBAHmm2YJX/wBwYiJBlNATOV1c5lGm8ZdHs0GFScWsHt9sgK/lIaAV9P7/hN/lN4OOZiPWVWUoF5dWtoesWohef3gj/dWZHd9Ilp2wRemXqzZlwzNnYypV+74zw5uIRbi8TgfPLtK2kslgjQQno22YV8mLQUeLJv1iTSINAmMz6t6L1Uh0WVgy+qncooflaGq2U1eIAK2vttOPlha2uuQrqKkBsOl8RJ4flLS6tEUqzEC2ePJfHmIAP4vp8TxSxjsAAAAvQQAlKbZglf8AKXFDs2tqEIh0VAKRnoKFzIy+i66Mc/tlCT9Om9glbz5BUacpJegAAAAZQQAtmbZglf8AAjVa7iVvO/r/qGsYP7ZfBgAAACBlZ3djAAABk8M0zaAABikyhkOHIAAAAZPDNM5S

When I parse this data with atob() it returns a chunk string always starts with dmoof mfhd prefix which I believe it’s something about MP4 encoding.
enter image description here

What I also know about this data has vc: h264 ac: aac encoding and avc1.42E01E, mp4a.40.2 codecs in order for me to decode it.

I’ve tried multiple methods including hls.js, jmuxer (https://github.com/samirkumardas/jmuxer) MediaSource() but couldn’t be successful to create video&audio in my HTML page.

This code below is the most closest try I got,

<video id="video" controls autoplay></video>
<script>
    // Convert base64 string to ArrayBuffer
    function base64ToArrayBuffer(base64) {
      const binaryString = atob(base64);
      const bytes = new Uint8Array(binaryString.length);
      for (let i = 0; i < binaryString.length; i++) {
        bytes[i] = binaryString.charCodeAt(i);
      }
      return bytes.buffer;
    }

    class VideoStreamHandler {
      constructor() {
        this.mediaSource = null;
        this.sourceBuffer = null;
        this.videoElement = document.getElementById('video');
        this.queue = [];
        this.isInitialized = false;

        // Bind methods to maintain correct context
        this.onSourceOpen = this.onSourceOpen.bind(this);
        this.processQueue = this.processQueue.bind(this);
      }

      init() {
        this.mediaSource = new MediaSource();
        this.videoElement.src = URL.createObjectURL(this.mediaSource);
        this.mediaSource.addEventListener('sourceopen', this.onSourceOpen, false);
      }

      onSourceOpen() {
        try {
          // Use a more generic codec string
          this.sourceBuffer = this.mediaSource.addSourceBuffer('video/mp4; codecs="avc1.42E01E, mp4a.40.2"');
          
          // Add event listeners to handle buffer updates
          this.sourceBuffer.addEventListener('updateend', this.processQueue);
          
          this.isInitialized = true;
          this.processQueue();
        } catch (e) {
          console.error('Error creating SourceBuffer:', e);
        }
      }

      processQueue() {
        if (this.queue.length > 0 && !this.sourceBuffer.updating) {
          const arrayBuffer = this.queue.shift();
          try {
            this.sourceBuffer.appendBuffer(arrayBuffer);
          } catch (error) {
            console.error('Error appending buffer:', error);
          }
        }
      }

      handleVideoStream(base64Data) {
        const arrayBuffer = base64ToArrayBuffer(base64Data);

        if (!this.isInitialized) {
          this.init();
        }

        // Always queue the buffer
        this.queue.push(arrayBuffer);

        // Try to process the queue
        if (!this.sourceBuffer.updating) {
          this.processQueue();
        }
      }
    }

    // Create a global instance of the handler
    const videoStreamHandler = new VideoStreamHandler();

    // Listen for video stream messages
    window.addEventListener('message', (msg) => {
      if (msg.data.action === 'VIDEO_STREAM') {
        var b64data = msg.data.data;
        videoStreamHandler.handleVideoStream(b64data);
      }
    });
  </script>

It updates the src attribute of the video tag with a blob url as,

<video id="video" controls="" autoplay="" src="blob:http://localhost/603a5c88-9aed-4f18-800f-885805fc1d5b"></video>

But it returns the error of

Error appending buffer: InvalidStateError: Failed to execute 'appendBuffer' on 'SourceBuffer': This SourceBuffer has been removed from the parent media source.

for the part of the code,

this.sourceBuffer.appendBuffer(arrayBuffer);

as image below,
enter image description here

I am not really experienced of http live streaming side of web development, can’t wait to hear your suggestions to try to achieve creating video&audio from the data. Thanks.

Can’t change React-tilt default options doesnt work

i’m designing a blog, and i want to use react-tilt for a premium and incredible experience, well, everything works, tilt works, effects works, but i want to change default options, like max tilt rotation

what i tried?

In the default doumentation says that i need to set that defaultOptions, As you can see, I put it in the code and still nothing changes, vary or change any value of the defaultOptions, and nothing

well there you have my code:

import React from 'react'
import { deleteBlogRequest } from '../../api/blosg.api'
import { useBlogs } from './BlogContext'
import { Link, useNavigate } from 'react-router-dom'
import { Tilt } from 'react-tilt'

const defaultOptions = {
    reverse:        false,  // reverse the tilt direction
    max:            1,     // max tilt rotation (degrees)
    perspective:    2000,   // Transform perspective, the lower the more extreme the tilt gets.
    scale:          1.1,    // 2 = 200%, 1.5 = 150%, etc..
    speed:          1000,   // Speed of the enter/exit transition
    transition:     false,   // Set a transition on enter/exit.
    axis:           null,   // What axis should be disabled. Can be X or Y.
    reset:          true,    // If the tilt effect has to be reset on exit.
    easing:         "cubic-bezier(.03,.98,.52,.99)",    // Easing on enter/exit.
}

function Blogcard({ e }) {

  const {handleDelete} = useBlogs()
  const colors = ["#018aff", "#ff7c01", "#01ff56"]
  var rand = colors[Math.floor(colors.length * Math.random())]

  return (
    <>
    <Tilt options={{defaultOptions}} className="blogs" 
    style={{border: `3px dashed ${rand}`, background: `${rand + "1c"}`}}>
      <div onClick={() => window.location.href = `/post/${e.id}`}>
        <img src={e.image}/>
        <h1>{e.post}</h1>
        <h2>{e.name}</h2>
        <p><small>{e.createAt}</small></p>
      </div>
        {/* <button onClick={() => handleDelete(e.id)}>eliminar</button> */}
      </Tilt>
    </>
  )
}

export default Blogcard

Thanks!!

Can creation of a PouchDB database be done as a Promise?

In PouchDB, when I put a document, I can manage the response and any errors in a Promise structure:

db.put(doc).then(function(response) {
  console.log(response);
}).catch(function(err) {
  console.log(err);
});

Can a similar approach be taken when creating the database?

The documentation says
const db = new PouchDB('dbname');

And the only upvoted (and accepted) answer to How do you catch errors on PouchDB creation? is effectively ‘Use db.info()‘.

Can I wrap the creation of a Pouch database in a Promise so that it’s result is thenable and failure is catchable?

At what points in the control flow of an inner function can an outer event listener be triggered

Take the following function:

export function repeater(): void {
  let timeout: number | undefined = undefined;
  const repeat = () => {
    some_slow_func();
    timeout = setTimeout(repeat, 100);
  };
  repeat();
  document.addEventListener('mouseup', () => clearTimeout(timeout), { once: true });
}

When the user releases their mouse, is it possible for clearTimeout to run, but only for timeout to be reset by the setTimeout line? E.g., say the user releases their mouse while some_slow_func() is running. I’ve played around with it and the answer seems to be that the event functionality will only be processed during a timeout, but I’d like to know why (and if this is actually correct).

ReactQuill: “getEditor is not a function” error when inserting images

I am building a post-writing page using Next.js (13), React (18), Apollo Client, and ReactQuill. The goal is to allow users to insert images into the editor, upload them to a server, and display the images within the editor.

Problem

When I try to use ReactQuill’s quillRef.current.getEditor() method to access the Quill editor instance and insert an image using insertEmbed, I get the following error:

TypeError: _quillRef$current.getEditor is not a function

This issue prevents images from being displayed in the editor after upload.


What I’ve Tried

  1. Accessing the Quill instance directly through the ref:

    const quill = quillRef.current.getEditor();

However, this results in the getEditor method being undefined.

  1. Dynamically importing ReactQuill in Next.js to avoid SSR issues:

    const ReactQuill = dynamic(() => import(“react-quill”), { ssr: false });

Even with dynamic import, the same error occurs.

  1. Ensuring the quillRef.current is not null by adding a useEffect to check initialization.

I want to:

  1. Allow users to upload images via ReactQuill.
  2. Use the Quill editor instance to insert the image URL at the current selection.
  3. Display the image in the editor after upload.

Minimum Reproducible Code

Here’s the simplified code where the issue occurs:

import dynamic from "next/dynamic";
import { useRef, useState } from "react";

const ReactQuill = dynamic(() => import("react-quill"), { ssr: false });

export default function Write() {
  const quillRef = useRef(null);
  const [content, setContent] = useState("");

  const imageHandler = () => {
    const input = document.createElement("input");
    input.setAttribute("type", "file");
    input.setAttribute("accept", "image/*");
    input.click();

    input.onchange = async () => {
      const file = input.files[0];
      const formData = new FormData();
      formData.append("file", file);

      try {
        const response = await fetch("http://localhost:4000/api/upload", {
          method: "POST",
          body: formData,
        });
        const data = await response.json();

        const quill = quillRef.current.getEditor(); // 여기서 에러 발생
        const range = quill.getSelection();

        quill.insertEmbed(range.index, "image", data.url);
      } catch (error) {
        console.error("이미지 업로드 실패:", error);
      }
    };
  };

  const modules = {
    toolbar: {
      handlers: { image: imageHandler },
    },
  };

  return (
    <ReactQuill
      ref={quillRef}
      value={content}
      onChange={setContent}
      modules={modules}
      theme="snow"
    />
  );
}

How to Trigger File Watch Recompile in Webpack 5 Without Modifying Files?

I’m developing a Webpack 5 plugin and need to manually trigger a recompile for a watched file without actually modifying it. This is primarily for some advanced HMR (Hot Module Replacement) use cases.

I came across this question on Stack Overflow and its solution, which involves using compiler.watchFileSystem to manipulate the file watcher. However, the provided solution seems outdated and incompatible with Webpack 5, as I couldn’t find:

compiler.watchFileSystem.watcher.fileWatchers.get(filePath).directoryWatcher.setFileTime( filePath, new Date().getTime(), false, false, "change" );

or:

compiler.watchFileSystem.watcher.fileWatchers.find(...).directoryWatcher.setFileTime(...)
The compiler.watchFileSystem object in my setup lacks the watcher property entirely, and thus the fileWatchers map is also unavailable.

What I’ve Tried:

  • Searching through Webpack 5’s source code to find if the watcher and fileWatchers are renamed or restructured.
  • Reading through the Webpack 5 documentation, but there doesn’t seem to be clear guidance on this.
  • Looking for other ways to simulate a “file change” event, but I couldn’t find anything concrete.

My Goal:
I want to:

  • Convince Webpack that a specific file has changed (without actually modifying the file on disk).
  • Trigger a recompilation for that file.

Does anyone know how to achieve this in Webpack 5? Alternatively, is there another approach to trigger a recompile programmatically for a specific file?

Any guidance or examples would be greatly appreciated!

How to implement conditional logic based on quiz results in JavaScript in anime suggestion app

I’m creating a quiz app that suggests anime series based on a few questions. After the user answers, I need to decide which series to recommend based on their responses. For example, if they like action, show one set of results, and if they prefer romance, show a different set. The app should display anime recommendations accordingly. I’m using JavaScript to process the answers and filter the suggestions, but I’m having trouble implementing the conditional logic properly. How can I make this work efficiently, especially when there are multiple possible outcomes?

I have created a function that checks the answers and uses if/else statements to display the appropriate results. I expected that after the user answers, the app would show the corresponding anime suggestions. However, when I test it, it sometimes displays incorrect results or doesn’t show anything at all. I tried using console.log to debug, but I’m not sure if the conditionals are being triggered properly.

How to Enable Premove in InputHandler

I am using cm-chessboard and I am trying to allow the player to drag his own pieces even though is not his turn. I am trying to accomplish this so I can allow premove. Premove means I am allowed to “premove” the next move in my opponents time. The issue is I cannot understand how to allow the user to drag moves when is not his turn.

const inputHandler = (event) => {
  if (event.type === INPUT_EVENT_TYPE.movingOverSquare) {
    return;
  }

  if (event.type !== INPUT_EVENT_TYPE.moveInputFinished) {
    event.chessboard.removeLegalMovesMarkers()
  }

  if (event.type === INPUT_EVENT_TYPE.moveInputStarted) {
    const moves = game.moves({square: event.squareFrom, verbose: true})
    event.chessboard.addLegalMovesMarkers(moves)
    return moves.length > 0

  } else if (event.type === INPUT_EVENT_TYPE.validateMoveInput) {
    const move = {from: event.squareFrom, to: event.squareTo, promotion: event.promotion}
    const result = game.move(move)

if (result) {
    event.chessboard.state.moveInputProcess.then(() => { 
      event.chessboard.setPosition(game.fen(), true)
    })
    return true;
} else {
        let possibleMoves = game.moves({square: event.squareFrom, verbose: true})
        for (const possibleMove of possibleMoves) {
            if (possibleMove.promotion && possibleMove.to === event.squareTo) {
                event.chessboard.showPromotionDialog(event.squareTo, COLOR.white, (result) => {
                    if (result.type === PROMOTION_DIALOG_RESULT_TYPE.pieceSelected) {
                        let pmove = game.move({from: event.squareFrom, to: event.squareTo, promotion: result.piece.charAt(1)})
                        event.chessboard.setPosition(game.fen(), true)
                    } else {
                        event.chessboard.setPosition(game.fen(), true)
                    }
                })
                return true
            }
        }
    }
    return result
}

}

Manually add page number to window.print()

I’m working on this task for 3 days now. I feel like I need to ask someone who’s well verse in JavaScript. I read multiple documentation about window.print() but I still do not get any fix.

Here’s my problem.

This is my html which is dynamically generated:

<body>
<div class="page-break page" data-div="0" id="printDiv_0">...long content here...</div>
<div class="page-break page" data-div="1" id="printDiv_1">...long content here..</div>
</body>

Now, when printing, I have a working code JS code except, when a div has multiple pages, it only add the prependedHeader to the 1st page, the subsequent pages is empty:

const testx = () => {
    const docs = document.querySelectorAll('.page-break');

    const createHeader = (leftText, rightText) => {
        const header = document.createElement('div');
        header.style.display = 'flex';
        header.style.justifyContent = 'space-between';
        header.style.paddingRight = '10px';
        header.style.paddingLeft = '10px';
        header.style.alignItems = 'center';
        header.style.marginBottom = '0px';
        header.style.fontWeight = 'bold';
        header.style.fontSize = '15px';
        header.classList.add("font-weight-bold");
        header.classList.add("print-header-div");

        // Left column
        const leftDiv = document.createElement('div');
        leftDiv.textContent = leftText;

        // Right column
        const rightDiv = document.createElement('div');
        rightDiv.textContent = rightText;

        header.appendChild(leftDiv);
        header.appendChild(rightDiv);

        return header;
    };

    docs.forEach((div, index) => {
        // Safely retrieve elements and fallback to defaults if missing
        const sectionId = div.getAttribute('data-div') || `Section ${index + 1}`;
        const requestCode = div.querySelector('#RequestCode')?.value || 'Unknown Request Code';
        const lastName = div.querySelector('.print-last-name')?.innerHTML || 'Unknown Last Name';
        const firstName = div.querySelector('.print-first-name')?.innerHTML || 'Unknown First Name';
        const dob = div.querySelector('.print-dob')?.innerHTML || 'Unknown DOB';

        // Generate the eOrderIdentity
        const eOrderIdentity = `${requestCode} ${lastName} ${firstName} ${dob}`;

        // Get total pages for the current div (assuming it has content that spans multiple pages)
        const totalPages = calculatePageCount(div) 
        const currentPage = 1; // For single div context, always start at 1

        // Create and prepend a header for the current page
        const prependedHeader = createHeader(
            `${eOrderIdentity}`,
            `Page ${currentPage} of ${totalPages}`
        );
        div.insertBefore(prependedHeader, div.firstChild);
    });

    // Trigger the print dialog
    window.print();
};





// Letter size by default
function calculatePageCount(content, pageHeight = 1056, pageWidth = 216) {
    let contentElement;
    if (typeof content === 'string') {
        contentElement = document.createElement('div');
        contentElement.innerHTML = content;
    } else if (content instanceof HTMLElement) {
        contentElement = content.cloneNode(true);
    } else {
        throw new Error('Invalid content. It must be an HTML string or a DOM element.');
    }

    contentElement.style.cssText = `
            visibility: hidden;
            position: absolute;
            width: ${pageWidth}mm;
            top: -9999px;
        `;
    document.body.appendChild(contentElement);

    const contentHeight = contentElement.scrollHeight;
    const totalPages = Math.ceil(contentHeight / pageHeight);
    //document.body.removeChild(contentElement);

    return totalPages;
}

Each div prependedHeader will reset on the next div.

For example:

The 1st div has 3 pages, the Header on each page will be Page 1 of 3, Page 2 of 3, Page 3 of 3.

The 2nd div has 2 pages, the Header on each page will be Page 1 of 2, Page 2 of 2.

Same for 1 paged div.

they will all be printed when the window.print() is called.

Thanks in advance!

VSC adding project name as a field to package.json

I’m facing an issue where the following keeps appearing in the dependencies section of my package.json: "myProjectName": "file:"
This also modifies my package-lock.json file, adding an entry like this:

"node_modules/myProjectName": {
  "resolved": "",
  "link": true
}

Each time I manually remove these changes, they reappear when I open the project in VSC. This behavior doesn’t happen in other IDEs or editors, so it seems to be specific to VS Code.

I tried dissabling all the extensions, updating VSC, reinstalling, checking for symlinks.

Why doesn’t my audio repeat after it ends?

I am trying to replay an audio file (jump.mp3) using Howler.js. However, the audio only plays once and does not repeat after it ends.

What I expected:

  • The audio should loop (repeat automatically) once it reaches the end.

What happens:

  • The audio plays only once and does not repeat after it ends.

How can I modify my code to ensure the audio repeats automatically after it finishes playing?

Here is a full Stackblitz Demo.

Here is my code:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Audio Example</title>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <button onclick="repeatAudio()">Repeat Audio</button>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/howler.min.js"></script>
    <script>
      class AudioManager {
        static sounds = {};
        static volume = 1;

        static load(audioFile) {
          if (!this.sounds[audioFile]) {
            this.sounds[audioFile] = new Howl({
              src: [audioFile],
              volume: this.volume,
              preload: true,
              onend: () => {},
            });
          }
        }

        static play(audioFile) {
          if (!this.sounds[audioFile]) {
            this.load(audioFile);
          }
          this.sounds[audioFile].play();
        }

        static replay(audioFile) {
          if (!this.sounds[audioFile]) {
            this.load(audioFile);
          }
          const sound = this.sounds[audioFile];
          sound.stop();
          sound.play();
        }
      }

      function repeatAudio() {
        AudioManager.replay('jump.mp3');
      }
    </script>
  </body>
</html>

how to make the longitude and latitude lines on map disappear in google maps api

I have this map in js code in google map api, and I cannot find solution how to make longitude and latitude lines on map disappear.

An image showing the longitude and latitude lines I want to remove

My attempt so far:

guessMap = new google.maps.Map(document.getElementById("guessMap"), {
    center: { lat: 0, lng: 0 },
    zoom: 2,
    streetViewControl: false,
    mapTypeControl: false,
    fullscreenControl: false,
    minZoom: 2, // Minimalny zoom
    maxZoom: 15, // Maksymalny zoom
    restriction: { // Ograniczenia geograficzne
      latLngBounds: {
        north: 85,
        south: -85,
        east: 180,
        west: -180,
      },
      strictBounds: true,
    },
    styles: [ // Styl mapy
      {
        "featureType": "administrative",
        "elementType": "geometry",
        "stylers": [{ "visibility": "on" }]
      },
      {
        "featureType": "landscape",
        "elementType": "geometry",
        "stylers": [{ "visibility": "on" }]
      },
      {
        "featureType": "poi",
        "elementType": "labels",
        "stylers": [{ "visibility": "on" }]
      },
      {
        "featureType": "road",
        "elementType": "geometry",
        "stylers": [{ "visibility": "on" }]
      },
      {
        "featureType": "transit",
        "elementType": "labels",
        "stylers": [{ "visibility": "on" }]
      },
      {
        "featureType": "water",
        "elementType": "geometry",
        "stylers": [{ "visibility": "on" }]
      },
      {
        "featureType": "administrative.land_parcel",
        "elementType": "geometry",
        "stylers": [{ "visibility": "off" }]
      },
      {
        "featureType": "administrative.locality",
        "elementType": "labels",
        "stylers": [{ "visibility": "on" }]
      },
      {
        "featureType": "administrative.neighborhood",
        "elementType": "labels",
        "stylers": [{ "visibility": "on" }]
      },
      {
        "featureType": "administrative.province",
        "elementType": "labels",
        "stylers": [{ "visibility": "on" }]
      }
    ]
});

I tried to enable and disable some things but when I turn off administrative geometry borders in countries disappear too.

Why does fs.link() fail with EPERM whre fs.rename() succeeds?

I want to serve some static files under the directory /var/www I would like to swap in a new set of files (which exist as, for example, /var/data/example) every few days or so. The server does not follow symlinks (the host is Linux).

So the curious thing is that when I try a hardlink I get an EPERM:

fs.link('/var/data/example', '/var/www');

This is a bit surprising, since I can create /var/www. What’s more if I do this:

fs.rename(`/var/data/example', '/var/www')

it works! I am mystified by this. I would rather use links, as it allows me to preserve what used to be there, rather than clobbering it.

Does anyone know why this might be happening?