Map.set really really slow

Map.set is really slow for me. Taking 14.677 seconds to set 300-400 items. I’m using Chrome for testing.

I’ve created a custom Map object:

export class DataMap<T> extends Map<string, T> {
  constructor(...args:MapConstructorParameters){
    super(...(args as []))
  }
  updateFromList(values:any[], {key='id', sortKey=null} : UpdateFromListOptions){
    // const self = this;

    let _values:any[];
    if (sortKey){
      console.log('Sorting')
      _values = this._sortValues(values, sortKey) // implementation not shown for brevity
      console.log('Sorting Finished')
    } else {
      _values = []
    }

    console.log('Setting')
    _values.forEach((_:any)=>{
      this.set(_[key], _ as T)
    })
    console.log('Setting finished')

  }
}

The idea of updateFromList is a little bit of syntax sugar, to allow passing of a list of objects and append them by a ‘key’ to the map. The part that is really slow is this:

    console.log('Setting')
    _values.forEach((_:any)=>{
      this.set(_[key], _ as T)
    })
    console.log('Setting finished')

Is this use of the Map a no go or am doing something stupid here?

chrome.scripting.executeScript Fails with “Tab Not Found” Error After Creating a New Window in Chrome Extension

I’m developing a Chrome extension and encountering an issue with executing a script in a newly created tab. Here’s what I’m trying to achieve:

On a button click, I use chrome.windows.create api to open a new popup window. In window I am opening an external webpage.

      // Create the window at the bottom-right corner
      chrome.windows.create({
          url: "https://localhost/index.html", // Replace with your HTML file
          focused: true,
        },
        function (window) {

          tabId = window.id; // Store the ID of the created window

          console.log("Window created at bottom-right corner.", tabId);
          chrome.storage.local.set({
              tabId: tabId
            },
            function () {
              console.log("Popup window ID stored:", tabId);
            }
          );

        });

I am trying to send a message from background.js to https://localhost/index.html using following code


     // This part Working Successfully
    `chrome.windows.update(tabId, {
        focused: true,
     });

`
     chrome.scripting.executeScript({
        target: {
          tabId: tabId
        },
        func: () => {
          window.postMessage(message, '*');
        }
      }, () => {
        if (chrome.runtime.lastError) {
          console.error(`Script execution failed: ${chrome.runtime.lastError.message}`);
        } else {
          console.log('Message sent to the new window');
        }
     });

chrome.scripting.executeScript, is failing with Script execution failed. tab not found for id : XXXX error.

  1. I have included necessary permission e.g. tabs, activetab, scripting in v3 manifest file.
  2. I checked if the tab is fully loaded before attempting to execute the script.

I was wondering why am I receiving the “Tab Not Found” error, and how can I ensure that chrome.scripting.executeScript works correctly with newly created window?

My goal is to send message to https://localshot/index.html.

react-material-ui-carousel Warning: Prop ‘className did not match” error

I am trying to use react-material-ui-carousel package and I am running into this error:

Warning: Prop className did not match. Server: “MuiButtonBase-root MuiIconButton-root MuiIconButton-sizeMedium css-9sd0w4-MuiButtonBase-root-MuiIconButton-root” Client: “MuiButtonBase-root MuiIconButton-root MuiIconButton-sizeMedium css-ktslay-MuiButtonBase-root-MuiIconButton-root”

I am not really sure how to resolve this

page.js

"use client";

import { Box } from "@mui/material";
import React from "react";
import ImageCarousel from "./ImageCarousel";

export default function Home() {
  return (
    <Box sx={{ width: "100vw" }}>
      <Box
        sx={{
          justifyContent: "center",
          textAlign: "center",
          mt: "20px",
        }}
      >
        <ImageCarousel />
      </Box>
    </Box>
  );
}

ImageCarousel.js

import React from 'react';
import Carousel from 'react-material-ui-carousel'
import { Paper, Button } from '@mui/material'

function ImageCarousel(props)
{
    var items = [
        {
            name: "Random Name #1",
            description: "Probably the most random thing you have ever seen!"
        },
        {
            name: "Random Name #2",
            description: "Hello World!"
        }
    ]

    return (
        <Carousel>
            {
                items.map( (item, i) => <Item key={i} item={item} /> )
            }
        </Carousel>
    )
}

function Item(props)
{
    return (
        <Paper>
            <h2>{props.item.name}</h2>
            <p>{props.item.description}</p>

            <Button className="CheckButton">
                Check it out!
            </Button>
        </Paper>
    )
}

export default ImageCarousel;

Sorry if this is a stupid question. I am new to web dev and React

I’ve tried modifying my layout.js and creating createEmotionCache.js, however, I don’t really understand what I was doing and nothing fixed the issue.

How can an object in Java be an instance of two different classes?

I’m working in the Rhino JavaScript engine (implemented in Java) in a context where a Java object has been shared into my JavaScript code’s runtime. It seems the object is somehow simultaneously an instance of two different classes.

When I use instanceof to try and find out what kind of object it is, it passes for two different classes:

foreignObject instanceof Packages.java.lang.String;  // true
foreignObject instanceof GlideElement;               // true

How could this have been implemented? Is there a pure Java way to get an object to pass both these instanceof tests? Is there some other kind of magic going on here specific to the Rhino JavaScript engine?

Tweet Scraped Data Disorganized

So I’ve been recently using twitter’s own backend API that it uses to display tweet/user data on a webpage to scrape and try and find a user’s latest tweet. The main issue I’m having with this, is the data I’m getting back is all jumbled and all over the place, and sometimes not even containing the latest tweet. It feels like it’s just grabbing random tweets and sending it back. I’ve even added a function to sort through the tweets and only give me the data for the tweet id, the date it was created, and the text inside of it, but still even with that sorting, it doesn’t seem like it’s getting the latest tweets of users.

What I’m doing is using the network API call in the “UserTweets” API and using that and the headers to make a call to the API myself and get the data response that it normally would with the web browser. I’m using the user’s ID of the user I want to scrape and creating a guest token to use for the x-guest-token header. I’m getting back over 30k lines in a json file of tweets, but I feel like maybe it’s not giving me everything? I just don’t understand why the response I’m getting back is different than the response you see in the “Response” tab of the “Network” tab when looking at UserTweets.

If anyone has something like this functional, can you assit me with what’s wrong and what I’m getting wrong? This is the fetch I’m using to get tweets:

    const res = await fetch(
      `https://api.x.com/graphql/V7H0Ap3_Hh2FyS75OCDO3Q/UserTweets?variables=%7B%22userId%22%3A%22${userId}%22%2C%22count%22%3A20%2C%22includePromotedContent%22%3Atrue%2C%22withQuickPromoteEligibilityTweetFields%22%3Atrue%2C%22withVoice%22%3Atrue%2C%22withV2Timeline%22%3Atrue%7D&features=%7B%22rweb_tipjar_consumption_enabled%22%3Atrue%2C%22responsive_web_graphql_exclude_directive_enabled%22%3Atrue%2C%22verified_phone_label_enabled%22%3Afalse%2C%22creator_subscriptions_tweet_preview_api_enabled%22%3Atrue%2C%22responsive_web_graphql_timeline_navigation_enabled%22%3Atrue%2C%22responsive_web_graphql_skip_user_profile_image_extensions_enabled%22%3Afalse%2C%22communities_web_enable_tweet_community_results_fetch%22%3Atrue%2C%22c9s_tweet_anatomy_moderator_badge_enabled%22%3Atrue%2C%22articles_preview_enabled%22%3Atrue%2C%22tweetypie_unmention_optimization_enabled%22%3Atrue%2C%22responsive_web_edit_tweet_api_enabled%22%3Atrue%2C%22graphql_is_translatable_rweb_tweet_is_translatable_enabled%22%3Atrue%2C%22view_counts_everywhere_api_enabled%22%3Atrue%2C%22longform_notetweets_consumption_enabled%22%3Atrue%2C%22responsive_web_twitter_article_tweet_consumption_enabled%22%3Atrue%2C%22tweet_awards_web_tipping_enabled%22%3Afalse%2C%22creator_subscriptions_quote_tweet_preview_enabled%22%3Afalse%2C%22freedom_of_speech_not_reach_fetch_enabled%22%3Atrue%2C%22standardized_nudges_misinfo%22%3Atrue%2C%22tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled%22%3Atrue%2C%22rweb_video_timestamps_enabled%22%3Atrue%2C%22longform_notetweets_rich_text_read_enabled%22%3Atrue%2C%22longform_notetweets_inline_media_enabled%22%3Atrue%2C%22responsive_web_enhance_cards_enabled%22%3Afalse%7D&fieldToggles=%7B%22withArticlePlainText%22%3Afalse%7D`,
      {
        headers: {
          "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36 Edg/128.0.0.0",
          accept: "*/*",
          "accept-language": "en-US,en;q=0.9",
          authorization: "Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA",
          "content-type": "application/json",
          priority: "u=1, i",
          "sec-ch-ua": ""Chromium";v="128", "Not;A=Brand";v="24", "Microsoft Edge";v="128"",
          "sec-ch-ua-mobile": "?0",
          "sec-ch-ua-platform": ""Windows"",
          "sec-fetch-dest": "empty",
          "sec-fetch-mode": "cors",
          "sec-fetch-site": "same-origin",
          "x-guest-token": token,
          "x-twitter-active-user": "yes",
          "x-twitter-client-language": "en",
          Referer: "https://x.com/",
          "Referrer-Policy": "strict-origin-when-cross-origin"
        },
        body: null,
        method: "GET"
      });

Scroll continuously while condition is true using React Native’s ScrollView

I’m currently implementing a drag-and-drop list using react-native-gesture-handler. The list is implemented as a simple Array.map() within a ScrollView since a FlatList would be incompatible with some other UI structures used in the app.

I’ve got the drag and drop functionality working but am struggling with the last requirement, which is auto-scrolling the ScrollView when the user drags an item to the top or bottom screen edge. Basically, I’m looking for a way to do this:

while (someCondition) {
  scrollViewRef.current.slowlyScrollDown();
}

I’ve tried to do something like this:

const handleDrag = useCallback((absoluteY) => {
  const scrollThreshold = 100; // pixels from top/bottom to trigger scroll

  if (autoScrollTimerRef.current) {
    clearInterval(autoScrollTimerRef.current);
  }

  if (absoluteY < scrollThreshold) {
    // Scroll up
    const newOffset = currentScrollOffset - 10;
    autoScrollTimerRef.current = setInterval(() => {
      containerRef.current?.scrollTo({y: newOffset, animated: true});
    }, 1000 / 60);
    setCurrentScrollOffset(newOffset);
  } else if (absoluteY > screenHeight - scrollThreshold) {
    // Scroll down
    const newOffset = currentScrollOffset + 10;
    autoScrollTimerRef.current = setInterval(() => {
      containerRef.current?.scrollTo({y: newOffset, animated: true});
    }, 1000 / 60);
    setCurrentScrollOffset(newOffset);
  }
}, []);

However, this is extremely janky and in general not a pleasant experience. I’d suppose this is because the previous scroll animation didn’t complete when the next animation cycle starts.

Is there any better way to do this?

Why am I gettting CONDITIONALTAB_HAS_INVALID_PARENT when trying to send an envelope from a template?

I’m trying to send a DocuSign template with conditional tabs. Through the UI/web portal, it sends fine. Via the API, it errors with this response from DocuSign:

CONDITIONALTAB_HAS_INVALID_PARENT – A conditional tab references an invalid parent. Parent label must match another tab. Only one parent allowed. Signature tabs may not be parent tabs. Child tab with label: sig-spanish has an invalid parent.

We’ve boiled our template’s conditional tabs down to just a radio group with 2 radio buttons as the parent, and 2 signature fields that are conditional on corresponding radio buttons:

image of part of template

Inspecting our call to DocuSign (via the createEnvelope() method), here is how those fields are being sent:

[
  {
    roleName: "primary",
    tabs: {
      radioGroupTabs: [
        {
          documentId: "1",
          groupName: "radio-group1",
          originalValue: "Spanish",
          radios: [
            {
              bold: "false",
              font: "calibri",
              fontColor: "black",
              fontSize: "size10",
              italic: "false",
              locked: "false",
              pageNumber: "1",
              required: "true",
              selected: "true",
              tabId: "d032aff1-ecbd-4d51-bce2-c0fd4225ecbf",
              underline: "false",
              value: "Spanish",
              xPosition: "171",
              yPosition: "247",
            },
            {
              bold: "false",
              font: "calibri",
              fontColor: "black",
              fontSize: "size10",
              italic: "false",
              locked: "false",
              pageNumber: "1",
              required: "true",
              selected: "false",
              tabId: "a45319cb-d98c-42d2-942f-3a77202ee7e1",
              underline: "false",
              value: "English",
              xPosition: "170",
              yPosition: "326",
            },
          ],
          recipientId: "72120635",
          requireAll: "false",
          requireInitialOnSharedChange: "false",
          shared: "false",
          tabType: "radiogroup",
          templateLocked: "false",
          templateRequired: "false",
          value: "Spanish",
        },
      ],
      signHereTabs: [
        ...
        {
          conditionalParentLabel: "radio-group1",
          conditionalParentValue: "Spanish",
          documentId: "1",
          name: "SignHere",
          optional: "false",
          pageNumber: "1",
          recipientId: "72120635",
          scaleValue: "1",
          stampType: "signature",
          tabId: "65bef1a3-4cd3-4ff7-8d2b-80a57fc1fbd3",
          tabLabel: "sig-spanish",
          tabType: "signhere",
          templateLocked: "false",
          templateRequired: "false",
          tooltip: "SignHere",
          xPosition: "254",
          yPosition: "242",
        },
        {
          conditionalParentLabel: "radio-group1",
          conditionalParentValue: "English",
          documentId: "1",
          name: "SignHere",
          optional: "false",
          pageNumber: "1",
          recipientId: "72120635",
          scaleValue: "1",
          stampType: "signature",
          tabId: "e027af5d-32e5-4b15-9b8d-8d721f0de470",
          tabLabel: "sig-english",
          tabType: "signhere",
          templateLocked: "false",
          templateRequired: "false",
          xPosition: "253",
          yPosition: "316",
        },
      ],
      textTabs: [
        ...
      ],
    },
    email: "[email protected]",
    name: "Test",
    clientUserId: "[email protected]",
    embeddedRecipientStartURL: "SIGN_AT_DOCUSIGN",
  },
]

This, as far as I can tell, follows the official documentation on setting up conditional tabs. There is additional documentation that does mention a couple things:

Which types you are allowed to use for Parent conditional fields differ between the UI and the API. In the UI, you can use only the following tab types to trigger revealing conditional fields:

  • Checkbox
  • Radio button
  • Dropdown
  • Text

In the API, you can use any field type as a Parent field if you set its optional property to true.

Emphasis mine. This seems to imply that parent fields set via the API need optional: 'true'. However, I’ve tried setting that without any change. I believe the documentation means for any types that the UI doesn’t accept, the optional property has to be set to ‘true’.

Additionally, those docs specify:

If the conditional field is a Checkbox tab or button from a Radio Group tab, use on as the value to show that the parent tab is active.

However, after investigating, this doesn’t even make sense for radio buttons.

Things I’ve tried:

  • Setting optional: 'true' on the parents (as noted above)
  • Setting optional: 'true' on the child fields (maybe the docs were wrong)
  • Trying checkboxes instead
  • Removing all but one conditional child tab and one parent
  • Combinations of the above

HTML page keep refreshing infinetly

Can someone help me?
I’ve already tried a lot of solutions here. But my page keeps refreshing infinitely when I open the HTML on the live server.

The HTML form code is:

<form class="newItem" onsubmit="return false">
        <input type="text" id="newInput" placeholder="Nome">
        <input type="text" id="newPreg" placeholder="Pregancies">
        <input type="text" id="newPlas" placeholder="Glucose">
        <input type="text" id="newPres" placeholder="Blood Pressure">
        <input type="text" id="newSkin" placeholder="Skin Thickness">
        <input type="text" id="newTest" placeholder="Insulin">
        <input type="text" id="newMass" placeholder="BMI">
        <input type="text" id="newPedi" placeholder="Diabetes Pedigree Function">
        <input type="text" id="newAge" placeholder="Age">
        <button type="button" onclick="newItem(event)" class="addBtn">Diagnosticar</button>
    </form>

And the Script.js is:


const getList = async () => {
  let url = 'http://127.0.0.1:5000/pacientes';
  fetch(url, {
    method: 'get',
  })
    .then((response) => response.json())
    .then((data) => {
      data.pacientes.forEach(item => insertList(item.name, 
                                                item.preg, 
                                                item.plas,
                                                item.pres,
                                                item.skin,
                                                item.test,
                                                item.mass,
                                                item.pedi,
                                                item.age,
                                                item.outcome
                                              ))
    })
    .catch((error) => {
      console.error('Error:', error);
    });
}


getList()




const postItem = async (inputPatient, inputPreg, inputPlas,
                        inputPres, inputSkin, inputTest, 
                        inputMass, inputPedi, inputAge) => {
    
  const formData = new FormData();
  formData.append('name', inputPatient);
  formData.append('preg', inputPreg);
  formData.append('plas', inputPlas);
  formData.append('pres', inputPres);
  formData.append('skin', inputSkin);
  formData.append('test', inputTest);
  formData.append('mass', inputMass);
  formData.append('pedi', inputPedi);
  formData.append('age', inputAge);

  let url = 'http://127.0.0.1:5000/paciente';
  fetch(url, {
    method: 'post',
    body: formData
  })
    .then((response) => response.json())
    .catch((error) => {
      console.error('Error:', error);
    });
}


const insertDeleteButton = (parent) => {
  ...
}


const removeElement = () => {
  ...
}


const deleteItem = (item) => {
  ...
}


const newItem = async (event) => {
  event.preventDefault();

  let inputPatient = document.getElementById("newInput").value;
  let inputPreg = document.getElementById("newPreg").value;
  let inputPlas = document.getElementById("newPlas").value;
  let inputPres = document.getElementById("newPres").value;
  let inputSkin = document.getElementById("newSkin").value;
  let inputTest = document.getElementById("newTest").value;
  let inputMass = document.getElementById("newMass").value;
  let inputPedi = document.getElementById("newPedi").value;
  let inputAge = document.getElementById("newAge").value;

  const checkUrl = `http://127.0.0.1:5000/pacientes?nome=${inputPatient}`;
  fetch(checkUrl, {
    method: 'get'
  })
    .then((response) => response.json())
    .then((data) => {
      if (data.pacientes && data.pacientes.some(item => item.name === inputPatient)) {
        alert("O paciente já está cadastrado.nCadastre o paciente com um nome diferente ou atualize o existente.");
      } else if (inputPatient === '') {
        alert("O nome do paciente não pode ser vazio!");
      } else if (isNaN(inputPreg) || isNaN(inputPlas) || isNaN(inputPres) || isNaN(inputSkin) || isNaN(inputTest) || isNaN(inputMass) || isNaN(inputPedi) || isNaN(inputAge)) {
        alert("Esse(s) campo(s) precisam ser números!");
      } else {
        insertList(inputPatient, inputPreg, inputPlas, inputPres, inputSkin, inputTest, inputMass, inputPedi, inputAge);
        postItem(inputPatient, inputPreg, inputPlas, inputPres, inputSkin, inputTest, inputMass, inputPedi, inputAge);
        alert("Item adicionado!");
      }
    })
    .catch((error) => {
      console.error('Error:', error);
    });

    event.preventDefault();
    return false;

}


const insertList = (namePatient, preg, plas,pres, skin, test, mass, pedi, age, outcome) => {
  var item = [namePatient, preg, plas,pres, skin, test, mass, pedi, age, outcome];
  var table = document.getElementById('myTable');
  var row = table.insertRow();

  for (var i = 0; i < item.length; i++) {
    var cell = row.insertCell(i);
    cell.textContent = item[i];
  }

  var deleteCell = row.insertCell(-1);
  insertDeleteButton(deleteCell);


  document.getElementById("newInput").value = "";
  document.getElementById("newPreg").value = "";
  document.getElementById("newPlas").value = "";
  document.getElementById("newPres").value = "";
  document.getElementById("newSkin").value = "";
  document.getElementById("newTest").value = "";
  document.getElementById("newMass").value = "";
  document.getElementById("newPedi").value = "";
  document.getElementById("newAge").value = "";

  removeElement();
}

The API is working perfectly on Swagger. The loop only occurs when I open the index.html. Sometimes the loop stops, but after submitting a form it returns the loop.

Server Side Event will not allow client side events to run at the same time

I am attempting to have updates sent whenever they are available from the server utilizing Javascript and PHP. It works as it is supposed to. The basic oulite of the code is as follows

My code simplified looks like this


        var sourceCallUpdater = new EventSource("./js/newmessage2.php");
      
      sourceCallUpdater.addEventListener('NewCall', (e) => {
                   //The returned information is processed and updated to the clients page with code in here
                  
                });

The problem I am having is that while the client is waiting for the server to respond back I can not run any other javascript actions locally. For instance I want to update another part of my page with the following code

function GotoPage(Page) {
        // alert("./pages/" + Page + ".php");

            $.post("./pages/" + Page + ".php", {  },
                    function(data) {
                        $('#Content').html(data);
                        });
                                 
        }

The code works when the client clicks on a button that calls the GotoPage(Page) function, however it will not execute the task until the server has returned the response for the Eventsource called at the start of this question.

Any suggestions. I need to be able to do both at the same time.

problem in receiving the foreground messages through firebase

I have setup a next app, and want to receive firebase foreground messages.
I created two files, firebase.js, firebase-notification.js.

Inside the firebase.js file I have configured the firebase app-

eslint-disable import/no-mutable-exports -- to ignore let error*/

import { initializeApp } from 'firebase/app';


const firebaseConfig = {
apiKey: 'my api key',
authDomain: 'my domain',
projectId: 'my project id',
storageBucket: 'My storage bucket',
messagingSenderId: 'senderID',
appId: 'My app id',
measurementId: 'measurement ID',
 };

export const app = initializeApp(firebaseConfig);

Inside the firebase-notifications.js file I have setup the messaging and listeners

'use client';

import * as React from 'react';
import { getMessaging, getToken, onMessage } from 'firebase/messaging';

import { adminProfile } from '@/lib/admin';
import { carrierProfile } from '@/lib/carrier';
import { app } from '@/lib/firebase';
import { shipperProfile } from '@/lib/shipper';
import { useUser } from '@/hooks/use-user';

let messaging;
if (typeof window !== 'undefined') {
  messaging = getMessaging(app);
}

export function WebNotifications() {
  // console.log('Setting up Web Notification', messaging);
  const { user } = useUser();

  React.useEffect(() => {
    if (user?.app_type) {
      requestPermission();
       }
  }, []);

  // Request permission to send notifications
  const requestPermission = async () => {
    try {
      const permission = await Notification.requestPermission();

      if (permission === 'granted') {
        // Get the token
        const token = await getToken(messaging, {
          vapidKey: 'my vapid key',
        });
        if (token) {
          const requestOptions = {
            admin: adminProfile.updateNotificationToken,
            sub_admin: adminProfile.updateNotificationToken,
            shipper: shipperProfile.updateNotificationToken,
            sub_shipper: shipperProfile.updateNotificationToken,
            carrier: carrierProfile.updateNotificationToken,
            sub_carrier: carrierProfile.updateNotificationToken,
          };

          // Send this token to server
          const request = requestOptions[user.app_type];
          request({ device_id: token })
            .then(() => {
              setupForegroundMessageListener();
            })
            .catch((_) => {});
        }
        // else {
        //   console.log('No registration token available. Request permission to generate one.');
        // }
      }
      // else {
      //   console.log('Unable to get permission to notify.');
      // }
    } catch (_) {
      // console.log(_);
    }
  };

  const setupForegroundMessageListener = () => {
    console.log('Setting up listener');

    onMessage(messaging, (payload) => {
      console.log('Message received: ', payload);
      const notificationTitle = payload.notification.title;
      const notificationOptions = {
        body: payload.notification.body,
        icon: '@/app/icon.png',
      };
      // eslint-disable-next-line no-new -- We need to trigger a notification without storing the instance.
      new Notification(notificationTitle, notificationOptions);
    });
    console.log('Finished with setting up', messaging);
  };
  
  return false;
}

And i have used this web notification in my main layout.js file
as a child to enable notification.

These all console messages are printing for setting up the listener and finished with setting up

I was expecting a notification when my app is on foreground
for testing purpose I have send various notifications through my backend but not receiving in my friend.

Use a predefined array of string values against querySelectorAll, to perform a specific action

If I have a predefined array of string values, how can I see if any of them exist in the DOM via querySelectorAll and textContent?


//my array of predefined string values
let primaries = ["house", "people", "cat", "dog"];

let mTable = document.querySelectorAll("#mytable td font");

this is where I am stuck…I want to find any string from primaries against mTable. And if any string value is found, then perform a specific action (i.e. console.log("I found you"));

This is what I have so far but it only works for one element at a time. How can I expand my thought process..

var mPrimary = Array.from(
  mtable.querySelectorAll("td font")
).find((el) => el.textContent === "house");
if (mPrimary) {
  mPrimary.closest("tr").classList.add("d-none");
}

express-session data from backend to frontend on different port

I am running frontend and backend on different ports: backend localhost:8000 and frontend localhost:3001
I am using express-session middleware, I need to save access token there. So, I am doing authorization first, which gives me code, this code is only for one time use and then it is exchanged with access token. If I just send response data to backend port, all is working fine, after refreshing website, data is still there, access token is saved in session and all good, but when I try to fetch data from frontend, from different port, session is not saved there.
So, question is how can I send this session to frontend side?
I hope, I explain it well.

I have tried different ways but nothing worked out.

CSS Marquee Scrolling Effect Not Working as Expected

I’m trying to create a marquee scrolling effect from left to right using CSS, but I can’t get it to work correctly. The content is supposed to scroll smoothly, but it doesn’t behave as expected in my implementation.

My Goal

I want to create a smooth, continuous scrolling effect, similar to the classic <marquee> HTML tag but using modern CSS. The text and images should scroll from left to right across the screen in a loop.

The Problem

When I apply my CSS, the scrolling effect doesn’t work smoothly, and sometimes the content doesn’t loop as intended. I’m not sure if the issue lies with the @keyframes animation, the width settings, or something else.

What I’ve Tried

Here’s the CSS and HTML I’m using:

<style>
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@900&display=swap');

.iso-marquee {
  padding: 1.4rem 0;
  overflow: hidden;
  white-space: nowrap;
}

.iso-marquee--long {
  display: flex;
  justify-content: start;
  align-items: center;
  animation: iso-marquee 21s linear infinite;
  width: 2300px; /* Replace with your calculated total width */
  clear: both;
  padding-top: 45px;
  padding-bottom: 45px;
  border-bottom: 1px solid #121212;
  border-top: 1px solid #121212;
}

.marquee-container {
  display: flex;
  align-items: center;
  margin-right: 25px;
}

.TEES {
  font-family: 'Poppins', sans-serif;
  font-size: 85px;
  font-weight: 900;
  display: inline-block;
  margin-right: 2rem;
}

.branding {
  font-family: 'Roboto', sans-serif;
  font-weight: 300;
  display: flex;
  flex-direction: column;
  margin: 0;
  padding: 0;
}

@keyframes iso-marquee {
  from { transform: translateX(0); }
  to { transform: translateX(-50%); }
}

/* Reduce motion for accessibility */
@media (prefers-reduced-motion: reduce) {
  .iso-marquee {
    animation: none;
  }
}
</style>

<div class="iso-marquee-linkwrap">
  <div class="iso-marquee--long iso-marquee">
    <img src="https://mrbeast.store/cdn/shop/files/photo_2023-06-29_02-49-55.jpg?height=85&v=1718170165" alt="" />
    <span class="TEES">TEES</span>
    <div class="branding">
      <span>MAKE YOUR</span>
      <span>MARK WITH</span>
      <span>EXCITISM</span>
    </div>
    <div class="marquee-container">
      <img src="https://mrbeast.store/cdn/shop/files/photo_2023-06-29_02-49-55.jpg?height=85&v=1718170165" alt="" />
      <span class="TEES">TEES</span>
      <div class="branding">
        <span>MAKE YOUR</span>
        <span>MARK WITH</span>
        <span>EXCITISM</span>
      </div>
    </div>
    <div class="marquee-container">
      <img src="https://mrbeast.store/cdn/shop/files/photo_2023-06-29_02-49-55.jpg?height=85&v=1718170165" alt="" />
      <span class="TEES">TEES</span>
      <div class="branding">
        <span>MAKE YOUR</span>
        <span>MARK WITH</span>
        <span>EXCITISM</span>
      </div>
    </div>
  </div>
</div>

What I Expect

I expect the above code to create a marquee effect similar to this one:

<style>
.marquee {
  margin: 2rem 0;
  font-size: clamp(4vw, 4rem, 8vw);
  overflow: hidden;
}

.marquee--long {
  font-size: 1.25rem;
}

.marquee span {
  display: inline-block;
  white-space: nowrap;
  color: #00112C;
  width: var(--tw);
  text-shadow: var(--tw) 0 currentColor,
               calc(var(--tw) * 2) 0 currentColor,
               calc(var(--tw) * 3) 0 currentColor,
               calc(var(--tw) * 4) 0 currentColor;

  will-change: transform;
  animation: marquee var(--ad) linear infinite;
}

@keyframes marquee {
  0% { transform: translateX(0); }
  100% { transform: translateX(-100%); }
}

@media (prefers-reduced-motion: reduce) {
  .marquee div {
    animation: none;
    text-shadow: none;
    width: auto;
    display: block;
    line-height: 1.5;
    text-align: center;
    white-space: normal;
  }
}
</style>
<div class="marquee" style="--tw: 40vw; --ad: 2.5s;">
  <span>Showreel</span>
</div>

how do dynamically add objects to script field for auto complete

is is possible to add objects for the script field to have access to when it runs?
for example, i want to add the following;
“current”: { “name”: “juan” }

so when the user is typing “curr”, the auto complete will kick in and suggest ‘current’

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.47.0/min/vs/loader.min.js"
    integrity="sha512-ZG31AN9z/CQD1YDDAK4RUAvogwbJHv6bHrumrnMLzdCrVu4HeAqrUX7Jsal/cbUwXGfaMUNmQU04tQ8XXl5Znw=="
    crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  <title>Monaco Editor</title>
  <style>
    body, html {
      margin: 0;
      padding: 0;
      width: 100%;
      height: 100%;
      display: flex;
      overflow: hidden;
    }
    #editorArea, #output {
      flex: 1;
      min-width: 0;
    }
    #editorArea {
      display: flex;
      flex-direction: column;
      overflow: hidden;
    }
    #toolbar {
      padding: 10px;
      background-color: #f5f5f5;
      border-bottom: 1px solid #ccc;
    }
    #editorContainer {
      flex-grow: 1;
      overflow: auto;
    }
    #container {
      width: 100%;
      height: 100%;
    }
    #outputArea {
      display: flex;
      flex-direction: column;
      flex: 1;
      overflow: hidden;
    }
    #outputToolbar {
      padding: 10px;
      background-color: #f5f5f5;
      border-bottom: 1px solid #ccc;
    }
    #output {
      flex-grow: 1;
      padding: 10px;
      overflow: auto;
      border-left: 1px solid #ddd;
    }
  </style>
</head>
<body>
  <div id="editorArea">
    <div id="toolbar">
      <select id="languageSelector">
        <option value="javascript">JavaScript</option>
      </select>
    </div>
    <div id="editorContainer">
      <div id="container"></div>
    </div>
  </div>
  <div id="outputArea">
    <div id="outputToolbar">
      <button id="runCodeButton">Run</button>
      <button id="exitEditorButton">Exit Editor</button>
    </div>
    <div id="output">Output will appear here...</div>
  </div>

  <script>
    document.addEventListener('DOMContentLoaded', function () {
      require.config({
        paths: {
          'vs': 'https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.47.0/min/vs'
        }
      });
      require(['vs/editor/editor.main'], function () {
        const editor = monaco.editor.create(document.getElementById('container'), {
          value: "// Your code heren",
          language: 'javascript',
          theme: 'vs-dark',
          automaticLayout: true
        });

        document.getElementById('languageSelector').addEventListener('change', function () {
          const newLanguage = this.value;
          monaco.editor.setModelLanguage(editor.getModel(), newLanguage);
        });

        // Define the global object
        const globalObject = { "current": { "name": "juan" } };

        // Provide IntelliSense support for the global object
        monaco.languages.typescript.javascriptDefaults.addExtraLib(`
          interface GlobalObject {
            current: { name: string };
          }
          declare var globalObject: GlobalObject;
        `);

        document.getElementById('runCodeButton').addEventListener('click', function () {
          const originalConsoleLog = console.log;
          document.getElementById('output').textContent = '';

          console.log = function (...args) {
            document.getElementById('output').textContent += args.join(' ') + 'n';
          };

          try {
            const userCode = editor.getModel().getValue();
            // Pass the global object to the eval context
            eval(`
              var globalObject = ${JSON.stringify(globalObject)};
              ${userCode}
            `);
          } catch (e) {
            document.getElementById('output').textContent = 'Error: ' + e.message;
          } finally {
            console.log = originalConsoleLog;
          }
        });
      });

      // Listen for messages from Flutter
      window.addEventListener('message', function(event) {
        if (event.data && event.data.type === 'initMonaco') {
          console.log('Data received from Flutter:', event.data.objects);
          // Handle the data received from Flutter as needed
        }
      });
    });
  </script>
</body>
</html>

the editor i am using is called Monaco Code Editor.

this stack overflow seems be the same issue as mine::

Adding globally defined objects for Intellisense and linting to Monaco Editor in javascript/typescript