What is the recommended way to access the true first element of a JavaScript array?

Say I have an array initialized like this:

let a = [];
a[1000] = 1;

this will result in an array whose first 1,000 elements are undefined, and the true first element is the 1,001st (index 1,000). If I don’t know how many elements are undefined before the first one, how do I access the true first element?

I can interate through every element in an array and look for the first one that is not undefined, but this will give me O(n) time complexity. I would like to have an O(1) method.

After some messing around I found out I can use the for ... in syntax to do achieve this, and it seems to be O(1), as it seems to be reasonably fast even when the first index is extremely large (1e9):

let index, value;
for(idx in a) {
    index=idx;value=a;
    break;
}

But I have read that it is not recommended to use for ... in for iterating through arrays (as it can mess up other libraries). So what would be the recommended way to achieve what I’m trying to do? is for ... in the only way?

Why does page.name return undefined in InDesign UXP plugin?

I’m developing a UXP plugin for Adobe InDesign and trying to access the name of each page using page.name. However, when I run the following code, page.name consistently returns undefined, even though doc.pages.length is valid and returns the correct number of pages.

Here’s the relevant code snippet:

document.getElementById("collectTextFramesBtn")?.addEventListener("click", async () => {
  try {
    if (!app.documents || app.documents.length === 0) {
      console.warn("⚠️ No document is open.");
      return;
    }

    const doc = app.activeDocument;

    for (let i = 0; i < doc.pages.length; i++) {
      const page = doc.pages[i];
      console.log(`➡️ Iterating page ${i + 1}`);
      console.log("page.name:", page?.name); // returns undefined
      console.log("documentOffset:", page?.documentOffset); // works fine
    }

  } catch (err) {
    console.error("❌ Error accessing page data:", err);
  }
});

What might cause page.name to return undefined even though other properties like documentOffset or textFrames work properly?

I’ve tested on InDesign 19+ with UXP and confirmed that page itself is valid and not null.

Read the id attribute of a tag in SVG file with getElementById using PHP

I have an SVG file named rectangle.svg (UPDATED)

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" 
  "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="300" height="130" xmlns="http://www.w3.org/2000/svg">
  <rect id="myid" width="200" height="100" x="10" y="10" rx="20" ry="20" fill="blue" />
  <rect id="myid2" width="200" height="100" x="10" y="10" rx="20" ry="20" fill="blue" />
</svg>

I try to read rect id with the readid.php (UPDATED):

<?php
    $dom = new DOMDocument("1.0", "utf-8");
    $dom->load('rectangle.svg');
    if ($dom->validate()) {
        echo "This document is valid!n";
    }
    $div = $dom->getElementById('myid');
    echo 'Result: '.$div->getAttribute('id');
?>

Output of php readid.php is:

This document is valid!
Result:

Why does not read the id attribute?

I would like to read the attributes and values of

<rect id="myid" width="200" height="100" x="10" y="10" rx="20" ry="20" fill="blue" />

how to make a WordPress plugin that alters the http status of 404 pages to 200 and uses the current theme to display 404 pages output

I am working on a plugin that changes the response for 404 pages so it issues HTTP status 200 instead of 404.

I already have the status change working using code like this:

function HTTP404Template()
{
    return __DIR__.'/404_template.php';
}
    
add_filter( '404_template', 'HTTP404Template');

Then the 404_template.php has code like this:

<?php
    status_header('200');
    add_filter( 'wp_robots', 'wp_robots_no_robots' );
    get_header();
    get_footer();
?>

Although this works, it shows the current theme template defined by another plugin, but it does not show the 404 page of that theme?

How can I change the output of a 404 to make the HTTP status be 200 and still show the current theme 404 page?

How to make a custom WooCommerce product type behave like Variable Product with full variation UI?

I’m creating a custom WooCommerce product type called bookable_service that should behave exactly like the native variable product type.

What I’ve implemented:

  • Created a class WC_Product_Variable_Bookable_Service extending WC_Product_Variable
  • Overrode get_type() to return 'variable' in admin, and 'bookable_service' on frontend
  • Registered the type using product_type_selector and woocommerce_product_class
  • Enabled variation support with woocommerce_product_type_supports
  • Injected 'product-type-variable' class into the <body> via admin JavaScript

Problem:

Despite this, the WooCommerce admin UI does not:

  • Show the “Used for variations” checkbox
  • Show the Variations tab in Product Data
  • Allow variation pricing to be added

If I switch the product type to 'variable', everything works fine. But with 'bookable_service', WooCommerce seems to ignore variation logic in the admin.

What I need:

I want WooCommerce to treat bookable_service exactly like a variable product — with full variation UI — but allow me to keep a custom product type for conditional frontend logic.

Is there a clean way to fully replicate Variable Product behavior for a custom product type without overriding WooCommerce templates or JS?

I expected that by extending WC_Product_Variable and returning 'variable' in get_type() during admin, WooCommerce would treat my custom type as variation-compatible. But it seems the admin UI logic is tied to hardcoded type strings.

Looking for a WooCommerce-native way to support full variation functionality in a custom product type.

Why does Intl.NumberFormat round large numbers differently in Node.js vs browsers?

I’m observing inconsistent rounding behavior with Intl.NumberFormat` between Node.js (v20+) and modern browsers (Chrome/Firefox) for very large numbers.

Example:

const formatter = new Intl.NumberFormat('en-US', {
  maximumFractionDigits: 0
});
console.log(formatter.format(9999999999999999.5)); // Output differs!`

- Browser (Chrome 120+): Returns "10,000,000,000,000,000" (rounds up)
- Node.js (v20): Returns "9,999,999,999,999,999" (rounds down)

What I’ve tried:

Verified the spec (ECMA-402) but found no explicit guidance for this edge case.

Tested with different locales/options – same inconsistency.

Optional parent property in Alpine.js nested scope

In a scoped / nested Alpine.js structure, I need data from an outer x-data in an inner one.

This works:

<script src="https://unpkg.com/[email protected]/dist/cdn.min.js" defer></script>

<div x-data="{ foo: 'hello' }">
  <div x-data="{ get foo() { return foo } }">
    <span x-text="foo"></span>
  </div>
</div>

The property foo exists in the outer scope, so is usable in the inner one.

But in my use case, the outer scope is a page and the inner scope is a separate widget. Sometimes foo exists in the outer scope, sometimes not, and sometimes there is no outer scope.

So this doesn’t work:

<script src="https://unpkg.com/[email protected]/dist/cdn.min.js" defer></script>

<div>
  <div x-data="{ get foo() { return foo || 'world' } }">
    <span x-text="foo"></span>
  </div>
</div>

How do I make foo optional (and provide a default value)?

Please help me with the nestjs schedule

I am using the schedule of nestjs to process the cron so that it works every specific time.

However, even though the cron that was first created for testing has been removed, it continues to go back every 0 o’clock.

the cron that was made for the test is not confirmed even if the entire contents are searched.

The following is the code I wrote.

// app.module.ts

import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import ConfigModule from './config';
import { LoggingMiddleware } from './common/middleware/logging.middleware';
import { ScheduleModule } from '@nestjs/schedule';
import { BatchService } from './batch.service';

@Module({
  imports: [
    ConfigModule(),
    ScheduleModule.forRoot(),
  ],
  providers: [BatchService],
})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(LoggingMiddleware).forRoutes('*');
  }
}

Test batch.service.ts was used and deleted only when testing.

// TEST batch.service.ts
 
import { Injectable, Logger } from '@nestjs/common';
import { ClientAuthService } from './routes/client/auth/auth.service';
import { Cron, CronExpression, SchedulerRegistry } from '@nestjs/schedule';
import { PracticeService } from './routes/client/practice/practice.service';
import { EventService } from './routes/client/event/event.service';

@Injectable()
export class BatchService {
  constructor(
    private readonly eventService: EventService,
    private schedulerRegistry: SchedulerRegistry
  ) {}

  @Cron(CronExpression.EVERY_DAY_AT_MIDNIGHT)
  async handleAttendanceEvents() {
    await this.eventService.checkAttendanceByCron();
  }
}

The file below is the actual contents of your current operation.

// REAL batch.service.ts

import { Injectable, Logger } from '@nestjs/common';
import { Cron, CronExpression, SchedulerRegistry } from '@nestjs/schedule';
import { EventService } from './routes/client/event/event.service';

@Injectable()
export class BatchService {
  constructor(
    private readonly eventService: EventService,
  ) {}

  @Cron(CronExpression.EVERY_DAY_AT_MIDNIGHT, {
    name: 'attendance',
  })
  async handleAttendanceEvents() {
    await this.eventService.checkAttendanceByCron();
  }
}

When viewed from getCronJobs, the following logs are displayed.

[Nest] 646445  - 05/11/2025, 00:00:00 PM LOG job: attendance -> next: Mon May 12 2025 00:00:00

From above, like the relevant log content, only one is searched and two are not. However, in reality, two are running. Seeking help on how to delete previously incorrectly written cron.

Have a good day.

Require.js fails to load data-main script (looks into wrong place)

Requirejs library fails to load script defined in data-main attribute for require.js script. According to browser output it looks into wrong place. Can’t sort it out why and how to fix it. Created dumbest way to reproduce it.

I have 3 files (in the root folder):

/dummy.html
/js/dummy-requirejs-config.js
/js/page/dummy-instance.js

Content of dummy.html:

<!DOCTYPE html>
<html lang="en">
    <body>
        <p>Hello World</p>
        <script data-main="/js/page/dummy-instance" src="https://requirejs.org/docs/release/2.3.7/comments/require.js"></script>
        <script src="js/dummy-requirejs-config.js"></script>
    </body>
</html>

Content of dummy-requirejs-config.js file:

require.config({
    baseUrl: 'js'
});

Content of dummy-instance.js file:

define({
    a: "a",
    b: "b"
});

My expectation was: page loads without any error. But it loads with error, browser console output is:

require.js:1962 
           GET http://localhost:8000/js/dummy-instance.js net::ERR_ABORTED 404 (Not Found)
req.load @ require.js:1962
load @ require.js:1686
load @ require.js:835
fetch @ require.js:825
check @ require.js:857
enable @ require.js:1177
enable @ require.js:1558
(anonymous) @ require.js:1162
(anonymous) @ require.js:135
each @ require.js:60
enable @ require.js:1114
init @ require.js:789
(anonymous) @ require.js:1461
setTimeout
req.nextTick @ require.js:1816
localRequire @ require.js:1450
configure @ require.js:1388
requirejs @ require.js:1795
(anonymous) @ require.js:2145
(anonymous) @ require.js:2146Understand this error
dummy.html:1 Refused to execute script from 'http://localhost:8000/js/dummy-instance.js' because its MIME type ('application/json') is not executable, and strict MIME type checking is enabled.Understand this error
require.js:169 Uncaught Error: Script error for "dummy-instance"
https://requirejs.org/docs/errors.html#scripterror
    at makeError (require.js:169:17)
    at HTMLScriptElement.onScriptError (require.js:1739:36)

Note that url it is looking for does not contain /page part anymore (sorry for trace ai was asking for).

How to place text over multiple images over a grid form

I’m trying to have my hidden description show over each imageContainer it’s connected to. However no matter which one I point to the description shows somewhere else on the page. Furthermore, I must have messed something up with the loop.Do I need an extra div somewhere? Some images have 2 descriptions that show up when you hover over them instead of 1, and some you get nothing.

document.addEventListener('DOMContentLoaded',function () {
  const images=document.querySelectorAll('.imageContainer')
  const descriptions=document.querySelectorAll('.hidden');
  images.forEach((image, index) => {
    image.addEventListener('mouseover', () => {
        descriptions[index].style.display = 'block';
    });

    image.addEventListener('mouseout', () => {
        descriptions[index].style.display = 'none';
    });
});
});
.imageContainer{
    position: relative;
    display: inline-block;
    width: 100%;
}
.imageContainer:hover ~ .hidden{
    position: absolute;
    
    transform: translate(-50%, -50%);
    z-index: auto;
    color: white;
    background: rgba(65, 64, 64, 0.51);
}
 <div class="container justify-content-evenly">
    <div class="row">
      <div class="imageContainer col-md-6">
        <img
          src="images/Mermaid.png"
          class="img-fluid"
          alt="mermaid"
          id="page1-img"
        />
      </div>
    <div class="hidden description col-md-6 mb-5">
      <div class="appTitle text-start text-decoration-underline" id="app-title">
        Mermaid Page
      </div>
      <p class="text-start p-0">
        Now this was the first webpage I ever created. It might not be
        responsive, but I find beauty in it's simplicity. It has
        significant amount of CSS, very little Javasript, and the
        information I used is linked to it's orginal source. It honestly
        made me want to learn more about coding.
      </p>
      <a
        class="btn btn-dark text-start text-start border border-white p-3"
        href="https://my-first-site-jj.netlify.app/"
        target="_blank"
        role="button"
        id="launch-app"
        title="Learn about Memaids"
        >Launch App</a
      >
    </div>
        <div class="hidden description col-md-6 mb-5">
          <div class="appTitle text-start text-decoration-underline" id="app-title">
            World Clock App
          </div>
          <p class="description  text-start p-0">
            Check what the time is not only in your area, but in the listed
            countries. I implemented moment_timezone and Javascript to give
            you the different timezone you see here. Hope you check it out and
            enjoy.
          </p>
          <br />
          <a
            class="btn btn-dark text-start text-start border border-white mb-5 p-3"
            href="https://world-clock-jordanka.netlify.app/"
            target="_blank"
            title="Check The Time"
            role="button"
            id="launch-app"
            >Launch App</a
          >
        </div>
        <div class="imageContainer col-md-6">
          <img
            src="images/clock.PNG"
            alt="clock app"
            class="img-fluid"
            id="page1-img"
          />
        </div>

          <div class="imageContainer col-md-6">
            <img
              src="images/Weather_App.png"
              alt="weather app"
              class="img-fluid"
              id="page1-img"
            />
          </div>
          <div class="hidden description col-md-6 mb-5">
            <div class="appTitle text-start text-decoration-underline" id="app-title">
              Weather App
            </div>
            <p class="description text-start p-0">
              Do you want to know your 5 day forecast? What about in any city
              in the world? Just type a city in the search engine and see the
              results. This app was made with React and to get this
              information I utilized Shecodes Weather API and my own APIkey.
            </p>
            <br />
            <a
              class="btn btn-dark text-start text-start border border-white p-3"
              href="https://jj-weather-react.netlify.app/"
              target="_blank"
              title="Check Your Weather"
              role="button"
              id="launch-app"
              >Launch App</a
            >
          </div>

          
          <div class="hidden description col-md-6 mb-5">
            <div class="appTitle text-start text-decoration-underline" id="app-title">
              Dictionary App
            </div>
            <p class="description  text-start p-0">
              Look up anyword you want, with an old-timey feel, and possiblily have some images for examples. I incorporated two different api keys for this project. I connected the pexel api to the dictionary api so the images would match the researched word. 

            </p>
            <a
              class="btn btn-dark text-start text-start border border-white p-3"
             href="https://jj-dictionary-app.netlify.app" 
              target="_blank"
              role="button"
              id="launch-app"
              title="look up words with my Dictionary"
              >Launch App</a
            >
          </div>
          <div class="imageContainer col-md-6">
            <img
              src="images/Dictionay.png"
              alt="Dictionay app"
              class="img-thumbnail"
              id="page1-img"
            />
          </div>

          <div class="imageContainer col-md-6">
            <img
              src="images/Marc-landing.png"
              alt="landing page about Marc Anthony"
              class="img-thumbnail"
              id="page1-img"
            />
          </div>
          <div class="hidden description col-md-6 mb-5">
            <div class="appTitle text-start text-decoration-underline" id="app-title">
              Marc Anthony Landing Page
            </div>
            <p class="description text-start p-0">
              Do you love Marc Anthony music as much as I do? Or do you simply want to open your ears and mind to some salsa music? Then who better to listen to than the man who's known as the king of Salsa. Click on the launch app to have a listen
            </p>
            <a
              class="btn btn-dark text-start text-start border border-white p-3"
             href="http://jj-marcanthony-project.netlify.app"
              target="_blank"
              role="button"
              id="launch-app"
              title="Learn about Marc Anthony"
              >Launch App</a
            >
          </div>
      
          <div class="hidden description col-md-6 mb-5">
            <div class="appTitle text-start text-decoration-underline" id="app-title">
              AI Italian Recipe
            </div>
            <p class="description text-start p-0">
              Ever wanted to make an Italian dish but didn't know where to start? Well take out the guess work and utilize my AI generated Italian Recipe app. Where you can simply type lasagna and it give you a delicious recipe within a minute.
            </p>
            <a
              class="btn btn-dark text-start text-start border border-white p-3"
             href="https://italian-food-generator.netlify.app" 
              target="_blank"
              role="button"
              id="launch-app"
              title="Use AI to get a new Italian recipe"
              >Launch App</a
            >
          </div>
          <div class="imageContainer col-md-6">
              <img
                src="images/AIrecipe.png"
                alt="italian recipe generator"
                class="img-thumbnail"
                id="page1-imgr"
              />
            </a>
            </div>
        </div>

Sidebar toggle not working on small screen

I have a div in an html like below:

<div id="sidebar" class="mainsidebar">

And a button on a different div on same html like this:

<button type="button" id="sidebarCollapse" class="navbar-btn">

And javascript goes like (no jQuery, all vanilla):

document.getElementById("sidebarCollapse").addEventListener('click',
    function() {
        document.getElementById("sidebar").classList.toggle("active");
        this.classList.toggle("active");
    });

Clicking sidebarCollapse button works as expected on full (large) screen. i.e. the sidebar toggles fine.

Situation: On small screen mode, the sidebar goes away expected but it never comes back by clicking sidebarCollapse button. In “inspect” mode I can clearly see the js function works. That means it toggles active class to sidebar just fine but for some reason the sidebar never appears.

What might be missing?

I have tried pretty much everything and now giving up. Any pointers will be helpful. I can provide all the info if anyone needs. For this purpose, I have put the whole thing here on github too. It has full html css and js.

How to Access Values Outside of the Scope of an Event Listener

I have an event listener tied to a button on the form to get the player’s names. I can access the player’s name inside the event listener, but have no way of pulling it out to create a new Player.

Surely, we are not supposed to write the rest of the program inside the event listener just so we can access these values right?

    let player1 = new Player();
    let player2 = new Player();

    let win;
    let whoWon;

    // Hide the play again button
    playAgain.classList.add('hidden');

    // Get the players
    subBtn.addEventListener('click', (e) => {
        e.preventDefault();

        // Generate a random token for player1
        let p1Token = generateToken();

        player1.setPlayerName(e.target.form[0].value);
        player1.setToken(p1Token);

        // Get the token for player 2
        let p2Token;
        if (player1.getToken() === 'X') {
            p2Token = 'O';
        } else {
            p2Token = 'X';
        }

        player2.setPlayerName(e.target.form[1].value);
        player2.setToken(p2Token);
    });

Here is the player module:
   class Player {
    constructor(name='p1', token='X') {
        this.name = name;
        this.token = token;
        this.wins = 0;
    }

    getPlayerName = () => this.name;
    setPlayerName = (name) => this.name = name;
    getToken = () => this.token;
    setToken = (val) => this.token = val;
    getWins = () => this.wins;
    addWin = () => ++this.wins;

}

export default Player;

How can I send values outside of the scope of the listener? I would also need to prevent the rest of the script from running until the listener has ran.