Child shows undefined. for this i want 500 character body for the

I am working on a React project where I need to pass data from a parent component to a child, but the child component keeps showing undefined. Problem: Even though I pass the prop like <Child data={myData} />, it doesn’t render correctly in the child.

Defined myData in state and passed it as a prop. What I expected: The child should receive and render the value, but instead it shows undefined. How can I fix this?

How to replace a space character with a   inside a XHTML file in an ePub (e-book) [closed]

I am augmenting content of a book in ePub format. My task is to make all single-letter words not to show at the end of a line in paragraphs (<p>) or header (<h1> to <h6>) elements.

To do

This is what we must do:

  • Use a php parser or php script to do the job.
  • Target a set of single-letter words declared earlier.
  • The set contains the following characters:
    u U i I o O a A z Z – (this set is for Polish language)
  • In a single html file there might be hundreds instances, multiple instances for each word.

Example of an input and output string/file

Input file

    <h4>Title a title I title O title z title</h4>

    <p>A Lorem ipsum i dolor sit – amet, w consectetur z adipiscing elit. Quisque tincidunt nisi. Z nec arcu convallis pulvinar.</p>

Output file

    <h4>Title a title I&#160;title O&#160;title z&#160;title</h4>

    <p>A Lorem ipsum i&#160;dolor sit&#160;– amet, w&#160;consectetur z&#160;adipiscing elit. Quisque tincidunt nisi. Z&#160;nec arcu convallis pulvinar.</p>
  • the desired code should be CASE SENSITIVE
  • In case of the , some publishers choose to force it to be at the end of a line or at the beginning of a line of text. The code should allow the user to switch between the two standards.

List of sub-jobs the code must do:

  • A note: I am a beginner in this. It is enough that you help me to write a solution for the first 1-2 letters. After seeing your solution, I will do the rest
  • change w w&#160;
  • change W w&#160;
  • change u w&#160;
  • change U w&#160;
  • change i w&#160;
  • change I w&#160;
  • change o w&#160;
  • change O w&#160;
  • change a w&#160;
  • change A w&#160;
  • change z w&#160;
  • change Z w&#160;
  • change &#160;–

Just a note

Currently I just do a find-and-replace. This crude method works and was acceptable for a single book per year. However, now I am about to do dozens.

How to remove all text from inside HTML elements of certain types in an XHTML file (in ePub)

Situation

My goal is to remove ALL text from a html file. The file is a part of an ePub (electronic book)

Example input and output

(It is a chapter of a novel, contained within a single xhtml file.)

<body id="">
  <div>
    <h3 class="h3"><a id="_idTextAnchor026"></a><a id="_idTextAnchor027"></a> Chapter title</h3>

    <p>Paragraph 1. Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
    <p>Paragraph 1. It contains an `a` element.<a id="_idTextAnchor026"></a>. The `a` element should remain intact!</p>

After processing the file or string, the output should be like this:

<body id="">
  <div>
    <h3 class="h3"><a id="_idTextAnchor026"></a><a id="_idTextAnchor027"></a></h3>

    <p></p>
    <p></p>

Success conditions:

  • In the output, all html elements intact. THerefore the structure of both the html file and the ePub is also intact.
  • The special focus is on <a> elements, which are vital part of the whole book’s structure. They are referred to in contents table, file manifests and so on.

What I have tried

I am a begginner in HTML parsing. All solutions lack documentation, which block all my progress in resolving issues.

I have used this repo:
https://github.com/paquettg
and tried to modify this code:

$dom = new Dom;
        $dom->loadStr('<div class="all"><p>Hey bro, <a href="google.com">click here1</a><a href="google.com">click here2</a><br /> :)</p></div>');
        /** @var DomNodeInnerNode $a */
        $a   = $dom->find('a');
        $a->childNodes()->setText('(deleted)');
        echo $dom;

Issues

  • I don’t know how to find all <a> elements. Replacing firstChild with my best quesses has not worked.
  • Also, I have no clue how to handle multiple elements: p, a, h1 to h5, span, b, i, cite, div.
    but I was unable to find a command to select all <a>, h3 and all <p> elements. No documentation.

Just a sidenote

  • My purpose is to create a ePub file with a book sample. The task is to keep first 30% of a book and delete all remaining chapters. Anex and everything at the end of a book should remain as is.
  • The common practices are time consuming and/or damage the ePub structure. In effect, the samples often do not pass automatic check-ups.
  • After I solve this issue, I plan to develop a clean-up app to remove all unwanted class and id attributes, replace spaces with non-breaking spaces and so on.

Woocommerce products batch update limitation: How to update more

I am creating a plugin to update products stock and regular price for now. I am using the batch update API endpoint as follow. I use a csv file with 3 columns product sku, stock and regular price to batch update my website using WC REST API (home_url(‘/wp-json/wc/v3/products/batch’). Everything is working correctly except that I can not batch update when my file contains between 500 to 600 products. I then get 503 Backend fetch failed. The way I proceeed is sending 50 products data at a time as json formatted array of data (as the limit indicated in WC REST API documentation is 100 products). I also used the filter from this SO question to increase the limit but without success. Below are the main methods parts of my stockUpdater class. I first upload the csv file in wp-content folder then use AJAX to instantiate a new class with the methods below that start the batch update process.

    private function sendBatchRequest($data) {

            $ch = curl_init($this->apiUrl);
            curl_setopt_array($ch, [
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_POST => true,
                CURLOPT_POSTFIELDS => json_encode($data),
                CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
                CURLOPT_USERPWD => $this->apiKey . ':' . $this->apiSecret, 
                CURLOPT_TIMEOUT => 60
            ]);

            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);

            return [
                'success'   => ($httpCode >= 200 && $httpCode < 300),
                'response'  => json_decode($response, true),
                'http_code' => $httpCode
            ];
    }

    public function processStockFile() {

        $products = $this->parseCSV(); 
        /* parseCSV returns 

            $products[] = [
                'sku' => trim($data[0]),  // Product SKU
                'id'  => $id,    // Product id
                'stock' => !empty($data[1]) ? (int)trim($data[1]) : 0, // Stock quantity
                'price' => !empty($data[2]) ? wc_format_decimal(str_replace(',', '.', trim($data[2]))) : 0//!empty($data[2]) ? (float)$data[2] : 0, // Product price
            ];
        */
        $chunks = array_chunk($products, 50); // split into 50 products per batch

        $results = [];
        foreach ($chunks as $chunk) {
            $data = ['update' => []];
            foreach ($chunk as $product) {
                $data['update'][] = [
                    'id'             => $product['id'],
                    'sku'            => $product['sku'],
                    'stock_quantity' => $product['stock'],
                    'regular_price'  => $product['price'],
                ];
            }

            $results[] = $this->sendBatchRequest($data);
            //used sleep(1) here did not change
        }

        return $results;

    }

I tried to pause the curl request before sending another one (using php sleep() and usleep()) but again without success. Is there anyway to increase this limit (what I tried did not work in my case) or maybe to fraction the data to send and proceed again after the previous response is a success, in this case what is the best way to proceed?

Ping/connection check stops when print window is open – leads to false “Lost connection to server” error

Description

I have implemented a print report feature in Angular.
When the user clicks the Print button, the browser’s print dialog opens (using window.print()).

At the same time, I also have a ping mechanism to check if the connection between Angular (frontend) and .NET (backend) is active. If no ping response is received within 30 seconds, the UI shows an error message:

“Lost connection to server”

The problem is: when the print window is open, all JavaScript execution is paused (including the ping mechanism). If the user leaves the print window open for more than 30 seconds, Angular displays the “Lost connection to server” error even though the connection is fine.

Steps to Reproduce

  1. Implement a ping/heartbeat mechanism in Angular that checks server
    connection every few seconds.
  2. Trigger window.print() from a button click.
  3. Keep the print window open for longer than the ping timeout
    (30 seconds in my case).
  4. Observe that the ping stops during print
    window → after timeout, Angular shows Lost connection to server.

Expected Behavior

The ping/heartbeat mechanism should continue working in the background (or resume seamlessly after print dialog is closed) so that the app does not incorrectly show Lost connection to server.

Actual Behavior

When the print dialog is open, JavaScript execution halts (including setInterval, setTimeout, and HTTP calls).
As a result, the ping never executes, and Angular incorrectly shows a server disconnection error after 30 seconds.

Environment

  1. Angular version: 18

  2. Browser(s): Chrome, Edge, etc.

  3. OS: Windows 11

Question

Is there any Angular-recommended workaround or best practice to handle this scenario where background tasks (like ping/heartbeat) stop working when the print window is open?

Need a reliable way to keep timer running for displaying server date/time in Angular

Description

I have a use case where the backend sends me the date/time.
On the UI side (Angular), I need to display this date/time and keep incrementing it every second, so that the user always sees the current server time.

I implemented this with setInterval(), but when I minimize the browser or switch to another tab, the timer stops updating because of browser throttling. This results in the displayed time lagging or freezing until the tab becomes active again.

Steps to Reproduce

  1. Receive a date string from backend.

  2. Start a timer that increments the date every second and displays it
    in the UI.

    updateDateTime(inputDate: string) {
        setInterval(() => {
            this.incrementDate(inputDate);
        }, 1000);
    }
    
    incrementDate(inputDate: Date) {
        inputDate.setSeconds(inputDate.getSeconds() + 1);
        this.formattedDateTimeSubject.next(this.formatDate(inputDate));
    }
    

3.Minimize the browser or switch to another tab.

4.Observe that the timer stops firing (UI stops updating).

Expected Behavior

The timer should continue updating every second even when the tab is inactive or minimized, so that the displayed time always reflects the correct running server time.

Actual Behavior

Due to browser throttling, the setInterval() callback is delayed or stopped when the tab is not active, and the UI clock freezes.

Environment

Angular version: 18
Browser(s): Chrome, Edge, etc.
Operating System: Windows 11

What is the recommended Angular way (or workaround) to avoid browser throttling issues for such a use case where we need continuous UI updates (like a clock) even if the tab is inactive?

I can’t created repeated events using ICS.js

I am struggling with ics.js (https://github.com/nwcell/ics.js/)

  1. It is ignoring rules for repeat events set up in rrules

  2. It is not allowing me to add another event from another .ics file after I have added a first one. However, if I delete the first one, I can add the second one.

  3. I am unable to add a calendar event using a JavaScript object.

    var myfunc = function(e) {

    var myfunc = function(e) {
        let target = e.currentTarget;
        if (target.tagName != 'X-EVENT') {
          throw "downloadEvent is for use on x-events only";
        }
        let form = target.querySelector("form");
        let fd = new FormData(form);
        //console.log(fd.has('subject'));
        let recur = fd.get("freq") != "none";
        let rRule = recur ? {"freq" : fd.get("freq"), "interval" : fd.get("interval"), "byday" : fd.getAll("byday"), "until" : fd.get('until') } : null;
    
        let cal  = ics();
    //    cal.addEvent(eventData);
        cal.addEvent(fd.get("subject"),fd.get("description"), fd.get("location"),       fd.get("start"), fd.get("end"), rRule);
        cal.download(fd.get("subject"));
    }
    

As you can infer from the code snippet above, I create adding an event as an object but that failed.

How can I fix this code so that the reoccurrence instructions in rRule are obeyed?

Flask python generate a white web page

I’m trying a small start with flaks and web tools, but the html, css does not show in the page, just a blank page, I need an explanation please, I’m using VSCode, this is my code :

Project structure :

FLASKTEST/
│ test.py              
│
├── templates/
│     index.html
└── static/
      style.css
      script.js

test.py file :

from flask import Flask, render_template

app = Flask(__name__)

@app.route("/")
def home():
    return render_template("index.html")  

if __name__ == "__main__":
    app.run(debug=True)

index.html file :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Small Example</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
    <h1>Welcome to Flask</h1>
    <p>This is a small example combining HTML + CSS + JS + Flask</p>
    <button onclick="showMessage()">Click here</button>

    <script src="{{ url_for('static', filename='script.js') }}"></script>
</body>
</html>

style.css file :

body {
    background-color: #396e9d;
    font-family: Arial, sans-serif;
    text-align: center;
    padding-top: 50px;
}
h1 {
    color: darkblue;
}
button {
    padding: 10px 20px;
    font-size: 16px;
    cursor: pointer;
}

script.js file :

function showMessage() {
    alert("Hello");
}

Should I Avoid Global Variables At All Cost? [closed]

In my project, I am trying to create a chat room. In the chat room, I need to send different kind of data about other sections of my app. I use web sockets to that.

To send same data to every client in the room they are inside of, I need to iterate over like, all of the clients. And if like, I have 1000 clients, it could create lag, so messages or other datas could be laggy. To prevent this, I can actually create a map object and set room name, to that key(room name) name I can use set object as value that is having an instance of client object of web socket itself. So thanks to that global variable map object I saved performance of iterating through all clients to just to send to the clients in the same room.

Code for the loop I am currently using to avoid global variable:

ws.communityName = communityName;

// Send to all clients in the same community
webSocket.clients.forEach((client) => {
      if(client.communityName === communityName) {
            client.send(stringifiedActiveUsers);

            // Send only to owner of the community within user's community 
            if(client.userid === communityOwnerId) {
                  client.send(suspendedUsersData);
            }
      }
});

That is my logic on how to send data to all clients in the same room. But I am using global variable, which I shouldnt because it could create memory leak problems etc…

Do you think there is a more efficient solution to this problem? Should I use global variable to save performance?

Unit testing AssertionError: expected false to be true after js-dom update

For a security compliance reason I had to update the js-dom libray to version 27.0.0 from 23.0.0 after that few unit tests failed.

This is a Vue.js project and use these libries for testing

import { expect } from 'chai';
import { mount } from '@vue/test-utils';

This is the unit test getting failed. After updating.

console.log(wrapper.find('.myclass')); // Output [Object: null prototype] {}
expect(wrapper.find('.myclass').exists()).to.be.false;

Error message I am getting here is

AssertionError: expected false to be true

Even though the console.log prints the same output, I am wondering why this is failing. What am I missing here?

Adding Tailwind hover class using classList.add in Javascript

clockBtn.classList.add(..., "opacity-0", "hover:opacity-100");

The clockBtn button is dynamically created in a function defined in .js file.

I am trying to use hover:opacity-100 so that the button, which is usually not visible, shows up upon hovering over the button.

But, the button stays invisible even when the cursor is over the button.

Is this the right way to add this hover Tailwind class in Javascript?

Should I Avoid Global Variables At All Cost?

In my project, I am trying to create a chat room. In the chat room, I need to send different kind of data about other sections of my app. I use web sockets to that.

To send same data to every client in the room they are inside of, I need to iterate over like, all of the clients. And if like, I have 1000 clients, it could create lag, so messages or other datas could be laggy. To prevent this, I can actually create a map object and set room name, to that key(room name) name I can use set object as value that is having an instance of client object of web socket itself. So thanks to that global variable map object I saved performance of iterating through all clients to just to send to the clients in the same room.

Code for the loop I am currently using to avoid global variable:

ws.communityName = communityName;

// Send to all clients in the same community
webSocket.clients.forEach((client) => {
      if(client.communityName === communityName) {
            client.send(stringifiedActiveUsers);

            // Send only to owner of the community within user's community 
            if(client.userid === communityOwnerId) {
                  client.send(suspendedUsersData);
            }
      }
});

That is my logic on how to send data to all clients in the same room. But I am using global variable, which I shouldnt because it could create memory leak problems etc…

Do you think there is a more efficient solution to this problem? Should I use global variable to save performance?

How to pass information to a GLTFLoader callback function?

With THREE.js and GLTFLoader I’m loading models. After the model is loaded I’d like to cache it in a dictionary. The only hold of the model I seem to get in the loader callback. I need to pass the key-string to the loader to save the loaded object in the dictionary.

How do I pass a string to the GLTFLoader callback?

Code:

var modelSources = { car: "resources/models/my-model.glb" };
modelSources.length = 0;
var dictionary = {};
for (var key in modelSources)
{
    var value = modelSources[key];
    if (typeof(value) === "string")
    {
        if (value.startsWith("http") || value.startsWith("resources/"))
        {
            modelSources.length++;
            var loader = new GLTFLoader();
            loader.load(value, function (group)
            {
                var obj = group.scene.children[0];
                // need key or at least value
                dictionary[key] = obj;
            });
        }
    }
}

window.visualViewport.scale is not updated until stack of function calls ends

This is part of a large Tampermonkey userscript i’m writing.
It changes window.visualViewport.scale and use the resize event to show the new value.

In the snippet it doesn’t do anything, but on the page it works (using the debug tools with the device toolbar activated)

// ==UserScript==
// @name         provaui
// @namespace    http://tampermonkey.net/
// @version      2025-09-20
// @description  try to take over the world!
// @author       You
// @match        https://www.soundcraft.com/ui24-software-demo/mixer.html
// @icon         https://www.google.com/s2/favicons?sz=64&domain=soundcraft.com
// @grant        none
// ==/UserScript==
let UserScale=1; // current scale variable
let dbgLog="";

function setViewportScale(ViewScale) {
  console.log(dbgLog+"setViewportScale Start"); dbgLog=dbgLog+"....";
  let NewScale = Number(ViewScale);
  CurrentScale=NewScale;
  console.log(dbgLog+"NewScale: "+NewScale);

  console.log(dbgLog+"Applying new scale");
  let vpElement = document.querySelector("meta[name=viewport]");
  if (!vpElement){
    vpElement=document.createElement('meta');
    vpElement.name = "viewport";
    document.getElementsByTagName('head')[0].appendChild(vpElement);
  }
  let content = 'width=device-width, initial-scale=' + NewScale + ', maximum-scale=1.5, minimum-scale=0.5, user-scalable=yes';
  vpElement.setAttribute('content', content);
  console.log(dbgLog+"VP Scale is "+ window.visualViewport.scale);
  dbgLog=dbgLog.replace("....",""); console.log(dbgLog+"setViewportScale End");
}
// =============================================================
function updateSize() {
  console.log(dbgLog+"updateSize Start"); dbgLog=dbgLog+"....";
  console.log(dbgLog+"VP Scale is "+ window.visualViewport.scale);
  dbgLog=dbgLog.replace("....",""); console.log(dbgLog+"updateSize End");
}
// =============================================================


// zoom button
let aDiv = document.createElement ('div');
aDiv.setAttribute ('id', 'ZoomButtonContainer');
aDiv.style = 'position:absolute; top: 12px; left: 10px; z-index: 99998; background-color: orange; display: flex; justify-content: center; align-items: center; padding: 5px;'
aDiv.innerHTML = ''
    + '<button id="bZoom" type="button" style="width:130px !important;">Zoom</button>'
    + '<button id="bLog" type="button" style="width:130px !important;">Log</button>'
    ;
document.body.appendChild (aDiv);
document.getElementById('bZoom').addEventListener('click', function(event) {
  event.stopPropagation();
  if (UserScale==1) {
    UserScale = 0.7;
  }else{
    UserScale = 1;
  }
  setViewportScale(UserScale);
});
document.getElementById('bLog').addEventListener('click', function(event) {
  console.log(dbgLog+"Log Button: VP Scale is "+ window.visualViewport.scale);
});

// Add an event listener for window resize
window.addEventListener('resize', updateSize);

(function() {
    'use strict';

    // Your code here...
})();

This same exact code, on the page declared in the userscript header, produces this output:

Log Button: VP Scale is 1

setViewportScale Start
....NewScale: 0.7
....Applying new scale
....VP Scale is 1
setViewportScale End
updateSize Start
....VP Scale is 1
updateSize End

Log Button: VP Scale is 0.7002456784248352

setViewportScale Start
....NewScale: 1
....Applying new scale
....VP Scale is 0.7002456784248352
setViewportScale End
updateSize Start
....VP Scale is 0.7002456784248352
updateSize End

Log Button: VP Scale is 1

As you can see, the resize event still shows the old scale value, even if the scaling works flawlessy.
What am i doing wrong? How can i read the updated scale value?

How to highlight Tamil spelling mistakes in a Chrome Extension using JavaScript?

I’m building a Tamil Spell Checker Chrome Extension. I want to highlight incorrect words in text input fields or on web pages.

I have a list of correct Tamil words in a dictionary (JavaScript array), and I want to compare each word on the page with this list.

Problem: I’m not sure how to efficiently check each word and highlight only the wrong ones in real-time without slowing down the page.

I looped through each word and checked against my dictionary.

Used innerHTML to wrap wrong words in tags with red color.

Issue: This sometimes breaks the page formatting and is slow on large paragraphs.