Can’t change boolean from inside of .onError in JS [duplicate]

I can’t seem to switch the boolean value of ‘errorcheck’ using image .onerror function.
I’m able to see console logs, trigger functions from inside the .onerror but I just can’t change the variable ‘errorcheck’

The goal is to have a for loop that adds item icons until a broken image path is found

let errorcheck= false;

document.addEventListener('DOMContentLoaded', function() {
  const itemInventory = document.getElementById('itembox');
  const totalItems= 25; //+1 actual count
  let inventoryadd="";
  
  for(let i = 1; i < totalItems; i++) {
    if (errorcheck) {
      break;
    }

    const itemImg= new Image();
    itemImg.src = `images/itemicon${i}.png`;

    // This isn't working
    itemImg.onerror = () => {
      errorcheck= true;
    }

    // returns errorcheck= false;
    console.log(errorcheck);

    inventoryadd += 
    `<li class="itemIcons">
    <img id="itemicon${i}" class="icons" onclick="itemCLick(this.id)" src="images/itemicon${i}.png">
    </li>`;

    myImage.remove();


    }
 
 
  itemInventory.innerHTML += inventoryadd;
    
});

Is there a way to extract the header HTML tag from a given URL dinamically with php?

I have a WordPress website, and I need to extract into a PHP plugin the header tag from this website, and format the code like this:

<style>
    Code stylization grouped if needed on the header here
</style>
<header>
    Header extracted from WordPress
</header>
<script>
    Scripts grouped if needed on the header here
</script>

I already did something interesting, but I’m having trouble loading two dropdown lists with options from the html (HOTELS and LANG).

Here is a sample HTML code from a random page:

<header class="fusion-header-wrapper">
    <div class="fusion-header-v5 fusion-logo-alignment fusion-logo-center fusion-sticky-menu- fusion-sticky-logo- fusion-mobile-logo- fusion-sticky-menu-only fusion-header-menu-align-center fusion-mobile-menu-design-modern">
        <div class="fusion-secondary-header">
            <div class="fusion-row">
                <div class="fusion-alignleft">
                    <div class="fusion-contact-info">
                        <span class="fusion-contact-info-phone-number">(+351) 300 528 059</span>
                        <span class="fusion-header-separator">|</span>
                        <span class="fusion-contact-info-email-address">
                            <a href="mailto:&#114;e&#115;&#101;r&#118;as&#64;tu&#114;&#105;mho&#116;e&#105;&#115;.c&#111;&#109;">&#114;e &#115;&#101;r &#118;as &#64;tu &#114;&#105;mho &#116;e &#105;&#115;.c &#111;&#109;</a>
                        </span>
                    </div>
                </div>
            </div>
        </div>
        <div class="fusion-header-sticky-height"></div>
        <div class="fusion-sticky-header-wrapper">
            <!-- start fusion sticky header wrapper -->
            <div class="fusion-header">
                <div class="fusion-row">
                    <div class="fusion-logo" data-margin-top="31px" data-margin-bottom="31px" data-margin-left="0px" data-margin-right="0px">
                        <a class="fusion-logo-link" href="https://my-site.com/">
                            <!-- standard logo -->
                            <img src="https://my-site.com/Logo.png" srcset="https://my-site.com/Logo.png 1x" width="308" height="105" alt="Book your stay on the Hotels official website! Logo" data-retina_logo_url="" class="fusion-standard-logo"/>
                        </a>
                    </div>
                    <div class="fusion-mobile-menu-icons">
                        <a href="#" class="fusion-icon awb-icon-bars" aria-label="Toggle mobile menu" aria-expanded="false"></a>
                    </div>
                </div>
            </div>
            <div class="fusion-secondary-main-menu">
                <div class="fusion-row">
                    <nav class="fusion-main-menu" aria-label="Main Menu">
                        <div class="fusion-overlay-search">
                            <form role="search" class="searchform fusion-search-form  fusion-search-form-clean" method="get" action="https://my-site.com">
                                <div class="fusion-search-form-content">
                                    <div class="fusion-search-field search-field">
                                        <label>
                                            <span class="screen-reader-text">Search for:</span>
                                            <input type="search" value="" name="s" class="s" placeholder="Search..." required aria-required="true" aria-label="Search..."/>
                                        </label>
                                    </div>
                                    <div class="fusion-search-button search-button">
                                        <input type="submit" class="fusion-search-submit searchsubmit" aria-label="Search" value="&#xf002;"/>
                                    </div>
                                </div>
                            </form>
                            <div class="fusion-search-spacer"></div>
                            <a href="#" role="button" aria-label="Close Search" class="fusion-close-search"></a>
                        </div>
                        <ul id="menu-main-menu" class="fusion-menu">
                            <li id="menu-item-3946" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-has-children menu-item-3946 fusion-dropdown-menu" data-item-id="3946">
                                <a href="#" class="fusion-bottombar-highlight">
                                    <span class="menu-text">HOTELS</span>
                                    <span class="fusion-caret">
                                        <i class="fusion-dropdown-indicator" aria-hidden="true"></i>
                                    </span>
                                </a>
                                <ul class="sub-menu">
                                    <li id="menu-item-3947" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-has-children menu-item-3947 fusion-dropdown-submenu">
                                        <a href="#" class="fusion-bottombar-highlight">
                                            <span>HOTEL-01</span>
                                            <span class="fusion-caret">
                                                <i class="fusion-dropdown-indicator" aria-hidden="true"></i>
                                            </span>
                                        </a>
                                        <ul class="sub-menu">
                                            <li id="menu-item-4037" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-4037">
                                                <a href="https://my-site.com/hotel01" class="fusion-bottombar-highlight">
                                                    <span>hotel01</span>
                                                </a>
                                            </li>
                                            <li id="menu-item-4035" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-4035">
                                                <a href="https://my-site.com/hotel02" class="fusion-bottombar-highlight">
                                                    <span>hotel02</span>
                                                </a>
                                            </li>
                                            <li id="menu-item-4782" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-4782">
                                                <a href="https://my-site.com/hotel03" class="fusion-bottombar-highlight fusion-has-highlight-label">
                                                    <span>hotel03</span>
                                                </a>
                                            </li>
                                        </ul>
                                    </li>
                                    <li id="menu-item-3962" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-has-children menu-item-3962 fusion-dropdown-submenu">
                                        <a href="#" class="fusion-bottombar-highlight">
                                            <span>HOTEL-02</span>
                                            <span class="fusion-caret">
                                                <i class="fusion-dropdown-indicator" aria-hidden="true"></i>
                                            </span>
                                        </a>
                                        <ul class="sub-menu">
                                            <li id="menu-item-4031" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-4031">
                                                <a href="https://my-site.com/hotel01" class="fusion-bottombar-highlight">
                                                    <span>hotel01</span>
                                                </a>
                                            </li>
                                        </ul>
                                    </li>
                                </ul>
                            </li>
                            <li id="menu-item-26285" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-26285" data-item-id="26285">
                                <a href="https://bookings.turim-hotels.com/pt/bookcore/loyalty/account" class="fusion-bottombar-highlight">
                                    <span class="menu-text">CLUB</span>
                                </a>
                            </li>
                            <li id="menu-item-6094" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-6094" data-item-id="6094">
                                <a href="https://turim-hotels.com/en/events-en/" class="fusion-bottombar-highlight">
                                    <span class="menu-text">EVENTS</span>
                                </a>
                            </li>
                            <li id="menu-item-6095" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-6095" data-item-id="6095">
                                <a href="https://turim-hotels.com/en/corporate-en/" class="fusion-bottombar-highlight">
                                    <span class="menu-text">CORPORATE</span>
                                </a>
                            </li>
                            <li id="menu-item-19578" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-19578" data-item-id="19578">
                                <a href="https://turim-hotels.com/en/trade/" class="fusion-bottombar-highlight">
                                    <span class="menu-text">TRADE</span>
                                </a>
                            </li>
                            <li id="menu-item-6093" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-6093" data-item-id="6093">
                                <a href="https://turim-hotels.com/en/news-en/" class="fusion-bottombar-highlight">
                                    <span class="menu-text">NEWS</span>
                                </a>
                            </li>
                            <li id="menu-item-6092" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-6092" data-item-id="6092">
                                <a href="https://turim-hotels.com/en/promotions-en/" class="fusion-bottombar-highlight">
                                    <span class="menu-text">PROMOTIONS</span>
                                </a>
                            </li>
                            <li id="menu-item-6091" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-6091" data-item-id="6091">
                                <a href="https://turim-hotels.com/en/careers-en/" class="fusion-bottombar-highlight">
                                    <span class="menu-text">CAREERS</span>
                                </a>
                            </li>
                            <li id="menu-item-6096" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-6096" data-item-id="6096">
                                <a href="https://turim-hotels.com/en/contacts-en/" class="fusion-bottombar-highlight">
                                    <span class="menu-text">CONTACTS</span>
                                </a>
                            </li>
                            <li id="menu-item-3987" class="pll-parent-menu-item menu-item menu-item-type-custom menu-item-object-custom menu-item-has-children menu-item-3987 fusion-dropdown-menu" data-classes="pll-parent-menu-item" data-item-id="3987">
                                <a href="#pll_switcher" class="fusion-bottombar-highlight">
                                    <span class="menu-text">
                                        <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAMAAABBPP0LAAAAt1BMVEWSmb66z+18msdig8La3u+tYX9IaLc7W7BagbmcUW+kqMr/q6n+//+hsNv/lIr/jIGMnNLJyOP9/fyQttT/wb3/////aWn+YWF5kNT0oqz0i4ueqtIZNJjhvt/8gn//WVr/6+rN1+o9RKZwgcMPJpX/VFT9UEn+RUX8Ozv2Ly+FGzdYZrfU1e/8LS/lQkG/mbVUX60AE231hHtcdMb0mp3qYFTFwNu3w9prcqSURGNDaaIUMX5FNW5wYt7AAAAAjklEQVR4AR3HNUJEMQCGwf+L8RR36ajR+1+CEuvRdd8kK9MNAiRQNgJmVDAt1yM6kSzYVJUsPNssAk5N7ZFKjVNFAY4co6TAOI+kyQm+LFUEBEKKzuWUNB7rSH/rSnvOulOGk+QlXTBqMIrfYX4tSe2nP3iRa/KNK7uTmWJ5a9+erZ3d+18od4ytiZdvZyuKWy8o3UpTVAAAAABJRU5ErkJggg==" alt="" width="16" height="11" style="width: 16px; height: 11px;"/>
                                        <span style="margin-left:0.3em;">English</span>
                                    </span>
                                    <span class="fusion-caret">
                                        <i class="fusion-dropdown-indicator" aria-hidden="true"></i>
                                    </span>
                                </a>
                                <ul class="sub-menu">
                                    <li id="menu-item-3987-pt" class="lang-item lang-item-15 lang-item-pt lang-item-first menu-item menu-item-type-custom menu-item-object-custom menu-item-3987-pt fusion-dropdown-submenu" data-classes="lang-item">
                                        <a href="https://my-site.com/" class="fusion-bottombar-highlight" hreflang="pt-PT" lang="pt-PT">
                                            <span>
                                                <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAABL0lEQVR4AV2RA2yEQRCFNxcnRVw3qG3bthXUbZxaUaOGRVA7ro2wDWoEtW2b9/b2nHx3v943uztDSAwhAQJ86P83keCJw2HcEAJoqLivmJHbnQt+s7OFfMXHMz5DAgBPCKBCUktSRmdK43Dw3Gz451TIc68nPr+7uLzZWr2Zm78bGLxpa797e1+IC0erUeAmL+ol3R8CEE+/qqvDv2BbwjYi6yJR+6Ys5m5zA0C7HbWEIEy/KCpKC8uzQRf5fkivX3zBZIIw/Swvj8cTKthRIbDGDwcYnXRF7avy/KM5q8NZg2cDPWEaYHt8AceFACBsTdui9nmn8VWmpngawN+ngiEVHCocGM5Vpu8G0rUB5iAS0CKAYwCsg/YB1lPWKESBSCAqhMiKwHQueJwI2BeDC83C2lDIxUCuAAAAAElFTkSuQmCC" alt="" width="16" height="11" style="width: 16px; height: 11px;"/>
                                                <span style="margin-left:0.3em;">Português</span>
                                            </span>
                                        </a>
                                    </li>
                                    <li id="menu-item-3987-es" class="lang-item lang-item-445 lang-item-es menu-item menu-item-type-custom menu-item-object-custom menu-item-3987-es fusion-dropdown-submenu" data-classes="lang-item">
                                        <a href="https://my-site.com/es" class="fusion-bottombar-highlight" hreflang="es-ES" lang="es-ES">
                                            <span>
                                                <img loading="lazy" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAMAAABBPP0LAAAAflBMVEX/AAD9AAD3AADxAADrAAD/eXn9bGz8YWH8WVn6UVH5SEj5Pz/3NDT0Kir9/QD+/nL+/lT18lDt4Uf6+j/39zD39yf19R3n5wDxflXsZ1Pt4Y3x8zr0wbLs1NXz8xPj4wD37t3jmkvsUU/Bz6nrykm3vJ72IiL0FBTyDAvhAABEt4UZAAAAX0lEQVR4AQXBQUrFQBBAwXqTDkYE94Jb73+qfwVRcYxVQRBRToiUfoaVpGTrtdS9SO0Z9FR9lVy/g5c99+dKl30N5uxPuviexXEc9/msC7TOkd4kHu/Dlh4itCJ8AP4B0w4Qwmm7CFQAAAAASUVORK5CYII=" alt="" width="16" height="11" style="width: 16px; height: 11px;"/>
                                                <span style="margin-left:0.3em;">Español</span>
                                            </span>
                                        </a>
                                    </li>
                                </ul>
                            </li>
                        </ul>
                    </nav>
                    <nav class="fusion-mobile-nav-holder fusion-mobile-menu-text-align-left fusion-mobile-menu-indicator-hide" aria-label="Main Menu Mobile"></nav>
                </div>
            </div>
        </div>
        <!-- end fusion sticky header wrapper -->
    </div>
    <div class="fusion-clearfix"></div>
</header>

And my plugin so far:

<?php
add_action('rest_api_init', function () {
    register_rest_route('plugin/v1', '/json', [
        'methods' => 'GET',
        'callback' => 'page_json',
        'permission_callback' => '__return_true',
        'args' => [
            'lang' => [
                'sanitize_callback' => 'sanitize_text_field',
                'default' => 'pt',
            ],
        ],
    ]);
});

function get_lang_url($lang) {
    $urls = array(
        'pt' => 'ptUrlPlaceholder',
        'en' => 'enUrlPlaceholder',
        'es' => 'esUrlPlaceholder'
    );
    return $urls[$lang];
}

function resolve_url($base, $relative) {
    if (parse_url($relative, PHP_URL_SCHEME)) return $relative;
    $base = rtrim($base, '/');
    return $base . '/' . ltrim($relative, '/');
}

function css_fix_urls($css, $baseUrl) {
    return preg_replace_callback(
        '/url((["']?)(?!data:|https?:|//)([^"')]+)1)/i',
        function($m) use ($baseUrl) {
            $path = resolve_url($baseUrl, $m[2]);
            return "url('{$path}')";
        },
        $css
    );
}

function get_clean_dom($url) {
    $response = wp_remote_get($url);
    if (is_wp_error($response)) {
        return new WP_Error('fetch_error', 'Erro ao acessar o site externo', ['status' => 500]);
    }

    $html = wp_remote_retrieve_body($response);
    if (empty($html)) {
        return new WP_Error('empty_html', 'Conteúdo vazio recebido do site externo', ['status' => 500]);
    }

    libxml_use_internal_errors(true);
    $dom = new DOMDocument();
    $dom->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
    return $dom;
}

function inject_style($dom, $headerNode, $styleBlock) {
    if (!$headerNode) return;
    if ($styleBlock) {
        $frag = $dom->createDocumentFragment();
        $frag->appendXML($styleBlock);
        $headerNode->insertBefore($frag, $headerNode->firstChild);
    }
}

function remove_links_and_scripts($dom, $node) {
    $xpath = new DOMXPath($dom);
    foreach ($xpath->query('.//link[@rel="stylesheet"]', $node) as $ln) { $ln->parentNode->removeChild($ln); }
    foreach ($xpath->query('.//script', $node) as $s) {
        $s->parentNode->removeChild($s);
    }
}

function collect_and_inline_css_simple($dom, $baseUrl) {
    $xpath = new DOMXPath($dom);
    $cssParts = [];

    foreach ($xpath->query('//style') as $styleNode) {
        $cssParts[] = $styleNode->nodeValue;
    }

    foreach ($xpath->query('//link[@rel="stylesheet"]') as $linkNode) {
        $href = $linkNode->getAttribute('href');
        if (!$href) continue;
        $full = resolve_url($baseUrl, $href);
        $res = wp_remote_get($full, ['timeout'=>15]);
        if (!is_wp_error($res)) {
            $css = wp_remote_retrieve_body($res);
            $css = css_fix_urls($css, $full);
            $cssParts[] = $css;
        }
    }

    $all = implode("n", $cssParts);
    return $all ? "<style>n{$all}n</style>" : '';
}

function collect_needed_scripts($url, $xpath) {
    $scriptContent = [];

    foreach ($xpath->query('//script[@src]') as $s) {
        $src = $s->getAttribute('src');
        if (!$src) continue;
        $full = resolve_url($url, $src);

        if (strpos($full, 'jquery') !== false ||
            strpos($full, 'avada') !== false ||
            strpos($full, 'fusion') !== false) {

            $res = wp_remote_get($full, ['timeout'=>15]);
            if (!is_wp_error($res)) {
                $code = wp_remote_retrieve_body($res);
                if ($code) {
                    $scriptContent[] = "n/* Script: {$full} */n" . $code;
                }
            }
        }
    }

    foreach ($xpath->query('//script[not(@src)]') as $s) {
        $code = trim($s->nodeValue);
        if ($code) {
            $scriptContent[] = "n/* Inline Script */n" . $code;
        }
    }

    $all = implode("n", $scriptContent);
    return $all ? "<script>n{$all}n</script>" : '';
}

function page_json($request) {
    $lang = $request->get_param('lang');
    $url  = get_lang_url($lang);

    $dom = get_clean_dom($url);
    if (is_wp_error($dom)) {
        return ['error' => 'DOM error'];
    }

    $xpath = new DOMXPath($dom);
    $headerNode = $xpath->query('//header')->item(0);
    $footerNode = $xpath->query('//footer')->item(0);

    $styleBlock = collect_and_inline_css_simple($dom, $url);

    $allScripts = collect_needed_scripts($url, $xpath);

    if ($headerNode) remove_links_and_scripts($dom, $headerNode);
    if ($footerNode) remove_links_and_scripts($dom, $footerNode);

    $headerHtml = $headerNode ? $dom->saveHTML($headerNode) : '';
    $footerHtml = $footerNode ? $dom->saveHTML($footerNode) : '';

    $finalHeader = $styleBlock . "n" . $headerHtml . "n" . $allScripts;

    return [
        'header' => $finalHeader,
        'footer' => $footerHtml
    ];
}

What am I doing wrong here?

Listener for opening a section in Elementor edit panel

I want some elements in my widget to be hidden when a specific section in the Style tab is opened in Elementor.

For example, I have this section (currently empty):

$this->end_controls_section();

$this->start_controls_section('section_style_counter', [
 'label' => 'Счетчик',
 'tab'   => Controls_Manager::TAB_STYLE,
]);

$this->add_control('counter_btns', [
 'label' => 'Кнопки счетчика',
 'type'  => Controls_Manager::HEADING,
]);

How can I add a listener to detect when this section is opened?
Basically, I want to run some JS code only when this section is expanded in the Elementor panel.

I tried adding an event listener in JS on click for the section, but it seems to ignore it.

MongoDB query with Mongoose – Matching subdocument attribute within an array

I am trying to solve an issue with the format of documents in a MongoDB depicted below.

{
  "_id": {
    "$oid": "68dc4f78e11553b3647231e2"
  },
  "name": "Dutch Bros",
  "address": "25 Down Street, Salt Lake City, UT",
  "facilities": [
    "Hot drinks",
    "Food"
  ],
  "coords": [
    -0.9690884,
    51.455041
  ],
  "reviews": [
    {
      "author": "John Smith",
      "rating": {
        "$numberDecimal": "5"
      },
      "createdOn": {
        "$date": "2025-09-30T06:00:00.000Z"
      },
      "reviewText": "Great Place. Would come back again!"
    },
    {
      "author": "Jane Doe",
      "rating": {
        "$numberDecimal": "4"
      },
      "createdOn": {
        "$date": "2025-09-30T06:00:00.000Z"
      },
      "reviewText": "Okay Place. Would come back again!"
    }
  ]
}

My goal is to match review sub-document(s) based on an attribute it has such as ratings being equal to five. I know that I could take the reviews array as a whole and iterate over them to search the attributes for what I need, but I want to be able to find it directly in the MongoDB query so the MongoDB server does the work while it saves my express server any additional workload.

I guess what I am asking is how do I reference the iterable objects in the reviews array. I hope that was clear enough and I apologize if it wasn’t!

I’ve successfully implemented a version that iterates in a for loop on the express server in the controller, but this is what I want to avoid. I’ve also tried using a .get() method on the returned array because I saw that it was an available method for the object, but that yielded an error. I’ve also tried to build a query which was close to what I believe the solution is going to be but I can’t understand how MongoDB element matches an array item, see below for my failed attempt.

const monReview = await Loc
            .findById(req.params.locationid)
            .select('name reviews')
            .where('reviews')
            .elemMatch({$eq: req.params.reviewRating})
            .exec();  

Update total in Stripe payments upon shipping rate change (Amazon, Google Pay etc)

Here is some infromation about shippingratechange for Stripe express checkout.
https://docs.stripe.com/js/elements_object/express_checkout_element_shippingratechange_event

which implemented and when the Stripe payment button is clicked the modal window properly displayed:
enter image description here

Then, as you see on the image, there are several shipping options properly passed and rendered. Once another shipping option (with another price) is chosen, it triggers ‘shippingratechange’. How to update the Total because the shipping price was changed?

When I change the shipping option, it changes fine, but the Total remains unchanged, although shippingratechange gets triggered with no questions. How to set another totals value, for example 99.90 (let’s say the math calculated).

What should be added to here?

expressCheckoutElement.on('shippingratechange', function(event) {
  var resolve = event.resolve;
  var shippingRate = event.shippingRate;
  // handle shippingratechange event

  // define payload and pass it into resolve
  var payload = {
    shippingRates: [
      shippingRate
    ]
  };

  // call event.resolve within 20 seconds
  resolve(payload);
});

Why does a small React dynamic import file (~3.7 KB) take 650 ms on first load but only 45 ms on refresh with AWS S3 + CloudFront?

I have a React app deployed on AWS S3 + CloudFront.

One of my routes uses a dynamic import (import()), and the corresponding JS chunk is very small (~3.7 KB).

On the first load, the request for this file takes about 650 ms, but if I refresh the page immediately afterward, it only takes about 45 ms.

Here’s the request and response details from Chrome DevTools for the file:

Request URL: https://admin.simprosysapis.com/assets/RolesList-DVgRFD0k.js
Request Method: GET
Status Code: 200 OK
Remote Address: 18.66.57.77:443
Referrer Policy: strict-origin-when-cross-origin

Response headers

cache-control: max-age=3600, must-revalidate
content-encoding: br
content-type: text/javascript
server: SimprosysAPI
via: 1.1 ...cloudfront.net (CloudFront)
x-cache: Miss from cloudfront

Request headers

accept-encoding: gzip, deflate, br, zstd
cache-control: no-cache
pragma: no-cache
user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) ...

My questions

  1. Why does a 3.7 KB file take ~650 ms to load the first time?

    • Is this mostly TLS/handshake + CloudFront latency rather than file size?
    • Is the x-cache: Miss from cloudfront header responsible?
  2. Why does it become so much faster (~45 ms) on refresh?

    • Is the browser using disk/memory cache or a CloudFront cached copy?
  3. Is there a way to improve the first load time for these small dynamic chunks (e.g., preloading, prefetching, or CloudFront settings)?


What I tried

  • Checked headers: content-encoding: br confirms compression is working.
  • Cache headers look reasonable (max-age=3600).
  • Behavior is consistent across multiple builds.

Expected / Desired

I want to understand if this latency difference is normal for CloudFront + S3 dynamic imports, and whether I can optimize the first-load latency further.

How to achieve an “inset carved” gallery card effect inside an image container with CSS clip-path or masks? [closed]

Reference
my trial

I’m trying to replicate a hero section design where the gallery card looks like it is carved into the main image container (instead of floating on top).

I attempted using an SVG clipPath with an organic shape applied to the .main-image, but the gallery card still appears as a separate overlay. It doesn’t blend with the container as expected.

<div class="organic-gallery">
  <!-- Clip path definition -->
  <svg width="0" height="0">
    <defs>
      <clipPath id="organic-carved-shape" clipPathUnits="objectBoundingBox">
        <path d="M 0.06,0 L 0.94,0 C 0.97,0 1,0.03 1,0.06 L 1,0.94 C 1,0.97 0.97,1 0.94,1 L 0.7,1 C 0.68,1 0.66,0.998 0.64,0.995 L 0.05,0.82 C 0.02,0.815 0,0.8 0,0.78 L 0,0.06 C 0,0.03 0.03,0 0.06,0 Z" />
      </clipPath>
    </defs>
  </svg>

  <div class="gallery-container">
    <!-- Main image background -->
    <div class="main-image">
      <img src="circuit.jpg" class="circuit-bg" />
      
      <!-- floating labels -->
      <div class="feature-label" style="top: 3rem; right: 3rem;">On-Device Analysis</div>
      <div class="feature-label" style="top: 8rem; right: 6rem;">Smart App</div>
    </div>

    <!-- supposed to be carved into the main container -->
    <div class="gallery-card">
      <div class="gallery-images">
        <div class="gallery-item">Thumb 1</div>
        <div class="gallery-item">Thumb 2</div>
      </div>
    </div>
  </div>
</div>
.gallery-container {
  position: relative;
  height: 600px;
}

.main-image {
  position: absolute;
  inset: 0;
  border-radius: 3rem;
  overflow: hidden;
  clip-path: url(#organic-carved-shape);
}

.circuit-bg {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.gallery-card {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 380px;
  padding: 1.5rem;
  border-radius: 2rem;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(12px);
  box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
}

Current result:
The gallery card simply overlaps the main image.

Expected result:
The gallery card should appear as if it’s part of (or cut into) the main container — following the same organic shape, not just sitting on top.

Question:
What’s the correct way (CSS clip-path, mask, pseudo-elements, or another technique) to make the gallery card look “carved into” the image container?

HTML Canvas lineTo() draws with incorrect y coordinates

Achieving clear lines in HTML canvas requires setting the CSS canvas height and width to be the canvas height and width / device pixel ratio:

this.element.style.height = this.element.height / dpr + "px";
this.element.style.height = this.element.height / dpr + "px";

An unfortunate outcome of this is that the lineTo command will now be incorrect. For example, if I draw a square as:

ctx.lineTo(113.395,54.233);
ctx.lineTo(120.791,54.233);
ctx.stroke();

ctx.lineTo(120.791,54.233);
ctx.lineTo(120.791,46.837);
ctx.stroke();

ctx.lineTo(120.791,46.837);
ctx.lineTo(113.395,46.837);
ctx.stroke();

ctx.lineTo(113.395,46.837);
ctx.lineTo(113.395,54.233);
ctx.stroke();

The result is not square:

enter image description here

Anti-aliasing aside, if we average the placement of each line to its darker side, the width is approximately 7px (correct), while the height is approximately 8px (incorrect).

Does anyone have a solution for this?

using polylang , how to move all the translation po files directly (using a plugin) instead of migrating them manually

HI I am working on a creating of a plugin where site is built using child of a classic theme In my site i am already using polylang (free) version now i tried to build a plugin

where I need to Ensure all French translations from the theme .po files are imported into the Polylang database automatically

Current status:I Manual conversion of _()/e() to pll()/pll_e() in the theme is done and working.

So Now i my requirement is to Create a one-time plugin to import existing .po translations into Polylang GUI/database.

The Purpose of it is to Avoid manual entry errors, reduce deployment downtime, and ensure translations work correctly in live/production.

Scope: Use existing .pot, .po, .mo files from the theme. No additional files are required. in my wp-contents/Language contain the theme and plugin folders where the all .po, .mo files are present

so on enabling this plugin all French translations must be verified and confirmed functional before task completion.

Also English strings may appear on French pages if the import is not done properly. The plugin is single-use, not continuous.

Requirement:
Create a one-time plugin that imports all French translations from theme .po files into Polylang’s database.

Site: child of a classic theme
Polylang (free) active
Manual conversion of _() / e() → pll() / pll_e() is already done
Goal: avoid manual errors, ensure translations work correctly in production
Plugin draft (current code):

<?php
/**
 * Plugin Name: Polylang French Translation Importer - DEBUG
 * Description: Debug version to import French translations from .po files into Polylang database
 * Version: 1.3
 * Author: Your Name
 */

if (!defined('ABSPATH')) exit;

class PolylangFrenchImporter {
    private $import_path;

    public function __construct() {
        $this->import_path = WP_CONTENT_DIR . '/languages/themes/';
        add_action('admin_menu', [$this, 'add_admin_page']);
    }

    public function add_admin_page() {
        add_management_page(
            'Polylang Import',
            'Polylang Import',
            'manage_options',
            'polylang-import',
            [$this, 'render_import_page']
        );
    }

    public function render_import_page() {
        if (isset($_POST['run_import'])) {
            $this->run_import();
        }

        echo '<div class="wrap"><h1>Polylang PO Import Debug</h1>';
        echo '<form method="post">';
        submit_button('Run Import', 'primary', 'run_import');
        echo '</form></div>';
    }

    private function run_import() {
        if (!function_exists('pll_get_the_language')) {
            echo '<p style="color:red;">Polylang not active!</p>';
            return;
        }

        require_once ABSPATH . 'wp-admin/includes/translation-install.php';

        $files = glob($this->import_path . '*.po');
        if (!$files) {
            echo '<p style="color:red;">No .po files found in: ' . esc_html($this->import_path) . '</p>';
            return;
        }

        foreach ($files as $file) {
            $locale = basename($file, '.po');
            echo '<h3>Processing: ' . esc_html($locale) . '</h3>';

            $translations = $this->parse_po_file($file);
            if (!$translations) {
                echo '<p style="color:red;">Failed to load PO file or no translations found.</p>';
                continue;
            }

            global $wpdb;
            $table = $wpdb->prefix . 'polylang_strings';

            $count = 0;
            foreach ($translations as $msgid => $msgstr) {
                if (!$msgid || !$msgstr) continue;

                $wpdb->insert($table, [
                    'string'  => $msgid,
                    'context' => 'theme',
                    'name'    => md5($msgid),
                    'value'   => $msgstr,
                    'group'   => 'po-import',
                    'multiline' => 0,
                ]);
                $count++;
            }

            echo '<p style="color:green;">Imported ' . intval($count) . ' strings from ' . esc_html($file) . '</p>';
        }
    }

    private function parse_po_file($file) {
        if (!class_exists('PO')) {
            require_once ABSPATH . 'wp-includes/pomo/po.php';
        }

        $po = new PO();
        $loaded = $po->import_from_file($file);
        if (!$loaded) {
            error_log('Failed to load PO file: ' . $file);
            return false;
        }

        $translations = [];
        foreach ($po->entries as $entry) {
            if (!empty($entry->translations[0])) {
                $translations[$entry->singular] = $entry->translations[0];
            }
        }

        error_log('Parsed ' . count($translations) . ' strings from ' . $file);
        return $translations;
    }
}

new PolylangFrenchImporter();
Error while testing:

PO files are detected (fr_CA.po, en_CA.po) ✅
But import_from_file fails → Failed to load PO file ❌
Results: Strings Found = 0, Strings Imported = 0
Debug log shows PO files exist but cannot be parsed

Getting “page over page” problem in laravel 11+ using inertia react for frontend

I have been struggling with this error for 2 weeks. Project setup is basically simple:

  • docker-compose for building app, redis and mariadb containers
  • nginx on production server for serving app and build assets from react

After a while, especially while submitting login or any POST request handling from react jsx template (using inertia router.post method), it opens up a new window inside current one with redirect.

Here is my login controller method

public function login(Request $request)
{
    $credentials = $request->validate([
        'email' => 'required|email',
        'password' => 'required',
    ]);

    if (Auth::guard('client')->attempt($credentials, $request->boolean('remember'))) {
        $client = Auth::guard('client')->user();

        if ($client->status) {
            $request->session()->regenerate();

            return Inertia::location(route('client.admin'));
        }

        Auth::guard('client')->logout();

        throw ValidationException::withMessages([
            'email' => 'Your account is inactive.',
        ]);
    }

    throw ValidationException::withMessages([
        'email' => 'The provided credentials do not match our records.',
    ]);
}

Attaching screenshots:

plaintext JSON output of login form followed by "Redirecting to" login form with "Email" and "Password" fields, "Remember me" checkbox, and "LOG IN" button

I would appreciate any help in resolving this. Thanks.

Call to undefined function readline()

When i try to write
$choice = readline();
it shows me

Fatal error: Uncaught Error: Call to undefined function readline()

But for other readlines, like $title = readline("Enter title: ") it doesn’t show me errors. What is the cause? I’m using php version 8.4.0

How can i fix it without needing to write longer codes (if possible) ?

I tried to make a do..while loop where there are multiple choices – cases, but it doesn’t seem to like it

do {
    echo "nn";
    echo "1 - show all booksn";
    echo "2 - show a bookn";
    echo "3 - add a bookn";
    echo "4 - delete a bookn";
    echo "5 - quitnn";
    $choice = readline();

    switch ($choice) {
        case 1:
            foreach ($books as $id => $book) {
                displayBook($id, $book);
            }

            break;
        case 2:
            $id = readline("Enter book id: ");
            displayBook($id, $books[$id]);

            break;
        case 3:
            addBook($books);
            break;
        case 4:
            deleteBook($books);
            break;
        case 5:
            echo "Goodbye!n";
            $continue = false;
            break;
        case 13:
            print_r($books); // hidden option to see full $books content
            break;
        default:
            echo "Invalid choicen";
    };

} while ($continue == true);

Laravel installer error – Could not scan for classes vendor/sebastian/code-unit-reverse-lookup/src/ which does not appear to be a file [duplicate]

When trying to create a new Laravel project, the Laravel installer throws the following error:

Could not scan for classes inside "/home/aes256/test/vendor/sebastian/code-unit-reverse-lookup/src/" which does not appear to be a file nor a folder
> pre-package-uninstall: IlluminateFoundationComposerScripts::prePackageUninstall
Script IlluminateFoundationComposerScripts::prePackageUninstall handling the pre-package-uninstall event terminated with an exception

In ComposerScripts.php line 66:

  [ErrorException]
  Constant LARAVEL_START already defined

Re-running the Laravel installer with verbose mode shows the following additional info:

Executing async command (CWD): 'rm' '-rf' '/home/aes256/test/vendor/sebastian/code-unit-reverse-lookup'
Could not scan for classes inside "/home/aes256/test/vendor/sebastian/code-unit-reverse-lookup/src/" which does not appear to be a file nor a folder
> pre-package-uninstall: IlluminateFoundationComposerScripts::prePackageUninstall
Script IlluminateFoundationComposerScripts::prePackageUninstall handling the pre-package-uninstall event terminated with an exception

In ComposerScripts.php line 66:

  [ErrorException]
  Constant LARAVEL_START already defined


Exception trace:
  at /home/aes256/test/vendor/laravel/framework/src/Illuminate/Foundation/ComposerScripts.php:66
 IlluminateFoundationBootstrapHandleExceptions->handleError() at /home/aes256/test/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/HandleExceptions.php:258
 IlluminateFoundationBootstrapHandleExceptions->{closure:IlluminateFoundationBootstrapHandleExceptions::forwardsTo():257}() at n/a:n/a
 define() at /home/aes256/test/vendor/laravel/framework/src/Illuminate/Foundation/ComposerScripts.php:66
 IlluminateFoundationComposerScripts::prePackageUninstall() at phar:///usr/bin/composer/src/Composer/EventDispatcher/EventDispatcher.php:508
 ComposerEventDispatcherEventDispatcher->executeEventPhpScript() at phar:///usr/bin/composer/src/Composer/EventDispatcher/EventDispatcher.php:284
 ComposerEventDispatcherEventDispatcher->doDispatch() at phar:///usr/bin/composer/src/Composer/EventDispatcher/EventDispatcher.php:158
 ComposerEventDispatcherEventDispatcher->dispatchPackageEvent() at phar:///usr/bin/composer/src/Composer/Installer/InstallationManager.php:369
 ComposerInstallerInstallationManager->executeBatch() at phar:///usr/bin/composer/src/Composer/Installer/InstallationManager.php:322
 ComposerInstallerInstallationManager->downloadAndExecuteBatch() at phar:///usr/bin/composer/src/Composer/Installer/InstallationManager.php:221
 ComposerInstallerInstallationManager->execute() at phar:///usr/bin/composer/src/Composer/Installer.php:839
 ComposerInstaller->doInstall() at phar:///usr/bin/composer/src/Composer/Installer.php:649
 ComposerInstaller->doUpdate() at phar:///usr/bin/composer/src/Composer/Installer.php:298
 ComposerInstaller->run() at phar:///usr/bin/composer/src/Composer/Command/UpdateCommand.php:281
 ComposerCommandUpdateCommand->execute() at phar:///usr/bin/composer/vendor/symfony/console/Command/Command.php:298
 SymfonyComponentConsoleCommandCommand->run() at phar:///usr/bin/composer/vendor/symfony/console/Application.php:1040
 SymfonyComponentConsoleApplication->doRunCommand() at phar:///usr/bin/composer/vendor/symfony/console/Application.php:301
 SymfonyComponentConsoleApplication->doRun() at phar:///usr/bin/composer/src/Composer/Console/Application.php:400
 ComposerConsoleApplication->doRun() at phar:///usr/bin/composer/vendor/symfony/console/Application.php:171
 SymfonyComponentConsoleApplication->run() at phar:///usr/bin/composer/src/Composer/Console/Application.php:137
 ComposerConsoleApplication->run() at phar:///usr/bin/composer/bin/composer:98
 require() at /usr/bin/composer:29

Is it something to be concerned about?

Tried a different Linux machine with fresh PHP + Composer install, same error.

edit: trying to create new project using PHPUnit instead of Pest works fine.

Doctrine ORM: Transaction commit fails after rollback in batch loop (Symfony 5.4, PHP 7.4)

I’m running a batch process in Symfony 5.4.48 (PHP 7.4.30, Doctrine ORM 2.20.3) where I need to handle database transactions per iteration. If a business condition fails, I want to rollback the transaction and continue to the next item. However, after a rollback, the next iteration fails with:

Transaction commit failed because the transaction has been marked for rollback only.

Here’s a simplified version of my code:

<?php
foreach ($items as $item) {
    $em = $doctrine->getManager();
    $connection = $em->getConnection();
    $connection->beginTransaction();
    try {
        // ... business logic ...
        if ($shouldRollback) {
            $connection->rollBack();
            $doctrine->resetManager();
            continue;
        }
        $connection->commit();
    } catch (Throwable $e) {
        if ($connection->isTransactionActive()) {
            $connection->rollBack();
        }
        $doctrine->resetManager();
        continue;
    }
}

Even after calling $doctrine->resetManager(), the next $em and $connection seem to be in a “rollback only” state, and commit() fails.

Environment:

  • Symfony: 5.4.48
  • Doctrine ORM: 2.20.3
  • PHP: 7.4.30
  • OS: Windows

What I’ve tried:

  • Resetting the EntityManager with $doctrine->resetManager()
  • Reacquiring the EntityManager and Connection after rollback
  • Checking transaction state with $connection->isRollbackOnly()

Questions:

  • Is this the expected behavior for Doctrine ORM?
  • How can I fully reset the EntityManager/Connection so that the next transaction works?
  • Is there a recommended pattern for batch processing with per-iteration transactions in Doctrine?

What will happen if Node.js cannot read a directory (or a part of a file) due to bad/problematic sectors on disk or corrupted file system?

I want to use the directory- and file-reading functions from 'node:fs' to merge multiple files into one file. For example, I have the following script:

import fs from 'node:fs';
import { readdir, readFile, stat } from 'node:fs/promises';
import { join } from 'node:path';
var myStream = fs.createWriteStream('path/to/output.txt', {flags: 'a'});
var dirPath = 'path/to/mydirectory';
try {
    const entries = await readdir(dirPath, { recursive: true, withFileTypes: true });
    for (const entry of entries) {
        if (entry.isFile()) {
        const myPath = join(entry.parentPath, entry.name);
        const { size } = await stat(myPath);
        const contents = await readFile(myPath);
        myStream.write('<path>' + myPath + '</path>' + '<size>' + size.toString(10) + '</size>n' + contents + 'n');
     }
};
} catch (err) {
    console.error(err);
}; 
myStream.end()

My question is: what will happen if a directory cannot be opened or some part of a file cannot be read (due to bad/problematic sectors on disk, corrupted file system, etc.)? Will the program just freeze, so I will need to terminate it manually? Or only the corresponding file/directory will be skipped? Will the program skip a file in its entirety or only the unreadable part of it? What type of error, if any, will the program report? I have not found any information on this topic. Would it be possible to use Node.js to make the full list of problematic directories and files that are located in a given directory?

How to persist uploaded photos in a multi-step React form across page refresh?

I’m building a multi-step form in React where users can upload photos along with other inputs.

Currently:

I store all the form values in a formData state object.

To persist progress across refreshes, I save formData in localStorage.

Problem:

Uploaded photos are stored using URL.createObjectURL(file).

These object URLs don’t survive a page refresh, so the images are lost even though the rest of the form data is restored from localStorage.

Question:

Is there a way to persist uploaded photos across page refreshes without just dumping everything into localStorage?

What are the common patterns for handling this in React multi-step forms?

Should I use IndexedDB for files?

Should I upload files immediately to a temporary backend storage (and store only the reference in localStorage)?

Or is there another best practice for this use case?