Is storing socket objects in Map can cause issues in a production environment with larger amount of clients?

I’m using ocpp-rpc package to run an OCPP server, currently I’m using Map to store the connected clients object, I want to reference them later.

I’m storing them like below

const connectedChargers = new Map();

server.on('client', async (client) => {
    console.log(`${client.identity} connected!`);

    connectedChargers.set(client.identity, client); // storing client reference
});

I want to know is this a best practice to do? Is there any better way to achieve this?
My system going to have thousands of clients that connecting to the server, so I need optimal way to handle this.

Also I tried to save them in the Redis, but it fails due to circular references.

Basically I need to know that my aproach is good or bad and if it is bad a better way to achieve this.

I tried to save them in the Redis, but it fails due to circular references. I want

Cannot create entry or view entry list inside the Code Journal

I am making a code journal to write down entries on a virtual journal and make them viewable, editable, and deletable. The error I am getting is:

main.js:71 Uncaught Error: No entries or entry list!
at toggleNoEntries (main.js:71:15)
at HTMLFormElement.<anonymous> (main.js:28:5) .
Can someone tell me what I am missing or doing wrong?

HTML: HTML:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Code Journal</title>
    <link rel="stylesheet" href="css/reset.css" />
    <link rel="stylesheet" href="css/layout.css" />
    <link rel="stylesheet" href="css/styles.css" />
  </head>
   <body>
    <header>
      <div class="container">
        <div class="row">
          <div class="column-full navbar">
            <h1 class="code-journal">Code Journal</h1>
            <div>
              <a href="#" id="entries-link">Entries</a>
            </div>
          </div>
        </div>
      </div>
    </header>
    <main class="container">
      <div data-view="entry-form">
        <div class="row">
          <div class="column-full">
            <h1 class="new-entry">New Entry</h1>
          </div>
        </div>

        <form id="entry-form">
          <div class="row">
            <div class="column-half">
              <img
                id="url-preview"
                src="/images/placeholder-image-square.jpg"
                alt="Image preview"
                class="url-preview" />
            </div>
            <div class="column-half">
              <div class="input">
                <label for="title">Title</label>
                <input type="text" id="title" required />
              </div>
              <div class="input">
                <label for="photo-url">Photo URL</label>
                <input type="url" id="photo-url" required />
              </div>
            </div>
          </div>
          <div class="row">
            <div class="column-full">
              <label for="content">Notes</label>
              <textarea id="content" cols="30" rows="10" required></textarea>
            </div>
          </div>
          <div class="row">
            <div class="column-full button-container">
              <button type="submit">SAVE</button>
            </div>
          </div>
        </form>
      </div>
      <div data-view="entries" class="hidden">
        <div class="row">
          <div class="column-full entries-heading">
            <h1>Entries</h1>
            <p class="no-entries">No entries</p>
            <a href="#" id="new-entry-button" class="new-entry-button">NEW</a>
          </div>
        </div>
        <ul class="entry-list"></ul>
      </div>
    </main>
    <script src="js/data.js"></script>
    <script src="js/main.js"></script>
  </body>
</html>

Typescript:

const $form = document.querySelector('#entry-form') as HTMLFormElement;
const $urlPreview = document.querySelector('#url-preview') as HTMLImageElement;
const $photoUrlInput = document.querySelector('#photo-url') as HTMLInputElement;

if (!$form) throw new Error('$form query failed!');
if (!$urlPreview) throw new Error('$urlPreview query failed!');
if (!$photoUrlInput) throw new Error('$photoUrlInput query failed!');

$photoUrlInput.addEventListener('input', function (event: Event) {
  const target = event.target as HTMLInputElement;
  $urlPreview.src = target.value || 'images/placeholder-image-square.jpg';
});

$form.addEventListener('submit', function (event: Event) {
  event.preventDefault();

  const newEntry = {
    entryId: data.nextEntryId,
    title: ($form.elements.namedItem('title') as HTMLInputElement).value,
    photoUrl: $photoUrlInput.value,
    content: ($form.elements.namedItem('content') as HTMLTextAreaElement).value,
  };
  const $newEntryElement = renderEntry(newEntry);
  const $entryList = document.getElementById('entry-list');

  if ($entryList && $newEntryElement) {
    $entryList.appendChild($newEntryElement);
  }

  toggleNoEntries();

  data.nextEntryId++;
  data.entries.unshift(newEntry);

  writeData();

  $form.reset();
  $urlPreview.src = 'images/placeholder-image-square.jpg';
});

function renderEntry(entry: JournalEntry): HTMLElement {
  const $li = document.createElement('li');
  $li.classList.add('row');

  const $imgWrapper = document.createElement('div');
  $imgWrapper.classList.add('column-half');

  const $img = document.createElement('img');
  $img.src = entry.photoUrl;
  $img.alt = `${entry.title}`;
  $img.classList.add('url-preview');

  const $div = document.createElement('div');
  $div.classList.add('column-half');

  const $h2 = document.createElement('h2');
  $h2.textContent = entry.title;

  const $p = document.createElement('p');
  $p.textContent = entry.content;

  $li.appendChild($imgWrapper);
  $li.appendChild($div);
  $div.appendChild($h2);
  $div.appendChild($p);

  return $li;
}

document.addEventListener('DOMContentLoaded', function () {
  const $ul = document.querySelector('ul');
  if (!$ul) throw new Error('$ul query has failed!');

  data.entries.forEach((entry) => {
    const entryElement = renderEntry(entry);
    $ul.appendChild(entryElement);
  });
});

function toggleNoEntries(): void {
  const $noEntries = document.getElementById(
    'no-entries',
  ) as HTMLParagraphElement;
  // const $entryList = document.getElementById('.entry-list');

  if (!$noEntries) throw new Error('No entries!');

  if (data.entries.length === 0) {
    $noEntries.style.display = 'block';
  } else {
    $noEntries.style.display = 'none';
  }
}

function viewSwap(view: 'entries' | 'entry-form'): void {
  const $entriesView = document.querySelector(
    '[data-view="entries"]',
  ) as HTMLElement;
  const $entryFormView = document.querySelector(
    '[data-view="entry-form"]',
  ) as HTMLElement;

  if (!$entriesView || !$entryFormView)
    throw new Error('View elements not found!');

  if (view === 'entries') {
    $entriesView.classList.remove('hidden');
    $entryFormView.classList.add('hidden');
  } else if (view === 'entry-form') {
    $entryFormView.classList.remove('hidden');
    $entriesView.classList.add('hidden');
  }

  data.view = view;
}

const $entriesLink = document.getElementById(
  'entries-link',
) as HTMLAnchorElement;

if (!$entriesLink) throw new Error('$entriesLink query failed!');

$entriesLink.addEventListener('click', function (event: Event) {
  event.preventDefault();
  viewSwap('entries');
});

const $newEntryButton = document.getElementById(
  'new-entry-button',
) as HTMLAnchorElement;

if (!$newEntryButton) throw new Error('$newEntryButton query failed!');

$newEntryButton.addEventListener('click', function (event: Event) {
  event.preventDefault();
  viewSwap('entry-form');
});

I don’t need $entryList, but if I were to delete it, I would lose the content of the title and notes of when I press the entries button inside of the header. Could it also be something wrong I did in my html?

Hamburger Menu Only Works on index.html, Not Other Pages in My Portfolio Website

I’m working on a personal portfolio website and have implemented a hamburger menu for mobile views. The hamburger menu works perfectly on my index.html page, but it doesn’t function on any of the other pages like about.html or research.html.

The hamburger menu in my index.html works as expected, but when I navigate to any other page (e.g., about.html), clicking the menu doesn’t do anything. I use the same HTML structure and link to the same external JavaScript file (scripts.js) for all pages.

Here’s my setup:
index.html (Header part):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Portfolio | Home</title>
    <link rel="stylesheet" href="styles.css"> <!-- Link to CSS -->
    <script defer src="scripts.js"></script> <!-- Link to JavaScript -->
    <link rel="icon" href="images/logos/favicon.png" type="image/png">
</head>
<body>
    <!-- Navigation Bar -->
    <header>
        <div class="nav-container">
            <div class="logo">
                <a href="index.html">
                    <img src="images/logos/logo.png" alt="Logo">
                </a>
            </div>
            <nav class="nav-menu">
                <a href="about.html">About</a>
                <a href="research.html">Research</a>
                <a href="blog.html">Blog</a>
                <a href="publications.html">Publications</a>
            </nav>
            <div class="hamburger-menu">
                <span></span>
                <span></span>
                <span></span>
            </div>
        </div>
    </header>
</body>
</html>

about.html (Same structure as index.html for the header):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Portfolio | About</title>
    <link rel="stylesheet" href="styles.css"> <!-- Link to CSS -->
    <script defer src="scripts.js"></script> <!-- Link to JavaScript -->
    <link rel="icon" href="images/logos/favicon.png" type="image/png">
</head>
<body>
    <!-- Navigation Bar -->
    <header>
        <div class="nav-container">
            <div class="logo">
                <a href="index.html">
                    <img src="images/logos/logo.png" alt="Logo">
                </a>
            </div>
            <nav class="nav-menu">
                <a href="about.html">About</a>
                <a href="research.html">Research</a>
                <a href="blog.html">Blog</a>
                <a href="publications.html">Publications</a>
            </nav>
            <div class="hamburger-menu">
                <span></span>
                <span></span>
                <span></span>
            </div>
        </div>
    </header>
</body>
</html>

JavaScript (scripts.js):

document.addEventListener('DOMContentLoaded', () => {
    const texts = [
        "where we explore the evolution and pharmacology of proteins.",
        "where we investigate the expansion of genes.",
        "where we conduct studies.",
        "where we study structure.",
        "where we learn new tools and explore visualization."
    ];

    let index = 0;
    const animatedTextElement = document.getElementById('animated-text');
    console.log('Animated text element:', animatedTextElement);

    function typeWriter(text, callback) {
        let i = 0;
        const speed = 50;

        function typing() {
            if (i < text.length) {
                animatedTextElement.textContent += text.charAt(i);
                i++;
                setTimeout(typing, speed);
            } else if (callback) {
                setTimeout(callback, 1000);
            }
        }

        typing();
    }

    function deleteText(callback) {
        let i = animatedTextElement.textContent.length;
        const speed = 30;

        function deleting() {
            if (i > 0) {
                animatedTextElement.textContent = animatedTextElement.textContent.substring(0, i - 1);
                i--;
                setTimeout(deleting, speed);
            } else if (callback) {
                setTimeout(callback, 500);
            }
        }

        deleting();
    }

    function cycleTexts() {
        typeWriter(texts[index], () => {
            deleteText(() => {
                index = (index + 1) % texts.length;
                cycleTexts();
            });
        });
    }

    cycleTexts();

    // Smooth scrolling for a specific section
    const videoSection = document.querySelector('.specific-section');
    if (videoSection) {
        const videoLink = document.querySelector('.scroll-to-section');
        if (videoLink) {
            videoLink.addEventListener('click', (event) => {
                event.preventDefault();
                videoSection.scrollIntoView({ behavior: 'smooth' });
            });
        }
    }

    // Form validation
    function validateForm(event) {
        const name = document.getElementById("name").value.trim();
        const email = document.getElementById("email").value.trim();
        const message = document.getElementById("message").value.trim();

        if (name === "" || email === "" || message === "") {
            alert("Please fill in all the required fields.");
            event.preventDefault(); // Prevent form submission if validation fails
            return false;
        }

        return true;
    }

    const form = document.getElementById("formId");
    if (form) {
        form.addEventListener("submit", validateForm);
    }

    // Hamburger menu toggle
    const hamburgerMenu = document.querySelector('.hamburger-menu');
    const navMenu = document.querySelector('.nav-menu');

    console.log('Hamburger menu:', hamburgerMenu);
    console.log('Nav menu:', navMenu);

    if (hamburgerMenu && navMenu) {
        hamburgerMenu.addEventListener('click', () => {
            navMenu.classList.toggle('active');
        });
    }
});

What I’ve Tried:

  1. Verified that the external JavaScript file is linked correctly on all pages (scripts.js is loaded).
  2. The HTML structure for the navigation bar is the same on both index.html and about.html.
  3. Checked for JavaScript errors in the console on about.html – no errors are shown.
  4. The JavaScript works on index.html but not on other pages.

My Expected Behavior:

I want the hamburger menu to toggle the .nav-menu on and off when clicked, across all pages, not just on the homepage (index.html).

What Could Be Causing the Issue?

  1. Could it be related to how I’m referencing the JavaScript or HTML structure across pages?
  2. Is there an issue with the JavaScript being loaded on other pages?

Any help or insights would be appreciated! Thanks in advance!

Application alert pop-up not appearing when browser launched via playwright

self.browser = self.playwright.chromium.launch(
                headless = False,
                slow_mo = 2000,
                devtools= True,
        args = [
            
            r"--user-data-dir=C:UsersuserAppDataLocalTempchrome_profile",
             "--allow-pre-commit-input" ,
        "--disable-background-networking","--disable-backgrounding-occluded-windows","--disable-blink-features=AutomationControlled",
        "--disable-browser-side-navigation","--disable-client-side-phishing-detection","--disable-default-apps" ,"--disable-dev-shm-usage","--disable-extensions",
        "--disable-features=VizDisplayCompositor","--disable-gpu","--disable-hang-monitor" ,"--disable-infobars" ,
        "--disable-popup-blocking" ,"--disable-prompt-on-repost","--disable-setuid-sandbox" ,"--disable-software-rasterizer","--disable-sync","--disable-web-security","--enable-automation",
        "--enable-logging ","--ignore-certificate-errors" ,"--log-level=0 "," --no-first-run",
        "--no-sandbox","--no-service-autorun","--password-store=basic","--proxy-bypass-list=*" ,"--proxy-server='direct://'","--remote-debugging-port=0" ,"--test-type" ,
        "--use-mock-keychain","--user-data-"
        ]
        self._browser = BrowserType.create_browser(browser_type)
        self._context = self._browser.new_context(              
                no_viewport = True,
                accept_downloads=True,
                bypass_csp=True,
                ignore_https_errors=True,
                 permissions=["geolocation", "notifications"],
            )
        self._context.clear_cookies()
         self._context.add_cookies([{
         'name': 'name',
         'value': 'value',
         'domain': 'domain',
         'path': '/'
         }])
  
        self._page = self._context.new_page()
<!-- BUTTONS START -->
<br>
&nbsp;
<input type="button" id="rules" name="rules" value="Rules" class="button-raised-primary" onclick="execute(this.form, 'rules');" accesskey="" style="">
&nbsp;
<input type="button" id="marketReport" name="marketReport" value="Launch market report" class="button-raised-primary" onclick="execute(this.form, 'marketReport');" accesskey="" style="">
&nbsp;
<input type="button" id="factReport" name="factReport" value="Launch fact report" class="button-raised-primary" onclick="execute(this.form, 'factReport');" accesskey="" style="">
</tr>
</tbody></table>
</div>
<!-- BUTTONS END -->

This is how i am launching the playwright browser and navigating to pages and when clicked on certain buttons the expected alert pop-up is not coming but if i refresh the browser manually by pausing the execution the pop-up starts appearing on those button click.
Also have provided the HTML of those buttons
say When i click to marketReport button the alert pop-up should appear but through playwright browser nothing is happening.Also in console execute function is not searchable which if i search through manually launched browser it works fine.
Button clicks should throw alert pop-up every time.

I have tried modifying the args that we pass to browser during launch but it didnt work.the alert pop-up should open on clicking buttons without manual intervention

How can I use Cloudflare Pages as an API server like Cloudflare Workers?

I’m currently using Cloudflare Workers as an API endpoint to return data to my application when I call the Worker URL. I’d like to achieve the same functionality using Cloudflare Pages. How can I configure Cloudflare Pages to return JSON data to my application instead of displaying web pages?
Any guidance on how to set up Cloudflare Pages to function as an API server would be greatly appreciated.

Lighthouse Reports Showing Mobile Layout Despite Desktop Configuration File

Lighthouse by defaults to the mobile layout. I am passing the lighthouseDesktopConfig file, located at lighthouse/core/config/lr-desktop-config from the node_modules to configure the tests for the desktop layout. However, the reports are still reflecting the mobile layout. Even with the desktop configuration being passed and there is also an error saying test timeout of 30000ms exceeded when i try running the test cases.
The version’s installed are

"playwright-lighthouse": "^3.2.6",
 "lighthouse": "^10.4.0"

enter image description here.

import {test } from '@playwright/test';
import{
    SLOW_3G_CONFIG
} from './constants.js'
import { checkWebVitals } from './webVitalsUtils.js';
import lighthouseDesktopConfig from 'lighthouse/core/config/lr-desktop-config.js';
import lighthouseMobileConfig from  'lighthouse/core/config/lr-mobile-config.js';

test('Performance metrics for Slow 3g network',async({playwright,browserName})=>{
    test.skip(browserName !== 'chromium','Running only on chrome');
    const browser=await playwright.chromium.launch({
        args:['--remote-debugging-port=9223'],
    });
    

    const page = await browser.newPage();

    await page.goto(HOME_PAGE_URL,{waitUntil:'networkidle'});

    await checkWebVitals({
        lighthouseConfig:lighthouseDesktopConfig,
        lightHouseNetworkOpts:SLOW_3G_CONFIG,
        portNumber:9223,
        page:page,
        reportName: 'lh-report-slow-3g-desktop',
    });
});

How create remote audio stream with webrtc transport with js-libp2p?

I have libp2p node
This node connects to the relay and has the ability to connect to a remote user.

this.libp2p = await createLibp2p({
    peerId: peerObject.PeerId,
    peerStore: PersistentPeerStore,
    addresses: {
        listen: [
            '/webrtc-direct',
            '/webrtc'
        ]
    },
    transports: [
        webRTCDirect(),
        webSockets({
            filter: filters.all
        }),
        webRTC(),
        circuitRelayTransport({
            discoverRelays: 2
        })
    ],
    peerDiscovery: boot,
    connectionEncryption: [noise()],
    streamMuxers: [yamux()],
    services: {
        identify: identify(),
        identifyPush: identifyPush(),
        pubsub: gossipsub(),
        dcutr: dcutr(),
        ping: ping(),
        dht: isDht ? kadDHT({
            kBucketSize: 12,
            kBucketSplitThreshold: `kBucketSize`,
            prefixLength: 32,
            clientMode: false,
            querySelfInterval: 5000,
            initialQuerySelfInterval: 1000,
            allowQueryWithZeroPeers: false,
            protocol: DhtProtocol,
            logPrefix: "libp2p:kad-dht",
            pingTimeout: 10000,
            pingConcurrency: 10,
            maxInboundStreams: 32,
            maxOutboundStreams: 64,
            peerInfoMapper: publicAddressesMapper,
        }) : () => {
        }
    },
    connectionManager: {
        minConnections: 20
    },
    transportManager: {
        faultTolerance: FaultTolerance.NO_FATAL
    },
    connectionGater: {
        denyDialPeer: (currentPeerId) => {
            return false
        },
    }
})

For transet text data.
Add listener for streams

await this.libp2p.handle(protoText, self.handler);
await this.libp2p.handle(protoAudio, self.handler);

handler
There I accept incoming data.

 handler: {
        value: async function ({ connection, stream }) {
            const protocol = stream.protocol
            if(stream.protocol === protoText) {
                const lp = lpStream(stream)

                const res = await lp.read()

                const output = new TextDecoder().decode(res.subarray())

                this._message = output
                this.printSmbl()
            }

            if(stream.protocol === protoAudio) {
                console.log('----------- stream --------------', '???')
               
            }
        },
        writable: true
    },

sender
Here I send data text and audio.
And I can’t figure out what to put here correctly.
It’s clear with the text, but not how to make an audio stream.



if(type === 'text') {
    const signal = AbortSignal.timeout(5000)

    this.DOM.input.textContent = ''
    const stream = await self.libp2p.dialProtocol(ma, proto, {
        signal
    });

    const lp = lpStream(stream)

    await lp.write(new TextEncoder().encode(msg))
}

if(type === 'audio') {
    const signal = AbortSignal.timeout(5000)
    this.DOM.input.textContent = ''
    
    const stream = await self.libp2p.dialProtocol(ma, protoAudio, {
        signal
    });
 
    ????

    return true
}

I can’t stream audio remotely.
I can’t find examples of how to transfer a audio stream.
I found examples of remote connection for webrtc but not for the libp2p library.

Issue with Previewing Multiple Images After Upload in React

I’m working on a React component that allows users to edit a product and upload images. While I’m able to set and preview a single image correctly, I’m having trouble with previewing multiple images. Specifically, the images do not display as expected right after the upload. in the line 78 the console.log do log the array of base 64 images but i don’t know why it do not previewing it

Here’s my code snippet:

"use client"
import { usePathname } from 'next/navigation'
import React, { useState } from 'react'
import { useEffect } from 'react'
import axios from 'axios'
import { OrbitProgress } from 'react-loading-indicators'
import Image from 'next/image'
import { render } from 'react-dom'
const EditContent = () => {
  // Get Data //
  const path = usePathname();
  const pathQeury = path.split("/");
  const id = pathQeury[3];
  const [fetched,setFetched] = useState(false);
  const [products,setProducts] = useState([])


  useEffect(() => {
    axios.get(`/api/OneProductGet/${id}`)
    .then((response) =>
     {setProducts(response.data);
        setFetched(true);
     })
    .catch((error) => console.error(error))
  },[id])
  console.log(products)
  //-------------------------------------------//


    // Data //
    const [title, setTitle] = useState("");
    const [description, setDescription] = useState("");
    const [price, setPrice] = useState(0);
    const [singleImage, setSingleImage] = useState(null);
    const [multipleImages, setMultipleImages] = useState([]);
    const [SingleImageSrc, setSingleImageSrc] = useState();
    const [MultipleImageSrc, setMultipleImageSrc] = useState([]);
    let MultipleImagesSrc = []; 
    let MultipleImages = [];
    //------------------------------------------------------//
    
    
// Tranforme Single Image Data To src //
    useEffect(() => {
      if(singleImage){
        const render = new FileReader();
  
        render.onload = (e) => {
          setSingleImageSrc(e.target.result);
        }
        render.readAsDataURL(singleImage);
      }
      else{
        setSingleImageSrc(products[0]?.images[0]);
      }
    },[singleImage,products[0]])
    console.log(SingleImageSrc)
//-------------------------------------//

// Function Of Handling Multiple Images //


MultipleImages.push(...multipleImages);


useEffect(() => {
  if(MultipleImages){
    MultipleImages.map((image) => {
      const render = new FileReader();

    render.onload = (e) => {
      setMultipleImageSrc(e.target.result);
    }
    render.readAsDataURL(image);
    MultipleImagesSrc.push(MultipleImageSrc);
  })
  }
  console.log(MultipleImagesSrc)
},[MultipleImages])
//--------------------------------------//
// Function Of Handling Data //
async function handleSubmit(){
  const formData = new FormData();

  formData.append('title', title);
  formData.append('description', description);
  formData.append('price', price);
  formData.append('singleImage', singleImage);
  formData.append('multipleImages', multipleImages);
}






    
    if (!fetched){
        return( 
        <div  className='flex justify-center items-center bg-white w-full m-5 rounded-lg ml-0 p-5'>
            <OrbitProgress color="#1e3a8a" size="medium" text="" textColor="" />
        </div>
        );
    }
  return (
    <div className=' bg-white w-full m-5 rounded-lg ml-0 p-5'>
        <h1 className=' ml-2 text-3xl mb-4 font-semibold text-blue-900'>Edit Product</h1>
      <form className='flex flex-col  gap-1' onSubmit={handleSubmit}>
        <label className='ml-1 text-blue-900 '>
          Product name <span className='text-red-500'>*</span>
        </label>
          <input required={true}  className='mb-2  border p-1 rounded-lg' type="text" name="title" placeholder={products[0]?.name}/>
        <label className='ml-1 text-blue-900 '>
          Description 
        </label>
          <textarea className='mb-2  border p-1 rounded-lg' name="content" rows="4" cols="50" placeholder={products[0]?.description} />
        <label className='ml-1 text-blue-900 '>Price (in MAD) <span className='text-red-500'>*</span></label>
        <input required={true} className='mb-2  border p-1 rounded-lg' type="number" name="price" placeholder={products[0]?.price} />
        
        <label className='text-blue-900'>Main Product Image  <span className='text-red-500'>*</span></label>
        <div className='grid grid-cols-4 gap-3'>
          { SingleImageSrc? (
            <div className='relative group h-full w-full flex rounded-xl overflow-hidden border-2'>
              <img
              
              src={SingleImageSrc}
              
              alt='hello'
              ></img>
              <div className='group-hover:opacity-20 transition-all bg-black h-full absolute opacity-0 w-full'></div>
              <button className=' absolute right-0' onClick={() => {setSingleImageSrc(undefined)}}>
                <i class='bx bx-x text-red-500 invisible  group-hover:visible absolute m-2 text-[30px] right-0'></i>
              </button>
            </div>
          ) : (<div className='hidden'></div>
          )}
          <div className='flex flex-col justify-center items-center text-center py-14 px-5 overflow-hidden relative border-dashed border-2 rounded-lg h-full '>
            <i class='bx bx-cloud-upload text-blue-900 text-[3em]'></i>
            <p className='w-[80%] '><span className='opacity-60'>Drop your images here or select</span> <span className='text-blue-900 opacity-100'>click to browse</span></p>
            <input required={true} type="file" name="singleImage" accept="image/*" className='z-10 w-full h-full absolute opacity-0' onChange={(e) => {setSingleImage(e.target.files[0])}}/>
          </div>
          
        </div>
        <label className='text-blue-900'>Product Images <span className='text-red-500'>*</span></label>
        <div className='grid grid-cols-4'>
        { MultipleImagesSrc.length > 0 ? (
          MultipleImagesSrc.map((image, i) => (
            <div key={i} className='relative group h-[232px] w-full rounded-xl overflow-hidden border-2'>
              <img
                src={image}  // Properly setting the base64 string here
                className='w-full h-full absolute'
                alt={`image-${i}`}  // Giving a unique alt attribute
              />
              <div className='group-hover:opacity-20 transition-all bg-black h-full absolute opacity-0 w-full'></div>
              <button className='absolute right-0' onClick={() => {MultipleImagesSrc.splice(i, 1)}}>
                <i className='bx bx-x text-red-500 invisible group-hover:visible absolute m-2 text-[30px] right-0'></i>
              </button>
            </div>
          ))
        ) : (
          <div className='hidden'></div>
        )}
          
          <div className='flex flex-col justify-center items-center text-center py-14 px-5 overflow-hidden relative border h-fit '>
            <i class='bx bx-cloud-upload text-blue-900 text-[3em]'></i>
            <p className='w-[80%] '><span className='opacity-60'>Drop your images here or select</span> <span className='text-blue-900 opacity-100'>click to browse</span></p>
            <input required={true} type="file" name="singleImage" accept="image/*" className='z-10 w-full h-full absolute opacity-0' multiple onChange={(e) => {setMultipleImages(e.target.files)}}/>
          </div>
          
        </div>
        <input type="submit" value="save" className='bg-blue-900 w-fit text-white pb-1 px-3 rounded-lg ' />
      </form>
    </div>
  )
}

export default EditContent

i tried to map the MultipleImagesSrc after i checked that it contain the base 64 of the images but it did not preview it

The problem:

The multiple images do not display as expected right after they are uploaded. I suspect it may be related to how I’m handling the state updates for the image previews.
The current method of rendering MultipleImagesSrc may not be working correctly.

Environment:

Next.js
React
Using Tailwind CSS for styling

Angular – Component making duplicate api ‘GET’ requests with behaviorsubject

I am working on an angular v14 application and I am having trouble figuring out how to fix an issue with my component making duplicate api calls.

I have a service that is shared between all components to set and retrieve state values. The value needed for the api call has an initial value set to be able to make the request when the component initializes.

@Injectable()
export class SharedService {
  private type$ = new BehaviorSubject<string>('some-tab-value');

  setType(type: string) {
    this.type$.next(libraryType);
  }

  getType() {
    return this.type$.asObservable();
  }
}

I have a top level component that sets the BehaviorSubject value whenever a user clicks a tab on the page with the tab value;

import { SharedService } from './services/shared.service';

export class TopLevelComponent {
  private initialValue = 'some value';

  constructor(private sharedService: SharedService) {}

  onTabClick(type) {
    this.sharedService.setType(type);
  }
}

I have another component that subscribes to the tab value clicked in the top level component. It is needed to make an api call.

import { SharedService} from '../../services/shared.service';
import { SomeService } from './services/some.service';

export class SomeOtherComponent implements OnInit {
  constructor(private sharedService: SharedService, private someService: SomeService) {}
  
  ngOnInit() {
    this.sharedService.getType().pipe(
      switchMap(selectedType => {
        // some api call
        return this.someService.getStuff(selectedType)
      })
    ).subscribe(value => {
       // this value is always logging twice when the component loads
       // also logs twice when clicking on tab in UI
       console.log(value)
     )
  }
}

The service that is handling the http requests look something like this

import { HttpClient } from '@angular/common/http';

@Injectable()
export class SomeService {
  constructor(private httpClient: HttpClient) {}

  getStuff(type) {
    return this.httpClient.get('some-url').pipe(
      catchError(err => {
        return throwError(() => new Error('Error while fetching stuff: ' + err));
      }
    )
  }

}

I think it has to do with the BehaviorSubject emitting the last and current values. I tried switching the BehaviorSubject into a Subject instead. However, since a Subject doesn’t take an initial value, I tried to set the initial value in the ngOnInit function inside the top level component. The other component does not fire the http request until the user clicks on a tab (but i want it to also fire when initializing).

I feel like this should be an easy fix but I have been stuck trying to resolve this. Any help is appreciated. Thanks

Laravel connection for xlcx

I’m using laravel 10 is it possible to direct connect the .xls that i made to laravel to transfer data directly to .xls and download is directly?

I what a possible answer and suggestions and a sample code that i can follow.

Unable to skip youtube ads anymore from browser console

I have this script that I used to paste in dev console and youtube ads used to get skipped if the ‘Skip Ads’ button was visible.

setInterval(()=>{try{ var elements = document.getElementsByClassName("ytp-skip-ad-button__text"); var skipAdBtn = elements?.[0];console.log("skip ad:",skipAdBtn);skipAdBtn.click(); } catch(err){} },5000)

However since the past few months, this has stopped working completely.
I checked that the Skip Ads button is in fact selected by the script (see 1 in the below image) just that the click does not happen. Also, when I click manually, the ad is skipped:

enter image description here

I am using Google Chrome. I tried incognito and even Microsoft Edge, but still the same problem.
Any help would be highly appreciated.

Identify vulnerable packages in CDN scripts

Is there a vulnerability scanner (SAST, SCA, or other) that flags in-code CDN scripts where the script is referencing a vulnerable package (ex. jQuery 1.9 is susceptible to XSS). Typically, SCA scans find vulnerable 3rd party packages by searching package.json, nuget, or the equivalent package listing; but do not scan the source code itself. SAST scans will scan the custom code, but not flag on specific versions of packages found (the screenshot below would flag on not using SRIs, but not for vulnerable versions). Is there either an existing SAST/SCA company that checks for these or a niche tool that will identify them?

enter image description here

Change background-colour of clicked button in react.js

var buttons = document.getElementsByClassName("time-button");

var click_listener = function(event) {
  //console.log("clicked " + event.target);
  for (var i = 0; i < buttons.length; i++) {
    buttons[i].classList.remove("clicked");
  }
  event.target.classList.add("clicked");
};
for (var i = 0; i < buttons.length; i++) {
  buttons[i].addEventListener("click", click_listener, false);
}
.clicked {
  background-color: orange;
}
<button className="time-button">9:30 am</button>
<button className="time-button">9:00 am</button>
<button className="time-button">8:30 am</button>
<button className="time-button">8:00 am</button>

I try to change the background color when click action ! So first click orange , other click without background, . Each button have to be single click to change background!
but I can`t remove class in this way

I expect the code to work with button clicks, first click on orange background, second click without background and so on. The way I did it, I can change one and delete the background of the other buttons, I want each button to work with its click, can someone help ?

How to get selected text when triple clicks?

When I triple click the last word in comment of issue in github, web will select the whole content of this comment rather than the current line in other websites. This is the first point I have seen.

I want to get the selected text in javascript, but function window.getSelection().toString() only catch the content in current line, I don’t know how to get the whole content in comment.

When I print window.getSelection() on console, I found window.getSelection() -> anchorNode -> innerText is what I want, but if I only get undefine as the return of window.getSelection().anchorNode.innerText in my code, meanwhile, the return of window.getSelection().anchorNode is also different with anchorNode content in the log of window.getSelection() (return of window.getSelection().anchorNode is a string and anchorNode content in the log of window.getSelection() is a json which contains lots of contents).

I want to know how I can get the expected content(whole comment) in javascript?

Pictures of log as below:

Log of window.getSelection()

Log of window.getSelection().anchorNode, this is just a string of current selected line content.

How to define an icon like FA icons in my webpage?

As Codeberg icon is not in FA, I try to include in my webpage (links simplified) as follows:

<script src='js/faCodeberg.js'></script>
<link rel="stylesheet" href="css/site.css" type="text/css">
...
<i class="fa-brands fa-codeberg"></i>

where js/faCodeberg.js is

'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var prefix = 'fab';
var iconName = 'codeberg';
var width = 512;
var height = 512;
var aliases = [];
var unicode = 'f366';
var svgPathData = 'M0.00 8.56C0.00 14.69 4.25 14.69 4.25 14.69 4.25 14.69 10.92 6.07 10.92 6.07 10.87 5.84 10.65 6.07 10.65 6.07 10.65 6.07 17.04 6.07 17.04 6.07 17.04 6.07 15.04 6.07 15.04 6.07 15.04 6.07 14.84 6.07 14.84 6.07 14.84 6.07 12.76 6.07 12.76 6.07 12.76 6.07 11.42 6.07 11.42 6.07 11.42 6.07 8.97 6.07 8.97 6.07 8.97 6.07 8.65 6.07 8.65 6.07 8.65 6.07 6.07 6.07 6.07 6.07 6.07 6.07 4.89 6.07 4.89 6.07 4.89 6.07 9.41 6.07 9.41 6.07 9.41 6.07 9.82 6.07 9.82 6.07 9.82 6.07 12.89 6.07 12.89 6.07 12.89 6.07 13.94 6.07 13.94 6.07 13.94 6.07 10.59 6.07 10.59 6.07 10.59 6.07 10.08 6.07 10.08 6.07 10.08 6.07 6.54 6.07 6.54 6.07 6.54 6.07 5.61 6.07 5.61 6.07 5.61 6.07 9.92 6.07 9.92 6.07 9.92 6.07 10.48 6.07 10.48 6.07 10.48 6.07 14.50 6.07 14.50 6.07 14.50 6.07 15.36 6.07 15.36 6.07 15.36 6.07 10.18 6.07 10.18 6.07 10.18 6.07 10.73 6.07 10.73 6.07 10.73 6.07 14.78 6.07 14.78 6.07 15.58 3.57 10.81 1.81 14.78 1.65 11.20 -6.35 6.78 -6.35 6.78 -6.35 6.78 -6.35 0.00 4.14 0.00 8.56ZM10.44 13.30C10.44 13.30 10.99 13.30 10.99 13.30 10.99 13.30 14.54 13.30 14.54 13.30 14.54 13.30 14.88 12.86 14.88 12.86 14.88 12.86 10.44 13.30 10.44 13.30ZM13.71 12.86C13.71 12.86 13.15 12.86 13.15 12.86 13.15 12.86 10.78 12.86 10.78 12.86 10.78 12.86 10.30 12.43 10.30 12.43 10.30 12.43 13.71 12.86 13.71 12.86ZM9.13 12.43C9.13 12.43 8.58 12.43 8.58 12.43 8.58 12.43 7.78 12.43 7.78 12.43 7.78 12.43 7.08 12.00 7.08 12.00 7.08 12.00 9.13 12.43 9.13 12.43Z';

exports.definition = {
  prefix: prefix,
  iconName: iconName,
  icon: [
    width,
    height,
    aliases,
    unicode,
    svgPathData
  ]};

exports.faCodeberg = exports.definition;
exports.prefix = prefix;
exports.iconName = iconName;
exports.width = width;
exports.height = height;
exports.ligatures = aliases;
exports.unicode = unicode;
exports.svgPathData = svgPathData;
exports.aliases = aliases;

and css/site.css contains

.fa-codeberg:before {
  content: "f366"; }

by imitation of CSS and JS for icons in Font Awesome GitHub. However, it is not working, as another symbol appears instead of the icon. What am I doing wrong or what I lack to do?

Thanks!