“Uncaught InternalError: too much recursion” when using Javascript’s standard string.includes( ) method

In Javascript, I am getting a “too much recursion” error in Firefox and Chrome when attempting to perform the following (simplified example):

const results = [];

for (let i = 0; i < 1000; i++) {
   if ("alksdhflasdkhflsakdhflksadjflkdsahf".includes(searchQueryStrippedQuotes)) {
      results.push("match");
   }
}

I get no error when using a short string for searchQueryStrippedQuotes, even there is a large number of results to parse through (bump 1,000 here to 30,000, for instance). However, with a long string (more than 6 or 7 words), I get the error.

JavaScript Query Google Sheets API To Retrieve All Sheets

I have the following code to query a single sheet (Sheet1) from a google sheet document. Haven’t been able to find any documentation on how to query all sheets from the file

const GoogleSpreadsheet = require('google-spreadsheet');
const { google } = require("googleapis");
const spreadsheetId = '123456';

const auth = new google.auth.GoogleAuth({
    keyFile: "credentials/sheets_token.json",
    scopes: "https://www.googleapis.com/auth/spreadsheets",
});


const client = await auth.getClient();
const googleSheets = google.sheets({ version: "v4", auth: client });

const res = await googleSheets.spreadsheets.values.get({
    auth,
    spreadsheetId: spreadsheetId,
    range: 'Sheet1'
});

Tried using empty range, or excluding range parameter, or using range “Sheet1:Sheet10” none worked. Also tried fetching all sheets from the metadata, but you can only get various sheets’ titles not their rows data

How to activate bootstrap dropdown menu item by pressing keyboard key

Bootstrap 5 navbar contains dropdown menus.
Dropdown menus have underlined hotkeys like a,n,s,e :

<div class="btn-group">
  <button type="button" class="btn btn-danger dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
    Action
  </button>
  <ul class="dropdown-menu">
    <li><a class="dropdown-item" href="#"><u>A</u>ction</a></li>
    <li><a class="dropdown-item" href="#">A<u>n</u>other action</a></li>
    <li><a class="dropdown-item" href="#"><u>S</u>omething else here</a></li>
    <li><hr class="dropdown-divider"></li>
    <li><a class="dropdown-item" href="#">S<u>e</u>parated link</a></li>
  </ul>
</div>

How to activate menu item if key is pressed in keyboard? For example, if dropdowns menu is open, pressing A should act like Action menu item is clicked.

jsfiddle: https://jsfiddle.net/b6or2s5e/

Left and right arrows are already handled using

How to use left and right arrow keys to navigate in bootstrap navbar

document.addEventListener("DOMContentLoaded", function () {
  document.querySelectorAll('.dropdown').forEach(function (el) {
    el.addEventListener('shown.bs.dropdown', function () {
      document.addEventListener('keydown', function (e) {
        const click = new MouseEvent("click", {
          bubbles: true,
          cancelable: true,
          view: window,
        })
        if (e.key === "ArrowRight") {
          const o = getNextSibling(e.target.closest('.dropdown'), '.dropdown')
          if (!o) {
            document.querySelector('.dropdown-toggle').dispatchEvent(click)
          } else {
            o.querySelector('.Xdropdown-toggle').dispatchEvent(click)
          }
        } else if (e.key === "ArrowLeft") {
          const o = getPrevSibling(e.target.closest('.dropdown'), '.dropdown')
          if (!o) {
            const ar = document.querySelectorAll('.dropdown-toggle')
            ar[ar.length - 1].dispatchEvent(click)
          } else {
            o.querySelector('.dropdown-toggle').dispatchEvent(click)
          }
        }
      }, { once: true })
    })
  })
})

How to add hotkey handling also?

antibotbrowser / puppeteer + change IP by Tor

I’m currently working on a Puppeteer-based script where I want to use Tor to rotate IP addresses dynamically. The code works when I manually set up Tor for simple Puppeteer instances, but I’m having issues integrating it into my full program, which includes puppeteer-extra, puppeteer-extra-plugin-stealth, and antibotbrowser.

My goal is to automatically switch IP addresses using Tor or another proxy service every time a new page is loaded, or after a specific task is completed (like processing a set of links). I’ve implemented a function that randomly selects a Tor port and sets the proxy server for Puppeteer, but the IP address does not seem to change as expected in the context of the full program.

Here’s the relevant portion of my code:

const antibotbrowser = require("antibotbrowser");
const puppeteer = require('puppeteer-extra');
const puppeteerExtraPluginStealth = require('puppeteer-extra-plugin-stealth');
const ac = require('@antiadmin/anticaptchaofficial');...

ac.setAPIKey('afdfdbdf89489fbd4bfd');
const ipLogFile = 'ip_log.txt';
 
async function switchTorCircuit() {
  
  const socksPorts = [9050, 9052, 9053, 9054];
  
  const socksPort = socksPorts[Math.floor(Math.random() * socksPorts.length)];  
  return `socks5://127.0.0.1:${socksPort}`;
}

async function createBrowserWithTorAndAntibot() {  
  
  const proxyServer = await switchTorCircuit();
  
  puppeteer.use(puppeteerExtraPluginStealth());
  const antibrowser = await antibotbrowser.startbrowser();

  const browser = await puppeteer.connect({
    browserWSEndpoint: antibrowser.websokcet,
    args: [
      `--proxy-server=${proxyServer}`,  // Use the selected SOCKS proxy
      '--disable-features=site-per-process',
      '--no-sandbox',
      '--disable-setuid-sandbox',
    ],
    headless: false,
  });

  const page = await browser.newPage();

   // check ip ...
  
  return { browser, page };
}


(async () => {  
  const { browser, page } = await createBrowserWithTorAndAntibot();   

  await page.goto('https://www.xxx');  
  await processPage(page);
...
})();

torrc:
`
SocksPort 9050
SocksPort 9052
SocksPort 9053
SocksPort 9054

MaxCircuitDirtiness 10
NewCircuitPeriod 15

ControlPort 9051
CookieAuthentication 1`

Now I can’t change IP at all.

The API key doesn’t fit 🙂

javascript: can not set cookies with some names

javascript: can not set cookies with some names:

Chrome devtool console

> document.cookie
  (empty)

> document.cookie='clientDeviceId=123'
  (no error, but cookie was not added)

> document.cookie
   (empty)

> document.cookie='clientDeviceId2=123'
  (cookie added successfully)

> document.cookie
  'clientDeviceId2=123'

Is “clientDeviceId” a reserved name?

Same for clientSecretKey. Renaming it to
clientSecretKey2 works.

Player score remains zero in rock, paper, scissors

I have this implementation of rock, paper, scissors, where I use buttons with images for the user to indicate their choice.

But the player score won’t go up — it remains 0, no matter what. The computer score works just fine. I only have trouble with getting the player score right. What am I doing wrong?

let result;
let playerScore = 0;
let computerScore = 0;
let playerSelection;
const buttonBox = document.querySelector(".selections");
const buttons = document.querySelectorAll('button');
const roundsBox = document.querySelector(".rounds");
const selection = ["ROCK", "PAPER", "SCISSORS"];
const pScore = document.querySelector("#playerScore");
const cScore = document.querySelector("#compScore");

buttons.forEach((button) => {
  button.addEventListener('click', () => {
    playerSelection = selection.data-selection;
    playRound(computerSelection());
    game();
  });
});

const computerSelection = function () {
  return selection[Math.floor(Math.random() * 3)];
};

function playRound(computerSelection) {
  const h1 = document.createElement("h1");
  const oneRound = document.createElement("div");
  oneRound.classList.add("oneRound");
  if (playerSelection == computerSelection) {
    h1.textContent = "DRAW";
  } else if (playerSelection == "ROCK" && computerSelection == "SCISSORS") {
    h1.textContent = "WIN";
    playerScore += 1;
  } else if (playerSelection == "PAPER" && computerSelection == "ROCK") {
    h1.textContent = "WIN";
    playerScore += 1;
  } else if (playerSelection == "SCISSORS" && computerSelection == "PAPER") {
    h1.textContent = "WIN";
    playerScore += 1;
  } else {
    h1.textContent = "LOSE";
    computerScore += 1;
  }
  
  pScore.textContent = playerScore;
  cScore.textContent = computerScore;
}

function game() {
  const finalResult = document.createElement("div");
  finalResult.classList.add("rounds");
  if (playerScore != 5 && computerScore != 5) {
    return
  } else if (playerScore == 5) {
    finalResult.textContent = "YOU WON! :D";
  } else if (computerScore == 5) {
    finalResult.textContent = "YOU LOST! :(";
  }
  roundsBox.prepend(finalResult);
  buttonBox.replaceWith(finalResult);
}
<div class='selections'>
    <button class='selection' data-selection='rock'> <img alt="rock" src='images/rock.png'> </button>
    <button class='selection' data-selection='paper'> <img alt="paper"  src='images/paper.png'> </button>
    <button class='selection' data-selection='scissors'> <img alt="scissors"  src='images/scissors.png'> </button>
</div>
<div class='results'>
    <div>
        <pre><h1>Player <span id="playerScore">0</span> - <span id="compScore">0</span> Computer</h1></pre>
        <div class="rounds">First to 5 wins!</div>
    </div>
</div>

Using RTK Query with a store that contains parent keys

I work for a large company that has an in-house framework that’s built in React. We import the framework and build our application on top of it. They generate the Redux store on their end, and combine reducers that we send them in a specific file. Once the store is generated, it looks like:

{
  stuff: {
           myReducer:{}
         },
  moreStuff: {},
  theirStuff: {}
}

I was trying to use RTK Query for an API we are building, but it’s putting the reducer for the query under the ‘stuff’ key, and this is causing the query to persist in the pending state. After all my testing, it seems that RTK Query doesn’t work when the reducers are a child in the store? Is there an option to handle this?

I commented everything out and created store locally in our code, and the queries worked just fine. Unfortunately, in order to use their components, we have to use their generated store.

Async/Await not working correctly for custom version of Promise.allSettled in NodeJs

I am working on custom implementation of Promise.allSettled in NodeJs. When I implement using Promise.then it works perfectly. But when I implement using Async/Await it throw the error.

[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason “Failed”.] {
code: ‘ERR_UNHANDLED_REJECTION’
}.

function myCustomAllSettled2(promises){
    return new Promise(async (resolve, reject) => {
        try{
            let completedCount = 0
            let results = []
            for(let i=0; i<promises.length; i++){
                try{
                    let result = await promises[i]
                    results[i] = {"status": "fulfilled", "value": result}
                }
                catch(ex){
                    results[i] = {"status": "rejected", "reason": ex.message || ex}
                }
                finally{
                    completedCount += 1
                    if(completedCount === promises.length){
                        resolve(results)
                    }
                }
            }  
        }
        catch(ex){
            reject(ex)
        }    
    })
};

function myCustomAllSettled(promises){
    return new Promise((resolve, reject) => {
        let completedCount = 0
        let results = []
        for(let i=0; i<promises.length; i++){
            promises[i].then(result => {
                results[i] = {"status": "fulfilled", "value": result}
            }).catch(ex => {
                results[i] = {"status": "rejected", "reason": ex.message || ex}
            }).finally(() => {
                completedCount += 1
                if(completedCount === promises.length){
                    resolve(results)
                }
            })
        }        
    })
};

(async()=>{
    try{
        let s = new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve('Success')
            }, 400)
        })
        
        let f = new Promise((resolve, reject) => {
            setTimeout(() => {
                reject('Failed')
            }, 300)
        })

        let promises = [s,f]
        //This works well
        myCustomAllSettled(promises).then(results => {
            results.forEach(result => {
                if(result.status === 'fulfilled'){
                    console.log('Success : ' , result.value)
                }
                else{
                    console.log('Failed : ' , result.reason)
                }
            });
        })

        let s2 = new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve('Success')
            }, 400)
        })
        
        let f2 = new Promise((resolve, reject) => {
            setTimeout(() => {
                reject('Failed')
            }, 300)
        })
        let promises2 = [s2,f2]
        //This throws error
        let results = await myCustomAllSettled2(promises2)
        results.forEach(result => {
            if(result.status === 'fulfilled'){
                console.log('Success : ' , result.value)
            }
            else{
                console.log('Failed : ' , result.reason)
            }
        });
    }
    catch(ex){
        console.log(ex)
    }
})();

I tried implementing using Promise.then and it worked. But When I try to implement using async/await it throws error.

Replacing a deleted Landsat 5 dataset in Google Earth Engine ‘LANDSAT/LT05/C01/T1’ for 2012 NDVI calculation

I’m trying to calculate NDVI for 2012 within my study area in GEE. I believe the best available quality is Landsat 5, and when I’m trying to filter the Image Collection with this function:
“var landsatCollection = ee.ImageCollection(‘LANDSAT/LT05/C01/T1’)”, a notification pops up that it’s a deleted Landsat dataset.
This is my entire code:

// Filter the image collection based on region and date range
var Filtered_Region = ImageCollection.filterBounds(Region);
var startDate = '2012-04-01';
var endDate = '2012-05-15';

// Function to calculate NDVI for Landsat 5 images
function calculateNDVI(image) {
  var ndvi = image.normalizedDifference(['B4', 'B3']).rename('NDVI'); // B4: NIR, B3: Red
  return image.addBands(ndvi);
}

// Filter Landsat 5 image collection for the given date range and region
var landsatCollection = ee.ImageCollection('LANDSAT/LT05/C02/T1')
  .filterBounds(Region)
  .filterDate(startDate, endDate)
  .map(calculateNDVI);

// Get the median NDVI image over the date range
var medianNDVI = landsatCollection.select('NDVI').median();

// Define visualization parameters
var visParams = {
  min: -1,
  max: 1,
  palette: ['blue', 'white', 'green']
};

// Add the NDVI layer to the map with a custom name
Map.addLayer(medianNDVI, visParams, 'NDVI 2012');

// Print the NDVI image to the console for additional information
print('Median NDVI Image:', medianNDVI);

I’ve tried changing it to ‘LANDSAT/LT05/C02/T1_L2’ or ‘LANDSAT/LT05/C02/T1’, but these appear not to be working (the layer has no bands to visualise).

Is there a reason I can’t collect data from my nested React form

I am working on a NextKs app, currently working on a component that has a form. Some of the key/value pair on the form are nested (please see the code below). I was under the impression that I can traverse down element on the form, but somehow getting errors

import React from "react";

const Rafce = () => {
  const [formData, setFormData] = useState({
    title: "",
    objectives: "",
    demographic: {
      geographic: {
        country: "",
        state: "",
        city: "",
      },
      target: "",
      gender: "",
      age: "",
      intention: "",
    },
    campaignReason: "",
    strategy: "",
  });


  const items = [
    "Item 1",
    "Item 2",
    "Item 3",
    "Item 4",
    
  ];

  const profession = ["Yes|No", "Yes", "No"];

  //Handling Country selection
  const [countries, setCountries] = useState([]);
  const [states, setStates] = useState([]);
  const [cities, setCities] = useState([]);

  const [selectedCountry, setSelectedCountry] = useState("");
  const [selectedState, setSelectedState] = useState("");
  const [selectedCity, setSelectedCity] = useState("");

  useEffect(() => {
    setCountries(Country.getAllCountries());
  }, []);

  useEffect(() => {
    if (selectedCountry) {
      setStates(State.getStatesOfCountry(selectedCountry));
      setCities([]); // Reset cities when country changes
    }
  }, [selectedCountry]);

  useEffect(() => {
    if (selectedState) {
      setCities(City.getCitiesOfState(selectedCountry, selectedState));
    }
  }, [selectedState, selectedCountry]);

  const handleCountryChange = (event) => {
    setSelectedCountry(event.target.value);
    setSelectedState("");
    setSelectedCity("");
  };

  const handleStateChange = (event) => {
    setSelectedState(event.target.value);
    setSelectedCity("");
  };

  const handleCityChange = (event) => {
    setSelectedCity(event.target.value);
  };

  const handleChange = (event) => {
    const { name, value } = event.target;
    setFormData({
      ...formData,
      [name]: value,
    });
  };


  return (<div>
  <form onSubmit={handleSubmit}>
      <div className="space-y-12">
        <div className="grid grid-cols-1 gap-x-8 gap-y-10 border-b border-gray-900/10 pb-12 md:grid-cols-3">
          <div>
            <h2 className="text-base font-semibold leading-7 text-gray-900">
              Some Name
            </h2>
          </div>

          <div className="grid max-w-2xl grid-cols-1 gap-x-6 gap-y-8 sm:grid-cols-6 md:col-span-2">
            <div className="col-span-full">
              <label
                htmlFor="title"
                className="block text-sm font-medium leading-6 text-gray-900"
              >
               Company Title
              </label>
              <div className="mt-2">
                <div className="flex rounded-md shadow-sm ring-1 ring-inset ring-gray-300 focus-within:ring-2 focus-within:ring-inset focus-within:ring-red-600 sm:max-w-md">
                  <input
                    type="text"
                    name="title"
                    id="title"
                    value={formData.title}
                    onChange={handleChange}
                    className="block flex-1 w-full border-0 bg-transparent py-1.5 pl-1 text-gray-900 placeholder:text-gray-400 focus:ring-0 sm:text-sm sm:leading-6"
                    placeholder="Your organization name"
                  />
                </div>
              </div>
            </div>
            
            <div className="relative inline-block text-left z-50 col-span-full">
              <select
                value={selectedItem}
                onChange={(e) => setSelectedItem(e.target.value)}
              >
                <option value="Select Type" disabled>
                  Select  Type
                </option>
                {items.map((item, index) => (
                  <option key={index} value={item}>
                    {item}
                  </option>
                ))}
              </select>
            </div>
            <div className="col-span-full">
              <label
                htmlFor="objectives"
                className="block text-sm font-medium leading-6 text-gray-900"
              >
                Objectives
              </label>
              <div className="mt-2">
                <textarea
                  id="objectives"
                  name="objectives"
                  value={formData.objectives}
                  onChange={handleChange}
                  rows={3}
                  className="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-red-600 sm:text-sm sm:leading-6"
                  defaultValue={""}
                  placeholder="What are the specific goals of the campaign beyond just raising funds? (e.g., increasing awareness, engaging new donors)"
                />
              </div>
            </div>
            <div className="col-span-full">
              <label
                htmlFor="features"
                className="block text-sm font-medium leading-6 text-gray-900"
              >
                Defining demographics
              </label>
              <div className="mt-2">
                <div className="isolate -space-y-px rounded-md shadow-sm">
                  <div className="relative rounded-md rounded-t-none px-3 pb-1.5 pt-2.5 ring-1 ring-inset ring-gray-300 focus-within:z-10 focus-within:ring-2 focus-within:ring-red-600">
                    <label
                      htmlFor="feature02"
                      className="block text-xs font-medium text-gray-900"
                    >
                      Geographic location
                    </label>
                    <div className="mb-3">
                      <label
                        className="block text-xs font-medium text-gray-900"
                        htmlFor="country"
                      >
                        Country:{" "}
                      </label>
                      <select
                        id="country"
                        value={selectedCountry}
                        onChange={handleCountryChange}
                      >
                        <option
                          className="block text-xs font-medium text-gray-900"
                          value=""
                        >
                          Select Country
                        </option>
                        {countries.map((country) => (
                          <option key={country.isoCode} value={country.isoCode}>
                            {country.name}
                          </option>
                        ))}
                      </select>
                    </div>

                    {states.length > 0 && (
                      <div className="mb-3">
                        <label
                          className="block text-xs font-medium text-gray-900"
                          htmlFor="state"
                        >
                          State:{" "}
                        </label>
                        <select
                          id="state"
                          value={selectedState}
                          onChange={handleStateChange}
                        >
                          <option
                            className="block text-xs font-medium text-gray-900"
                            value=""
                          >
                            Select State/Region
                          </option>
                          {states.map((state) => (
                            <option key={state.isoCode} value={state.isoCode}>
                              {state.name}
                            </option>
                          ))}
                        </select>
                      </div>
                    )}
                    {cities.length > 0 && (
                      <div className="mb-3">
                        <label
                          className="block text-xs font-medium text-gray-900"
                          htmlFor="city"
                        >
                          City:{" "}
                        </label>
                        <select
                          id="city"
                          value={selectedCity}
                          onChange={handleCityChange}
                        >
                          <option
                            className="block text-xs font-medium text-gray-900"
                            value=""
                          >
                            Select City
                          </option>
                          {cities.map((city) => (
                            <option key={city.name} value={city.name}>
                              {city.name}
                            </option>
                          ))}
                        </select>
                      </div>
                    )}
                  </div>
                  <div className="relative rounded-md rounded-t-none px-3 pb-1.5 pt-2.5 ring-1 ring-inset ring-gray-300 focus-within:z-10 focus-within:ring-2 focus-within:ring-red-600">
                    <label
                      htmlFor="target"
                      className="block text-xs font-medium text-gray-900"
                    >
                      Target
                    </label>
                    <input
                      type="text"
                      name="target"
                      id="target"
                      value={formData.demographic.target}
                      onChange={handleChange}
                      className="block w-full border-0 p-0 text-gray-900 placeholder:text-gray-400 focus:ring-0 sm:text-sm sm:leading-6"
                      placeholder="e.g: Gen Z, Baby Boomers, Gen X"
                    />
                  </div>
                  <div className="relative rounded-md rounded-t-none px-3 pb-1.5 pt-2.5 ring-1 ring-inset ring-gray-300 focus-within:z-10 focus-within:ring-2 focus-within:ring-red-600">
                    <label
                      htmlFor="gender"
                      className="block text-xs font-medium text-gray-900"
                    >
                      Gender
                    </label>
                    <input
                      type="text"
                      name="gender"
                      id="gender"
                      value={formData.demographic.gender}
                      onChange={handleChange}
                      className="block w-full border-0 p-0 text-gray-900 placeholder:text-gray-400 focus:ring-0 sm:text-sm sm:leading-6"
                      placeholder="E.g: 'Male' or 'Female' "
                    />
                  </div>
                  <div className="relative rounded-md rounded-t-none px-3 pb-1.5 pt-2.5 ring-1 ring-inset ring-gray-300 focus-within:z-10 focus-within:ring-2 focus-within:ring-red-600">
                    <label
                      htmlFor="age"
                      className="block text-xs font-medium text-gray-900"
                    >
                      Age
                    </label>
                    <input
                      type="text"
                      name="age"
                      id="age"
                      value={formData.demographic.age}
                      onChange={handleChange}
                      className="block w-full border-0 p-0 text-gray-900 placeholder:text-gray-400 focus:ring-0 sm:text-sm sm:leading-6"
                      placeholder="e.g: 20-64"
                    />
                  </div>
                  <div className="relative rounded-md rounded-b-none px-3 pb-1.5 pt-2.5 ring-1 ring-inset ring-gray-300 focus-within:z-10 focus-within:ring-2 focus-within:ring-red-600">
                    <label
                      htmlFor="intention"
                      className="block text-xs font-medium text-gray-900"
                    >
                     Intention
                    </label>
                    <input
                      type="text"
                      name="intention"
                      value={formData.demographic.intention}
                      onChange={handleChange}
                      id="intention"
                      className="block w-full border-0 p-0 text-gray-900 placeholder:text-gray-400 focus:ring-0 sm:text-sm sm:leading-6"
                      placeholder="e.g: Events"
                    />
                  </div>
                </div>
              </div>
            </div>
            <div className="col-span-full">
              <label
                htmlFor="features"
                className="block text-sm font-medium leading-6 text-gray-900"
              >
                Strategy
              </label>
              <div className="mt-2">
                <div className="isolate -space-y-px rounded-md shadow-sm">
                  <div className="relative rounded-md rounded-b-none px-3 pb-1.5 pt-2.5 ring-1 ring-inset ring-gray-300 focus-within:z-10 focus-within:ring-2 focus-within:ring-red-600">
                    <label
                      htmlFor="feature01"
                      className="block text-xs font-medium text-gray-900"
                    >
                      What strategies have you tried
                    </label>
                    <div className="flex justify-between">
                      <Select
                        label=""
                        placeholder="Click to Select (multiple if needed)"
                        selectionMode="multiple"
                        className="bg-white"
                      >
                        {strategies.map((selection) => (
                          <SelectItem className="bg-white" key={selection.key}>
                            {selection.label}
                          </SelectItem>
                        ))}
                      </Select>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div className="mt-6 flex items-center justify-end gap-x-6">
        <button
          type="submit"
          className="rounded-md bg-green-600 px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-green-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-green-600"
        >
          Save and Continue
        </button>
      </div>
    </form>
  </div>);
};

export default Rafce;

The issue is that nested elements (e.g: demographic) are not showing in the UI – As if I never set the event target value. Also, the Select bitton elements that are supposed to be a simple Yes/No aren’t showing

Upload an Excel file or CSV file, so that the data can be appended

I used ChatGPT to help me write some scripts. Basically I would like to add a function in Google sheet, so that the user can upload an excel file or CSV file, so that the data of the excel file can be appended to current Google sheet. Here is what ChatGPT give me, but no matter how many times I have tried, the Excel data cannot be added… I have tried many different ways to debug but still doesn’t work:

Here is what in the Code.gs:

function onOpen() {
  var ui = SpreadsheetApp.getUi();
  ui.createMenu('Custom Menu')
    .addItem('Upload Excel File', 'openSidebar')
    .addToUi();
}

function openSidebar() {
  var html = HtmlService.createHtmlOutputFromFile('UploadSidebar')
      .setTitle('Upload Excel File');
  SpreadsheetApp.getUi().showSidebar(html);
}

function uploadExcel(data) {
  try {
    Logger.log('Starting uploadExcel function');
    if (data) {
      Logger.log('Data received, length: ' + data.length);
      var bytes = Utilities.base64Decode(data);
      Logger.log('Data decoded, byte length: ' + bytes.length);
      var blob = Utilities.newBlob(bytes, 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'upload.xlsx');
      Logger.log('Blob created, blob size: ' + blob.getBytes().length);
      
      var file = DriveApp.createFile(blob);
      Logger.log('File created with ID: ' + file.getId());

      var fileId = file.getId();
      var sheetName = 'WB Accrual Data';
      var excelData = ExcelToCsv(fileId);
      Logger.log('Excel data converted to CSV format');

      var csvData = Utilities.parseCsv(excelData);
      Logger.log('CSV Data parsed: ' + JSON.stringify(csvData));

      var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
      if (sheet) {
        var lastRow = sheet.getLastRow();
        Logger.log('Last row in the sheet: ' + lastRow);
        sheet.getRange(lastRow + 1, 1, csvData.length, csvData[0].length).setValues(csvData);
        Logger.log('Data appended successfully.');
      } else {
        Logger.log('Sheet not found: ' + sheetName);
      }

      file.setTrashed(true); // Optional: Delete the file from Drive after importing
      Logger.log('File trashed');
    } else {
      Logger.log('Error: Data is null or undefined');
    }
  } catch (e) {
    Logger.log('Error: ' + e.toString());
  }
}

function ExcelToCsv(fileId) {
  var file = DriveApp.getFileById(fileId);
  var openSpreadsheet = SpreadsheetApp.open(file);
  var sheet = openSpreadsheet.getSheets()[0];
  var range = sheet.getDataRange();
  var values = range.getValues();
  var csv = "";
  for (var i = 0; i < values.length; i++) {
    csv += values[i].join(",") + "n";
  }
  Logger.log('CSV: ' + csv);
  return csv;
}

function testAppendData() {
  var testData = [
    ["A1", "B1", "C1"],
    ["A2", "B2", "C2"],
    ["A3", "B3", "C3"]
  ];
  var sheetName = 'WB Accrual Data';
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
  if (sheet) {
    var lastRow = sheet.getLastRow();
    sheet.getRange(lastRow + 1, 1, testData.length, testData[0].length).setValues(testData);
  } else {
    Logger.log('Sheet not found: ' + sheetName);
  }
}

Here is what in the UploadSidebar.html

<!DOCTYPE html>
<html>
<head>
  <base target="_top">
  <script>
    console.log('Sidebar loaded'); // Log to confirm the sidebar is loaded

    function handleFileSelect(evt) {
      console.log('handleFileSelect called'); // Log to confirm the function is called
      var file = evt.target.files[0];
      console.log('File selected: ' + file.name); // Log the file name to confirm file selection
      var reader = new FileReader();
      reader.onload = function(e) {
        var data = e.target.result.split(',')[1]; // Get the base64 part
        console.log('File read successfully, base64 length: ' + data.length); // Log the base64 length
        google.script.run.withSuccessHandler(onSuccess).uploadExcel(data);
      };
      reader.readAsDataURL(file);
    }

    function onSuccess() {
      document.getElementById('status').innerHTML = 'File uploaded and data appended successfully.';
    }
  </script>
</head>
<body>
  <h2>Upload Excel File</h2>
  <input type="file" id="fileInput" />
  <div id="status"></div>
  <script>
    document.getElementById('fileInput').addEventListener('change', handleFileSelect, false);
    console.log('Event listener added to file input'); // Log to confirm event listener is added
  </script>
</body>
</html>

Can anyone please help me?? I am not a software engineer so I have no idea what’s wrong

  1. ChatGPT told me to check Developer Tools console for the log, and I did. But nothing was showed up there.
  2. Also I ensured my JavaScripts has been enabled and allowed
  3. The function of testAppendData() was correctly added but it just cannot extract the data from excels uploaded

LlamaIndex Typescript to Javascript

How to convert LlamaIndex code written in typescript to javascript for use in a browser environment? I’m running into errors related to LlamaIndex imports.

I’m converting using “tsc filename.ts”. The file does get converted however, there are a lot of errors in the terminal related to LlamaIndex imports. This line of code throws errors if I try to use it in a browser environment:
Object.defineProperty(exports, “__esModule”, { value: true });
var llamaindex_1 = require(“llamaindex”);
How should I change my approach so that it works in a browser environment? Any help would be appreciated!

Process on SIGTERM callback is not triggered?

This is my code:

process.on('SIGTERM', () => {
  console.log('Got SIGTERM signal.')
})

process.kill(process.pid, 'SIGTERM')

Node: v20.16.0

OS: Windows 10

I executed the file by running node test.js. I expected to see Got SIGTERM signal logged to my console. However, there is nothing logged to my console. Can someone explain what I’m misunderstanding?

Forex broker website and tools to use using js and laravel php

I am building a forex broker website and I want to know the how to work on the trading page like this one here enter image description here

Someone told me that there’s a package to use and achieve it…. That it looks like a trading bot and it uses vue js or react or laravel livewire on the frontend and I can now use my laravel backend to store information that I got from the Page and trading history of the user.. The admin also want to control the candle sticks too and the platform wants to use crypto payment for deposit into the platform.. can someone help me on how to achieve this using JavaScript and php as my backend… It’s a forex broker website that people can come and trade forex and gain profits.
They also want users to be trading mt4 on the platform too
Thank you so much for the upcoming replies

I have made my research so far, but the tools I have seen that can trade mt4 it’s too costly and it’s not the best choice for me to use.

Content-Security-Policy: The page’s settings blocked the loading of a resource (font-src) at chrome-extension://*/static/assets/fonts/WorkSans-Black

Good afternoon, i have this problem when run my react app.
I recently added webpack to my project, I had no problems with it before, I tested in Chrome and firefox there were such errors everywhere, no extensions were installed, and it would seem that I disabled all the fonts in the style files that were in errors, but they did not disappear
i don’t use nginx or something like this, i’m tested it only on localhost.
include meta tag in public/index.html also doesn’t work.
front – react, back – node.js (express)

Erorr:
Content-Security-Policy: The page’s settings blocked the loading of a resource (font-src) at chrome-extension://**/static/assets/fonts/WorkSans-Black.ttf because it violates the following directive: “font-src ‘self’” localhost:8080