Why does reduce waits for promises sequentially, while forEach does not?

Consider the code:

const promises = [
  new Promise(r => setTimeout(r, 10000, "Hi")),
  new Promise(r => setTimeout(r, 500, "second")),
  new Promise(r => setTimeout(r, 100, "third"))
];
promises.reduce(async (a, promise) => {
  await a;
const p = await promise;
console.log(p);
}, Promise.resolve());

The output of this code is Hi, first, third, despite there is a massive time difference between these three promises.
My thoughts:

In each iteration, the reduce callback returns immediately with a pending promise which resolves synchronously. Therefore, its subsequent async opeerations will wait until the three promises returned by the callback is resolved. But I still don’t think the output should be like this, because those three promises are separate ones – each one creating its own chain of async operation. When the first callback executes, the function immediately resolves with undefined. Then, the async code (the awaiting of promises and the logging of three is defered to the next event cycle – placed into the microtask queue). I think this happens to all three of the promises iterated by reduce.

However, in a forEach loop, the promises are resolved insequentially, even with the following code:

const promises = [
  new Promise(r => setTimeout(r, 10000, "Hi")),
  new Promise(r => setTimeout(r, 500, "second")),
  new Promise(r => setTimeout(r, 100, "third"))
];
promises.forEach(async promise => {
  // try to force the delay of the "promise" in the promises array.
  await 3;
const p = await promise;
console.log(p);
});

The output is second, third, first. Why is this happening?

So why did this happen? I totally expeected someething different

How can I assign an element to have a scaling transformation in percentage relative to the window in react native?

For example, I can achieve the same thing by applying the formula:

const { width } = useWindowDimension();
const porcentage = width * 0.8 (80% of the window);

<ComponentOrElement style={ width: porcentage } />

But this is based on the width (or also the height) of the element, I want to obtain the same but based on the scaling transformation. For example:

const { width } = useWindowDimension();
const porcentage = width * 0.8 (80% of the window?);

<ComponentOrElement style={ transform: [ { scale: porcentage } ] } />

Scaling has a range of 0 to 1 (or more, but it always refers to a factor, not pixels, dp, etc.).

How can I achieve this in scaling?

Predicting direction in a pseudo-random sequence based on the threshold 49

I am working with a sequence of pseudo-random numbers in Python, represented by the ‘sequence’ list, which contains values ranging from 0 to 99:

sequence = [43, 43, 31, 49, 52, 54, 81, 14, 0, 29, 97, 89, 42, 93, 83, 63, 68, 83, 19]

The goal is to develop a Python system that can predict the direction of the next number in the sequence (based on all known records). The direction is defined as follows:

  1. If the next number is less than 49, it is considered a leftward direction.
  2. If the next number is greater than 49, it is considered a rightward direction.

It is important to note that I am not interested in predicting the actual next number in the sequence, but rather the direction in which it would be positioned in relation to the threshold of 49 (the midpoint of the range 0-99).

Various approaches can be proposed in the implementation of this system, ranging from machine learning to advanced mathematical methods. The main objective is to achieve an effectiveness and precision in direction predictions of 97% to 100%, meaning a highly reliable system that can not only predict the direction but do so with a high degree of accuracy.

NOTE: I mention Python because it is a robust and popular language, but implementations in any other programming language are also welcome.

As of now, I haven’t initiated any specific strategies or implementations for the given task. My focus has been on seeking recommendations and suggestions to effectively address the challenge at hand. I am open to various approaches, be it machine learning or advanced mathematical methods, to create a Python system capable of predicting the direction of the next number in the sequence. The ultimate goal is to achieve a high level of accuracy, ideally between 97% to 100%, in predicting the direction, rather than the actual numerical value, based on the defined threshold of 49. Please feel free to provide guidance or propose strategies to enhance the effectiveness and precision of the predictive system.

Finding the sum of Numbers in a string containing letters and numbers using javascript & for loops

I think I’m close to solving this one The goal here is the find the Numbers in the string and add them together to find the sum of them.
there are numbers and letters in the strings in question

instruction:

  • PART 2
  • Create a getStringSum(str) function that returns the sum of any integers that are in the string.
  • Example1: getStringSum(“GH2U87A”) => 17
  • Example2: getStringSum(“GHIUJUHSG”) => 0
  • */

Where I’m at:

   function getStringSum(str) {
    let sum = 0;
     for(let  i = 0; i < str.length; i++){
      if (str[] == typeof Number){
      sum += str[i];
      };
      };
     return sum;
      };

I have my for loop condition set to iterate through the string, but I don’t think my “typeof” proterty is registering the Numbers in the string as numbers, because theyre are within a string, I’m not certain thats the case, but I’m guessing thats whats happening, so my biggest question, is how to re assign the numbers, or identify the numbers in my string, to the value of number . any help or advice / push in the right direction is greatly apprecitated, thank you!!

After form sending Email I recieve just data from input fields, when transition Javascript scripts active

I had tried different variations of this trouble solution, but in result just text inputs sent to email, but elements with “wpforms-selected” class don’t send, when nextformspage.js scripts active on website and everything goes wrong. This scripts active on website https://staging-new.deutsche-thermo.de/mobile-heizung-lp-2/ , which have developed on wordpress. In this case I can edit just forms.js, nextformspage.js and functions.php files. So how can I fix this codes and error in website?

Here is last version of forms.js file in website

const wpForm = document.querySelector('.lindenfield-step-form-v1');
const choiceItems = document.querySelectorAll('.lindenfield-step-form-v1 .wpforms-image-choices-item');
const wpformsPage = document.querySelectorAll('.lindenfield-step-form-v1 .wpforms-page');
const wpformsLastPage = document.querySelectorAll('.lindenfield-step-form-v1 .wpforms-page.last.wpform-footer-btns');
const wpformButtonNext = document.querySelectorAll('.lindenfield-step-form-v1 .wpforms-page-next');
const wpformButtonBack = document.querySelectorAll('.lindenfield-step-form-v1 .wpforms-page-prev');
const wpformsButtonSubmit = document.querySelector('.lindenfield-step-form-v1 .wpforms-submit');
const wpformsFields = document.querySelectorAll('.lindenfield-step-form-v1 .wpforms-field');
const wpformsTextFields = document.querySelectorAll('.lindenfield-step-form-v1 .wpforms-field.wpforms-field-text');
const wpformsRequiredField = document.querySelectorAll('.lindenfield-step-form-v1 .wpforms-field-required');
const wpformsIndicatorWrap = document.querySelector('.lindenfield-step-form-v1 .wpforms-page-indicator-page-progress-wrap');
const wpformsIndicatorProgress = document.querySelector('.lindenfield-step-form-v1 .wpforms-page-indicator-page-progress');
const wpformsIndicatorContainer = document.createElement('div');
wpformsIndicatorContainer.className = 'wpforms-page-indicator-container';
wpformsIndicatorProgress.appendChild(wpformsIndicatorContainer);
const wpformsIndicatorText = document.createElement('div');
wpformsIndicatorText.className = 'wpforms-page-indicator-text';
wpformsIndicatorContainer.appendChild(wpformsIndicatorText);
const wpformsIndicatorProgressWidth = Math.round(parseFloat(wpformsIndicatorProgress.style.width));
wpformsIndicatorText.innerText = wpformsIndicatorProgressWidth + '% geschaft';
//current page index
let currentPageIndex = 0;

for (var item = 0; item < choiceItems.length; item++) {
    const choiceItemOnHover = document.createElement('div');
    choiceItemOnHover.className = "wpforms-choices-header-onhover";
    const label = choiceItems[item].querySelector('.lindenfield-step-form-v1 .wpforms-image-choices-label');
    choiceItemOnHover.innerText = label ? label.innerText : '';
    choiceItems[item].append(choiceItemOnHover);
}

showButton();

function showButton() {
    wpformButtonNext.forEach((button, index) => {
        const page = wpformsPage[index];
        if (page.getAttribute('data-page')) {
            const selectedItems = page.querySelectorAll(`.lindenfield-step-form-v1 .wpforms-image-choices-item.wpforms-selected`);
            if (selectedItems.length === 0) {
                button.style.visibility = 'hidden';
            } else {
                button.style.visibility = 'visible';
            }
        } else {
            button.style.visibility = 'hidden';
        }
    });
}

function progressNext() {
    const totalPages = wpformsPage.length;
    currentPageIndex = Array.from(wpformsPage).indexOf(this.closest('.lindenfield-step-form-v1 .wpforms-page'));

    if (currentPageIndex === totalPages - 2 || currentPageIndex === totalPages - 1) {
        const actualPercentValue = '95%';
        wpformsIndicatorProgress.style.width = actualPercentValue;
        wpformsIndicatorText.innerText = wpformsIndicatorProgress.style.width + ' - Fastgeschafft';
        wpformsIndicatorText.setAttribute('data-progress-width', wpformsIndicatorProgressWidth);
        /* const screenWidth = window.innerWidth;
        if (screenWidth <= 768) {
            wpformsIndicatorText.style.right = '-20px';
        } else {
            wpformsIndicatorText.style.right = '-40px';
        } */
        wpForm.style.backgroundColor = 'white';

    } else {
        const pixelProgressWidth = window.getComputedStyle(wpformsIndicatorProgress).getPropertyValue('width');
        const currentIndicatorWidth = window.getComputedStyle(wpformsIndicatorWrap).getPropertyValue('width');
        const percentageValue = Math.round((parseFloat(pixelProgressWidth) / parseFloat(currentIndicatorWidth)) * 100);
        const actualPercentValue = wpformsIndicatorProgressWidth + percentageValue;
        wpformsIndicatorText.innerText = actualPercentValue + '% geschafft';
        wpformsIndicatorText.setAttribute('data-progress-width', wpformsIndicatorProgressWidth);
    }
    showButton();
    buttonDetect();
}

function progressBack() {
    const pixelProgressWidth = window.getComputedStyle(wpformsIndicatorProgress).getPropertyValue('width');
    const currentIndicatorWidth = window.getComputedStyle(wpformsIndicatorWrap).getPropertyValue('width');
    const percentageValue = Math.round((parseFloat(pixelProgressWidth) / parseFloat(currentIndicatorWidth)) * 100);
    const actualPercentValue = wpformsIndicatorProgressWidth - percentageValue;
    wpformsIndicatorText.innerText = -actualPercentValue + '% geschafft';
    showButton();
}

function addSelected(event) {
    const clickedChoiceItem = event.currentTarget;
    const currentPage = clickedChoiceItem.closest('.wpforms-page');
    const choiceItemsOnPage = currentPage.querySelectorAll('.wpforms-image-choices-item');
    choiceItemsOnPage.forEach(item => item.classList.remove('wpforms-selected'));
    clickedChoiceItem.classList.add('wpforms-selected');
    progressNext.call(clickedChoiceItem);
}

if (choiceItems) {

    for (var i = 0; i < wpformButtonNext.length; i++) {
        wpformButtonNext[i].addEventListener('click', progressNext);
    }
    for (var i = 0; i < wpformButtonBack.length; i++) {
        wpformButtonBack[i].addEventListener('click', progressBack);
    }
    for (var i = 0; i < choiceItems.length; i++) {
        choiceItems[i].addEventListener('click', addSelected);
    }

} else {
    console.error('wpformButtonNext not found');
}

wpformsButtonSubmit.innerText = 'Angebote erhalten';

function checkFields(page) {
    const textFields = page.querySelectorAll('.wpforms-field.wpforms-field-text input');
    const requiredFields = page.querySelectorAll('.wpforms-field-required input');

    let anyFieldEmpty = false;

    textFields.forEach((field) => {
        if (field.value.trim() === '') {
            anyFieldEmpty = true;
        }
    });

    requiredFields.forEach((field) => {
        if (field.value.trim() === '') {
            anyFieldEmpty = true;
        }
    });

    if (anyFieldEmpty === true) {
        wpformsButtonSubmit.disabled = true;
    } else {
        wpformsButtonSubmit.disabled = false;
    }

}

function buttonDetect() {
    if (wpformsButtonSubmit) {
        if (currentPageIndex < wpformsPage.length - 1) {
            const nextPage = wpformsPage[currentPageIndex + 1];

            nextPage.addEventListener('input', () => checkFields(nextPage));

            checkFields(nextPage);
        } else {
            console.log('No next page found');
        }
    }
}

document.addEventListener("DOMContentLoaded", function () {
    const screenWidth = window.innerWidth;
    
    if (screenWidth <= 768) {
        if (wpformsIndicatorProgressWidth <= 20) {
            wpformsIndicatorText.style.right = '-100px';
            wpformsIndicatorText.innerText = wpformsIndicatorProgressWidth + '% geschafft';
        } else if (wpformsIndicatorProgressWidth >= 20) {
            console.log("s17");
            wpformsIndicatorText.style.right = '-75px';
        } else if (wpformsIndicatorProgressWidth >= 80) {
            wpformsIndicatorText.style.right = '-20px';
        }
    }


    const firmaInput = document.querySelector('.wpforms-input-firma');
    const nameInput = document.querySelector('.wpforms-input-name');
    const plzInput = document.querySelector('.wpforms-input-plz');
    const phoneInput = document.querySelector('.wpforms-input-telefon');
    const errorText = document.querySelector('.wpforms-error');

    // Till here everything is okay

    function validateFirmaInput() {
        const maxLength = 39;
        const trimmedValue = trimInputValue(firmaInput);

        if (trimmedValue.length > maxLength) {
            firmaInput.value = trimmedValue.slice(0, maxLength);
        } else {
            const sanitizedValue = trimmedValue.replace(/[^A-Za-z()s]/g, '');
            firmaInput.value = sanitizedValue;
        }
    }

    function validateNameInput() {
        const maxLength = 39;
        const trimmedValue = trimInputValue(nameInput);

        if (trimmedValue.length > maxLength) {
            nameInput.value = trimmedValue.slice(0, maxLength);
        }

        const sanitizedValue = trimmedValue.replace(/[^A-Za-z()s]/g, '');
        nameInput.value = sanitizedValue;
    }

    function validatePlzInput() {
        const value = trimInputValue(plzInput);
        const sanitizedValue = value.replace(/[^0-9]/g, '');

        if (sanitizedValue.length > 5) {
            plzInput.value = sanitizedValue.slice(0, 5);
        } else {
            plzInput.value = sanitizedValue;
        }
    }

    function validatePhoneInput() {
        const value = trimInputValue(phoneInput);
        const maxLength = 17;

        if (value.length > maxLength) {
            phoneInput.value = value.slice(0, maxLength);
        }
    }

    firmaInput.addEventListener('input', validateFirmaInput);
    nameInput.addEventListener('input', validateNameInput);
    plzInput.addEventListener('input', validatePlzInput);
    phoneInput.addEventListener('input', validatePhoneInput);

    nameInput.addEventListener('keypress', function (e) {
        const charCode = (e.which) ? e.which : event.keyCode;
        const allowedChars = /[A-Za-z()s]/;
        const char = String.fromCharCode(charCode);

        if (!char.match(allowedChars)) {
            e.preventDefault();
        }
    });

    plzInput.addEventListener('keypress', function (e) {
        const charCode = (e.which) ? e.which : event.keyCode;
        const allowedChars = /[0-9]/;
        const char = String.fromCharCode(charCode);

        if (!char.match(allowedChars)) {
            e.preventDefault();
        }
    });

    phoneInput.addEventListener('keypress', function (e) {
        const charCode = (e.which) ? e.which : event.keyCode;
        const allowedChars = /[0-9,*+()-_s]/;
        const char = String.fromCharCode(charCode);
        if (!char.match(allowedChars)) {
            e.preventDefault();
        }
    });

    function trimInputValue(input) {
        if (input && input.value) {
            return input.value.replace(/^s+|s+$/g, '');
        }
        return '';
    }

    function checkFields(page) {
        const textFields = page.querySelectorAll('.wpforms-field.wpforms-field-text input');
        const requiredFields = page.querySelectorAll('.wpforms-field-required input');

        let anyFieldEmpty = false;

        textFields.forEach((field) => {
            if (field.value.trim() === '') {
                anyFieldEmpty = true;
            }
        });

        requiredFields.forEach((field) => {
            if (field.value.trim() === '') {
                anyFieldEmpty = true;
            }
        });

        const isValidName = validateNameInput();
        const isValidFirma = validateFirmaInput();
        const isValidPlz = validatePlzInput();
        const isValidPhone = validatePhoneInput();

        if (anyFieldEmpty === true || !isValidName || !isValidFirma || !isValidPlz || !isValidPhone) {
            wpformsButtonSubmit.disabled = true;
        } else {
            wpformsButtonSubmit.disabled = false;
        }
    }

    wpformsPage.forEach(function (page) {
        page.addEventListener('input', () => checkFields(page));
    });

    // Initialize field validation on page load
    checkFields(wpformsPage[0]);
});

And here is nextformspage.js file, where had wrotten scripts for transition

var isClickAllowed = true;

function addTransitionClass() {
    wpformsPage.forEach(function (page) {
        page.classList.add("anim-trans");
    });

    wpformsIndicatorProgress.classList.add("anim-bar");

    setTimeout(function () {
        wpformsPage.forEach(function (page) {
            page.classList.remove("anim-trans");
        });
        wpformsIndicatorProgress.classList.remove("anim-bar");
    }, 1000);
}

choiceItems.forEach(function (item) {
    item.addEventListener("click", function (event) {
        event.preventDefault();
        if (isClickAllowed) {
            isClickAllowed = false;
            var closestPage = item.closest('.wpforms-page');
            var nextPageButton = closestPage.querySelector('.wpforms-page-next');
            nextPageButton.click();
            addTransitionClass();
            setTimeout(function () {
                isClickAllowed = true;
            }, 100);
        }
    });
});

function handleButtonClick(button) {
    button.addEventListener("click", function () {
        if (isClickAllowed) {
            isClickAllowed = false;
            addTransitionClass();
            setTimeout(function () {
                isClickAllowed = true;
            }, 100);
        }
    });
}

choiceItems.forEach(function (item) {
    handleButtonClick(item);
});

wpformButtonNext.forEach(function (item) {
    handleButtonClick(item);
});

wpformButtonBack.forEach(function (item) {
    handleButtonClick(item);
});
<?php
/**
 * GeneratePress.
 *
 * @package GeneratePress
 */

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly.
}

require_once('session.php');
require_once('tracking.php');
require_once('lead.php');
require_once('regional.php');
require_once('wpsl.php');
require_once('regional_sitemap.php');

/*
 * Add Actions
 */
remove_action('wp_head', 'print_emoji_detection_script', 7);
remove_action('wp_print_styles', 'print_emoji_styles');
add_action('wp_print_scripts', 'fg1_dequeue_scripts', 100);
add_action('wp_print_styles', 'fg1_dequeue_styles', 100);
add_action('wp_head', 'fg1_ajax_url_nonce');

add_action('wp_enqueue_scripts', 'custom_enqueue_styles_and_scripts');
add_action('wp_enqueue_scripts', 'forms_scripts');

add_action('enqueue_block_editor_assets', function () {
    wp_enqueue_style('local-fonts', "/wp-content/themes/generatepress-child/style.css", false, '1.0', 'all');
});


//login cookie secure
add_action('init', 'lf_wp_login_cookie_secure', 10);
function lf_wp_login_cookie_secure()
{

    if (strpos($_SERVER['REQUEST_URI'], 'wp-login.php') !== false) {
        if (!isset($_COOKIE['lm_wp_login_secure']) or $_COOKIE['lm_wp_login_secure'] != "TSvrEQHnzVaoriNmM5Sb") {
            header("HTTP/1.0 403 Forbidden");
            exit();
        }
    }
}

function custom_enqueue_styles_and_scripts()
{
    wp_enqueue_script('custom-js', '/wp-content/themes/generatepress-child/style.js', array('jquery'), '1.0.0', true);
}

function forms_scripts()
{
    wp_enqueue_script('nextformpage-js', '/wp-content/themes/generatepress-child/nextformpage.js', array('jquery'), '1.0.0', true);
    wp_enqueue_script('forms-js', '/wp-content/themes/generatepress-child/forms.js', array('jquery'), '1.0.0', true);
}

/**
 * Modify the required field indicator
 *
 * @link https://wpforms.com/developers/how-to-change-required-field-indicator/
 */
 
 function wpf_dev_required_indicator( $text ) {
 
    return ' <span class="wpforms-required-label">' . __( ' ', 'wpforms' ) . '</span>';
}
 
add_filter( 'wpforms_get_field_required_label', 'wpf_dev_required_indicator', 10, 1 );

//End Modify

function fg1_dequeue_scripts()
{
    $wp_scripts = wp_scripts();
    if (isset($wp_scripts->registered['lazyload-youtube-js'])) {
        $wp_scripts->registered['lazyload-youtube-js']->src = '/wp-content/themes/generatepress-child/lazyload-youtube.js';
    }
}

function fg1_dequeue_styles()
{
    //wp_dequeue_style( 'aawp-styles' );
}

function fg1_ajax_url_nonce()
{
    ?>
    <script type="text/javascript">
        var ajaxurl = '<?php echo admin_url("admin-ajax.php"); ?>';
        var ajaxnonce = '<?php echo wp_create_nonce("itr_ajax_nonce"); ?>';
    </script>
    <?php
}


/** 
 * Removes empty paragraph tags from shortcodes in WordPress.
 */
function tg_remove_empty_paragraph_tags_from_shortcodes_wordpress($content)
{
    $toFix = array(
        '<p>[' => '[',
        ']</p>' => ']',
        ']<br />' => ']'
    );
    return strtr($content, $toFix);
}
add_filter('the_content', 'tg_remove_empty_paragraph_tags_from_shortcodes_wordpress');

function set_cache_value($cache_key, $cache_value)
{

    global $wpdb;

    $cache_value_db = $wpdb->get_row($wpdb->prepare("SELECT cache_value FROM fg1_cache WHERE cache_key = %s LIMIT 1;", array($cache_key)));

    if (!empty($cache_value_db)) {
        $wpdb->query($wpdb->prepare("UPDATE fg1_cache SET cache_value = '" . $cache_value . "' WHERE cache_key = %s LIMIT 1;", array($cache_key)));
    } else {
        $wpdb->insert('fg1_cache', array("cache_key" => $cache_key, "cache_value" => $cache_value));
    }
}

function get_cache_value($cache_key)
{

    global $wpdb;

    $ret = false;
    $cache_value = $wpdb->get_row($wpdb->prepare("SELECT cache_value FROM fg1_cache WHERE cache_key = %s LIMIT 1;", array($cache_key)));
    if (!empty($cache_value))
        $ret = $cache_value->cache_value;

    return $ret;
}

add_action('init', 'custom_lazyload_youtube_proxy', 10, 0);
function custom_lazyload_youtube_proxy()
{

    global $wp;

    if (strpos($_SERVER['REQUEST_URI'], '/ythumb/') !== false) {
        $src = $_GET['src'];
        if (substr($src, 0, 23) == 'https://i2.ytimg.com/vi') {
            header('Content-Type: image/jpeg');
            readfile($src);
        }
        exit();
    }
}

add_action('rest_api_init', 'custom_rest_api_init');

function custom_rest_api_init()
{

    register_rest_route(
        'lc/v1',
        '/get_all_wpforms/',
        array(
            'methods' => 'GET',
            'callback' => 'get_all_wpforms'
        )
    );

}

function get_all_wpforms()
{

    $args = array(
        'numberposts' => -1,
        'post_type' => 'wpforms'
    );

    $wpforms_posts = get_posts($args);

    return $wpforms_posts;
}
function display_year()
{
    $year = date('Y');
    return $year;
}
add_shortcode('year', 'display_year');

add_shortcode('month', 'display_month');

function display_month()
{
    $monatsnamen = array(
        1 => "Januar",
        2 => "Februar",
        3 => "März",
        4 => "April",
        5 => "Mai",
        6 => "Juni",
        7 => "Juli",
        8 => "August",
        9 => "September",
        10 => "Oktober",
        11 => "November",
        12 => "Dezember"
    );
    $monat = date('n');
    return $monatsnamen[$monat];
}

function add_search_box($items, $args)
{
    $items .= '<li>' . get_search_form(false) . '</li>';
    return $items;
}

add_filter('wp_nav_menu_topmenue_items', 'add_search_box', 10, 2);

add_filter('generate_search_placeholder', 'test_suche');
function test_suche()
{
    return 'Wonach suchen Sie?';
}

add_filter('pre_get_posts', 'SearchFilter');
function SearchFilter($query)
{
    if ($query->is_search) {
        $query->set('post__not_in', array(2, 129, 288, 425, 432, 594, 710, 885, 892, 1027, 1068, 1078, 1081, 1237, 1230, 1308, 1310, 1362, 1364, 1433, 2498, 3412, 3415, 3417, 3420, 3422, 3424, 4037, 7234, 7236, 7272, 7283, 7298, 7240, 7505, 7695, 8480, 8939, 9562, 10632, 10691, 10702, 10713, 10730, 10763, 10771, 10799, 10805, 10817, 10821, 10824, 10830, 10834, 10857, 11316, 11424, 11432, 11434, 12331));
    }

    return $query;
}

function limit_author_posts_per_page($query)
{
    if ($query->is_author()) {
        $query->set('posts_per_page', 6);
    }
    return $query;
}
add_filter('pre_get_posts', 'limit_author_posts_per_page');

//WPforms Spam Schutz Token Gültigkeit erhöhen, sodass das Formular länger gecached und mit Spam-Schutz funktioniert
add_filter('wpforms_form_token_check_before_today', 'lf_wpforms_form_token_check_before_today');
function lf_wpforms_form_token_check_before_today($valid_token_times_before)
{
    $valid_token_times_before = [];
    $valid_days_ago = 100;

    for ($i = 1; $i <= $valid_days_ago; $i++) {
        $valid_token_times_before[] = ($i * 86400);
    }

    return $valid_token_times_before;
}

function last_modified_shortcode()
{
    $date_format = 'd.m.Y';
    $last_modified = get_the_modified_date($date_format);
    return $last_modified;
}
add_shortcode('last_modified', 'last_modified_shortcode');

I want solve this problem, and in result recieve data from all elements with ‘wpforms-selected’ class in email

Recursively transform object and nested objects in javascript

How can the below object be recursively transformed, including nested objects, by removing all edges and nodes? Note that the structure is always the same, meaning edges will always be an array of nodes.

const data = {
  products: {
    edges: [
      {
        node: {
          title: 'x',
          collections: {
            edges: [
              {
                node: {
                  title: 'x - collection'
                }
              }
            ]
          }
        }
      }
    ]
  }
}

I have a helper function removeEdgesAndNodes

function removeEdgesAndNodes(obj) {
  return obj.edges.map(edge => edge?.node)
}

removeEdgesAndNodes(data.products)

Expected Output

[
  {
    title: 'x',
    collections: [
      {
        title: 'x-collection'
      }
    ]
  }
]

NOTE: It is not uncommon for queries to be nested even further, although it does not often go past three levels deep.

const data = {
  products: {
    edges: [
      {
        node: {
          title: 'x',
          collections: {
            edges: [
              {
                node: {
                  title: 'x - collection',
                  products: {
                    edges: [
                      {
                        node: {
                          title: 'product in x collection'
                        }
                      }
                    ]
                  }
                }
              }
            ]
          }
        }
      }
    ]
  }
}

Dropdown & checkbox filters are not populating from dynamically generated html table sourced from local MySQL database

I cant figure out why the dropdown or checkbox filters are not populating from my html table for the chart I’m using.

I’m using bootstrap & vanilla javascript to create an interactive chart based on data from an html table that is sourced from my local MySQL database. I’m trying use checkbox filters and dropdown menu filters to filter the data from the html table. I’m trying to get the filters to auto populate based on column 2 & column 10 on my table, however I can’t get the data to populate.

I’ve tried running this through GPT 3.5, GPT 4, and Grimoire and I’ve had no luck with all of their suggestions. They say it’s probable that the table is loading after the filters are, which would cause the filters to not populate. I’ve tried using the DOMContentLoaded function, and using the $.ajax({ url: ‘http://localhost:3001/getData’ and the .trim() method as well but no luck.

The strange thing is, when select the date range to filter my data to reflect on the chart, it works. When I use the filters on the datasets built into the table they work too.

hydration error in nexjts when using the div tag instead of the main tag

I’ve encountered the hydration error in nextjs and on debugging I found that when I use the div tag instead of the main tag then it causes this issue.

The error that I get

enter image description here
Below is the code that caused the error

import React from "react";
import Image from "next/image";

type Props = {};

const LearnTesting = (props: Props) => {
  return (
    <div>
      <h1>Learn Testing</h1>
    </div>
  );
};

export default LearnTesting;

Below is the code that runs flawlessly

import React from "react";
import Image from "next/image";

type Props = {};

const LearnTesting = (props: Props) => {
  return (
    <main>
      <h1>Learn Testing</h1>
    </main>
  );
};

export default LearnTesting;

You can see the only difference is the usage of the div tag instead of the main tag causing the hydration error.

While going through the documentation I don’t see an explanation related to the usage of semantic tags or anything related. It only mentions incorrect nesting of tags. Maybe I’m missing something?

How to import all font types inside a variable font file in React Native

I am a beginner to React Native, and have been fooling around with a project created with expo. I am using the expo-font library with the useFonts hook to import a ttf variable font. The issue I am having is that it only imports one type of font and not all of them. I read through the docs of expo but it says nothing about variable font files.
This is how I’m importing the fonts:

import { StyleSheet, Text, View } from 'react-native';
import {useFonts} from "expo-font";
import * as SplashScreen from 'expo-splash-screen';
import { useCallback } from 'react';

SplashScreen.preventAutoHideAsync();

export default function App() {

  const [fontsLoaded, fontError] = useFonts({
    "Quicksand" : require('./assets/fonts/Quicksand/Quicksand-VariableFont_wght.ttf')
  });

  const onLayoutRootView = useCallback(async () => {
    if (fontsLoaded || fontError) {
      await SplashScreen.hideAsync();
    }
  }, [fontsLoaded, fontError]);

  if (!fontsLoaded && !fontError) {
    return null;
  }

  return (
    <View style={styles.container} onLayout={onLayoutRootView}>
      <Text style={styles.text}>Open up App.js to start working on your app!</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  text: {
    fontFamily: "Quicksand",
    fontSize: 50,
  }
});

Is there a way to import all of the font types and weights from the variable fonts file instead of having to import the static fonts one by one?
Thanks in advance!

Failed to resolve entry for package “appwrite”. The package may have incorrect main/module/exports specified in its package.json. error

Was working on the react app and used appwrite as my backend but it is giving me the following error;

** Failed to resolve entry for package “appwrite”. The package may have incorrect main/module/exports specified in its package.json.**

enter image description here

All I have done in the file which referred by the error (auth.js) is used some appwrite function for creating authorization. Here is the code below for that file,

`import conf from ‘./config’;
import { Client, Account, ID } from “appwrite”;

export class AuthService {

client = new Client();
Account;

constructor() {
    this.client
        .setEndpoint(conf.appwriteURL)
        .setProject(conf.projectID);

    this.Account = new Account(this.client)
}

async createAccount({ email, password, name }) {
    try {

        const userAccount = await this.Account.create(ID.unique(), email, password, name);

        if (userAccount) {
            // call other methd
            return this.login(email, password);
        }
        else {
            return userAccount;
        }
    } catch (error) {
        console.log(`Appwrite error: createAccount() :: ${error}`)

    }
}

async login(email, password) {
    try {
        return await Account.createEmailSesson(email, password);
    } catch (error) {
        console.log(`Appwrite error: login() :: ${error}`)

    }
}

async getCurrentUser() {
    try {

        return this.Account.get();

    } catch (error) {
        console.log(`Appwrite error: getCurrentUser() :: ${error}`)
    }

    return null;
}

async logOut(){
    try {

        return this.Account.deleteSessions();

    } catch (error) {
        console.log(`appwrite :: logOut() : ${error}`)
    }
}

}

const authService = new AuthService();

export default authService;`

Though I have provided all the code related to the file the error reffering to, I don’t really think the problem is more about the code. I think there is some problem in installing or importing the appwrite.

Simplest way to use Google Sheets API with a basic website?

I’m building out my wedding website

The goal is to have a Google sheet as my “database” for guest list.

With columns for: First name, last name, attendance, a timestamp for each change of RSVP, and an invite code.

Problem is it feels like it’s becoming over complicated. Seems the API requires an OAuth2.0 to be able to access the sheet and to edit it, etc.

What’s the simplest method here? My hope would be: I can use an express server to make all the API calls on behalf of the React website.

I’ve tried simply using an API key, but ran into “The caller does not have permission” errors in my Insomnia testing, which led me to find out that since 2015, Google APIs require users to identify themselves to be used.

I don’t want end users to have to Google Auth themselves on the site, it should be a simple site where they need only Submit their invite code and RSVP status.

Is it possible for me to essentially give OAuth2.0 clearance to my express server (.env hidden client_ids and client_secrets of course) so that it just works on it’s own indefinitely?

Password Field Modification with React

I am trying to build a new kind of password field, the differentiating factor would be when moving the text-cursor in the password field, it should unmask the character at the same index as the text cursor. I have tried various methods but couldn’t quite build it. Can someone help?

I have tried a text field and masking it with css, and it works but not entirely.

Vue Prism Component: Text or Code from Database Not Wrapping, How to Enable Word Wrap or Adjust Width/Height Dynamically?

I want to make a code highlighting component using prism:

<template>
  <!-- <prism language="javascript"> {{ code }}</prism> -->
  <prism language="javascript" v-html="code"> </prism>
</template>

<script setup>
import { ref } from 'vue'
import 'prismjs'
import 'prismjs/themes/prism.css'
import Prism from 'vue-prism-component'
const props = defineProps(['code'])
// const code = ref('const a = b')
</script>

<style lang="scss" scoped></style>

to this component sometimes is delivered a code and sometimes a text from database.
For example text like this:

<p>A Promise is an object representing the eventual completion or failure of an asynchronous operation. Essentially, a promise is a returned object to which you attach callbacks, instead of passing callbacks into a function.</p>

since it has no n it is very wide and the text doesnt wrap. It works like here, it gets scroll instead of wrapping down and increasing the height. Normal wrapping behavior, or changng the width or height is impossible. How to make a text or code behave like a text if it comes from db without whitespaces, so they wrap and increase height, instead of getting a scroll?

Scroll behavior, like here on StackOverflow is bad. I want it to wrap.

My Glsl shaders are not loading on Liveserver or Github pages

I’m still new at web development, and have been working on using 3D images in a web page. On a particular project I am using .glsl files to load textures and shaders. When I run my code locally everything works fine but when I attempt to view on a live server I get the following error.

enter image description here

I’m not sure how to interpret this but i came into a similar error on another project where i tried to access gsap from my node modules. To solve that i had to implement a script directly into my html file, a CDN of some sorts.

<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.11.4/gsap.min.js"></script>

So, is there a something similar for .glsl files or is there a more permanent solution for these kind of errors.

PS. The project is a simple HTML, CSS, JS (Albeit ThreeJS)

How to mock functions in Jest

I have 2 simple components. I am writing tests for them using jest. I want to test when I click on currencyItem, the respective array should be added to the select state. As you can see I am passing handleCurrencyToggle function as props to the currencyItem hence I want to mock it in jest test too.

CurrencySelector.tsx

import { useEffect, useState } from "react";
import { currencies } from "../constants";
import { Currency } from "../types";
import CurrencyItem from "./CurrencyItem";

const CurrencySelector = () => {
  const initialSelected = () => {
    const storedCurrencies = sessionStorage.getItem("currencies");
    return storedCurrencies ? JSON.parse(storedCurrencies) : [];
  };

  const [selected, setSelected] = useState<Currency[]>(initialSelected);

  const handleCurrencyToggle = (currency: Currency) => {
    const isSelected = selected.some(
      (selectedCurrency) => selectedCurrency.name === currency.name
    );

    if (isSelected) {
      setSelected((prevSelected) =>
        prevSelected.filter(
          (selectedCurrency) => selectedCurrency.name !== currency.name
        )
      );
    } else {
      setSelected((prevSelected) => [...prevSelected, currency]);
    }
  };

  useEffect(() => {
    sessionStorage.setItem("currencies", JSON.stringify(selected));
  }, [selected]);

  return (
    <div className="currency-selector">
      <div className="selected-currencies currency-items">
        {selected.length > 0 ? (
          selected.map((currency: Currency, index: number) => (
            <div
              data-testid="selected-currency"
              key={index}
              className="selected-currency currency"
            >
              <span>{currency.name}</span>
              <button
                className="unselect-currency"
                onClick={() => handleCurrencyToggle(currency)}
              >
                x
              </button>
            </div>
          ))
        ) : (
          <div data-testid="no-selected-currencies" className="no-currencies">
            No selected currencies
          </div>
        )}
      </div>
      <div className="currency-items">
        {currencies.map((currency: Currency, index: number) => (
          <CurrencyItem
            data-testid={`currency-item-${index}`}
            key={index}
            currency={currency}
            onClick={() => handleCurrencyToggle(currency)}
            isSelected={selected.some(
              (selectedCurrency) => selectedCurrency.name === currency.name
            )}
          />
        ))}
      </div>
    </div>
  );
};

export default CurrencySelector;

CurrencyItem.tsx

import { Currency } from "../types";

const CurrencyItem = ({
  currency,
  onClick,
  isSelected,
}: {
  currency: Currency;
  onClick: () => void;
  isSelected: boolean;
}) => {
  const handleCheckboxChange = () => {
    onClick();
  };

  return (
    <div data-testid="currency-item" onClick={onClick} className="currency">
      <label>
        <input onChange={handleCheckboxChange} checked={isSelected} type="checkbox" />
        <span className="checkbox-container"></span>
      </label>
      <span>{currency.name}</span>
    </div>
  );
};

export default CurrencyItem;

currency array:

import { Currency } from "../types";

export const currencies: Currency[] = [
  {
    name: "EUR",
  },
  {
    name: "PLN",
  },
  {
    name: "GEL",
  },
  {
    name: "DKK",
  },
  {
    name: "CZK",
  },
  {
    name: "GBP",
  },
  {
    name: "SEK",
  },
  {
    name: "USD",
  },
  {
    name: "RUB",
  },
];

my test:

  it("adds currency to select list", () => {
    const handleCurrencyToggle = jest.fn()
    const { getByTestId: getByTestId2 } = render(
        <CurrencySelector />
      );
    const { getByTestId } = render(
      <CurrencyItem
        key={1}
        currency={currencies[0]}
        onClick={() => () => {
          handleCurrencyToggle();
        }}
        isSelected={true}
      />
    );
    
    const currencyItem = getByTestId("currency-item");
    fireEvent.click(currencyItem);

    const selectItem = getByTestId2("selected-currency").textContent
    expect(selectItem).toBe("EUR");
  });
});

I know it’s not correct but please guide me how can I mock the real handleCurrencyToggle function.