the code is completely ignoring weight/ distance / speed in my caloric calculation [closed]

This calorie calculator is ignoring all the input boxes, and the button only works once. I’m using the formula:

calories = weight * MET * distance

Speed is supposed to affect MET, but it doesn’t seem to. Also, the button becomes unresponsive after one click. Here’s all the JavaScript I’m using:

document.getElementById("distance");
document.getElementById("speed");
document.getElementById("Calories");
document.getElementById("submit");
document.getElementById('weight');

const weightInput = document.getElementById('weight');
const distanceInput = document.getElementById("distance");
const speedInput = document.getElementById("speed");
const caloriesInput = document.getElementById('Calories');
const submitButton = document.getElementById('submit');

const weightValue = (weightInput) => {
    return parseFloat(weightInput.value);
}

const distanceValue = (distanceInput) => {
    return parseFloat(distanceInput.value);
};

const speedValue = (speedInput) => {
    return parseFloat(speedInput.value);
};

function getMet(exerciseType) {
    let multiplier;
    switch (exerciseType.toLowerCase()) {
        case 'walking':
            multiplier = 3.5;
            break;
        case 'running':
            multiplier = 7.0;
            break;
        case 'biking':
            multiplier = 6.8;
            break;
        case 'swimming':
            multiplier = 5.8;
            break;
        default:
            multiplier = 4.0;
    }
    return multiplier;
}

function computeCal(weight, met, distance) {
    return weight * met * distance;
}

const clicking = (event) => {
    event.preventDefault();
    const distance = distanceValue(distanceInput);
    const speed = speedValue(speedInput);
    const weight = weightValue(weightInput);
    const exercise = document.getElementById("exercise-type").textContent;
    console.log("Distance:", distance);
    console.log("Speed:", speed);
    console.log("Exercise Type:", exercise);
    const met = getMet(exercise);
    const calories = computeCal(weight, met, distance);
    caloriesInput.textContent = `Calories Burned : ${calories.toFixed(2)}`;
}

submitButton.addEventListener("click", clicking);

Data not fetching on initial load, only after backend restart [closed]

I’m working on a project using Next.js for the frontend and Fastify with Prisma ORM for the backend. I’m encountering a strange issue
Problem:
When I start the frontend (Next.js), it fails to fetch data from the backend (Fastify).

After I manually restart or refresh the backend, the data starts fetching correctly.

This happens every time I restart the frontend without touching the backend—the data doesn’t load until I refresh the backend.

Tech Stack:
Frontend: Next.js

Backend: Fastify + Prisma

Why might the frontend not fetch data on the initial load?

How to modify data before resolving a promise in Javascript

I have a database with text entries.
I want to search for the city name, and return the country.

I have an async function which returns a thenable promise.

getText('New').then(alert(result));

After an await on a 2nd function, I want to resolve the promise with one item from the object found. i.e. TheText .

I have this code:

getText=async()=>{

const TheData=await getDataSet('City','New York'); //{country:'USA',city:'New York}
const TheText=TheData['country']; //'USA'

return new Promise((resolve,reject)=>{
  const request=??;
  request.onsuccess=()=>{resolve(TheText)};);

}

How can I modify the code above to return TheText as a resolved thenable promise.

Animation in JavaScript function only runs once even when called twice

I’m new to programming and am designing a game for a school assignment. I have made a small animation in CSS of a dice being shaken, then displaying the number of eyes of the throw. What I want is to call on the function playYourTurn() once (linked to a button), and then it would run the animation twice with some delay inbetween and move the players accordingly.

As it is now, only the second animation, playSpino(), runs. I have tried many variations with not having them as separate functions, change the intervals etc but to no avail. Sometimes it’s only the first animation, playSasha(), that runs. Borth markers move accordingly to their throws, I have checked by writing it out in the log, so it’s just the animations I’m struggling with.

The functions and the function in which they’re being called

The function with the animation that currently only runs once

Google Custom Search API returns 0 results for an indexed URL

I’m using the Google Custom Search JSON API to check whether a specific URL is indexed. However, even though I can find the page in Google manually, the API returns totalResults: 0

Here’s the URL I’m checking:
https://diario24horas.com/madrid/consigue-un-cabello-liso-y-saludable-con-un-alisado-permanente-organico-en-dim-salon/

And this is the request I’m sending:
GET https://www.googleapis.com/customsearch/v1?q=site:https://diario24horas.com/madrid/consigue-un-cabello-liso-y-saludable-con-un-alisado-permanente-organico-en-dim-salon/&key=API_KEY&cx=MY_cx

I get this response:
{
“searchInformation”: {
“totalResults”: “0”
}
}

a solution for my problem

Getting a 403 error from nginx when trying to build an nginx and php-fpm dev environment

I’m trying to get a simple nginx with php project up and running under Docker, but I’m getting a 403 error now that I’ve modified my nginx configuration to point at the php server.

My docker-compose.yaml is as follows:

version: '3.8'

# Services
services:

  # Nginx Service
  nginx:
    image: nginx:latest
    ports:
      - 8880:80
    volumes:
      - ./src:/var/www/php
      - ./nginx/conf.d:/etc/nginx/conf.d
    depends_on:
      - php

  # PHP Service
  php:
    image: php:8.1-fpm
    working_dir: /var/www/php
    volumes:
      - ./src:/var/www/php

I have a php.conf file under my ./nginx/conf.d directory as follows:

server {
    listen 80 default_server;
    listen [::]:80 default_server;
    root   /var/www/php;
    index  index.php;

    location ~* .php$ {
        fastcgi_pass   php:9000;
        include        fastcgi_params;
        fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param  SCRIPT_NAME     $fastcgi_script_name;
    }
}

and under my ./src directory I have a very simple index.php that should call phpinfo() as follows:

<?php
phpinfo():
?>

nginx itself was working fine with the default configuration and the container would serve the “Welcome to nginx!” page no problem. But with the above config to point to the php-fpm container it breaks.

The error is coming from the nginx container according to the logs:

192.168.1.162 - - [10/May/2025:23:24:02 +0000] "GET / HTTP/1.1" 403 555 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36" "-"
2025/05/10 23:24:02 [error] 21#21: *7 "/var/www/php/index.php" is forbidden (13: Permission denied), client: 192.168.1.162, server: , request: "GET / HTTP/1.1", host: "192.168.1.99:8880"

I have connected to both containers and have checked that index.php is both visible and readable (I can cat the file no problem from inside the container), I’ve even added other read and execute permissions to the index.php file but that makes no difference.

I guess something simple must be wrong with the php.conf as I don’t see anything in the php container’s log to say that it has received any forwarded request from the nginx container, but I am getting nowhere trying to figure out what is wrong.

Docker is running on a UGreen NAS, but this seems more fundamental than a host problem. I think I am just missing something in the setup.

How to serve React on root URL and Laravel Blade on /admin routes (e.g. /admin/login) on Hostinger?

I have a project with both a React frontend and a Laravel backend. I want to achieve the following routing logic:

When a user visits www.example.com, it should load the React frontend (like an SPA).

When the user visits www.example.com/admin/login, it should route to Laravel’s Blade template for admin login.

I’m hosting the project on Hostinger (shared hosting) and need help setting up this structure correctly.

// Catch-all route for React frontend
Route::get('/', function () {
    return file_get_contents(public_path('react-app/public/index.html'));
});

// Catch React frontend routes (e.g., /about, /contact, etc.)
Route::get('/{any}', function () {
    return file_get_contents(public_path('react-app/public/index.html'));
})->where('any', '^(?!admin).*');

I write like that but I want to know that is this good approach?
I mean can it create problems in future and can it create problems to frontend?

Memory overflow when saving an Excel document?

I’m solving a problem such as saving big data to an Excel document. There is a console command that uploads data from the database to an xlsx document.

The code performs the following actions:

  1. Allocates memory to the process.
  2. Creates a Spreadsheet object for the header and fills the spreadsheet with headers.
  3. Next, in the loop, it creates temporary Spreadsheet1 and in batches of 500 records, we pull it from the database and write it to the same document.
  4. When a new iteration of the while loop begins, we destroy Spreadsheet1.
  5. At the end and at intermediate stages, we save the document.
    As a result, an error occurs:

Worksheet!D301 -> Unable to access External Workbook

at the stage of loading the second data packet. Here is the code:

ini_set('memory_limit', '512M');
...
// Create new object - Spreadsheet
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();

 $count_data = DB::table($table_name)->count();

            $data = DB::table($table_name)->get();
            //skip($pos)->take(1000)->

            $headers = [];
            if (count($data) > 0) {
                // header  
              $this->info('Create header');
                foreach ($data as $itm) {

                    $Arr = json_decode($itm->data_json);

                    if (is_object($Arr))
                        // Add keys in array of headers
                        foreach ($Arr as $key => $value) {
                            if (!in_array($key, $headers)) {
                                $headers[] = $key;
                            }
                        }
                }

                $rowIndex = 1;
                $columnIndex = 1; // Start with first column 
                foreach ($headers as $colIndex => $header) {
                    //$sheet->setCellValueByColumnAndRow($columnIndex++, 1, $header);
                    $colLetter = Coordinate::stringFromColumnIndex($colIndex + 1); 
                   // create Alfabet string
                    $cell = $colLetter . $rowIndex;
                    $sheet->setCellValue($cell, $header);
                }

                $this->info('Header created...');
                $this->info('Rec data...');

                try {
                    $writer = new Xlsx($spreadsheet);
                    $writer->save(base_path('public') . '/' . $document);
                } catch (PhpOfficePhpSpreadsheetWriterException $e) {
                    $this->error('Error of save document: ' . $e->getMessage());
                }

$rowIndex = 2; // Begin with second record
$pos = 0;    
while ($rowIndex < $count_data) {

   $dump = DB::table($table_name)->skip($pos)->take(500)->get();

if ($dump->count()) {
$spreadsheet1 = PhpOfficePhpSpreadsheetIOFactory::load(base_path('public').'/'.$document);
//$spreadsheet1 = new Spreadsheet();
$sheet1 = $spreadsheet1->getActiveSheet();

foreach ($dump as $item) {
   $Arr = json_decode($item->data_json);
       foreach ($headers as $colIndex => $header) {
           $colLetter = Coordinate::stringFromColumnIndex($colIndex + 1);
           $cell = $colLetter . $rowIndex;
           $sheet1->setCellValue($cell, $Arr->$header ?? '');
       }
       $rowIndex++;
}

$this->info('Save document ' . base_path('public') . '/' .$document);
$this->info('Memory Size: ' . memory_get_usage() . ' bite');

try {
      $writer = new Xlsx($spreadsheet1);
      $writer->save(base_path('public') . '/'.$document);
      sleep(5);
      unset($spreadsheet1);
      unset($sheet1);
} catch (PhpOfficePhpSpreadsheetWriterException $e) {
      $this->error('Error of save document: ' . $e->getMessage());
    }
}

How to solve the problem?

JS and CSS Files Not Being Loaded in WordPress Plugin

I am developing a plugin for WordPress and it appears my my js and css files are not being enqueued even though I have enqueued them correctly in my code.

<?php
// Exit if accessed directly
if (!defined('ABSPATH')) exit;

/**
 * Enqueue styles and scripts only on the personalize-book page
 */
function bp_enqueue_assets() {
    // Only enqueue on the personalize-book page
    if (is_page('personalize-book')) {
        wp_enqueue_style('bp-style', BP_PLUGIN_URL . 'assets/css/style.css', [], '1.0');
        wp_enqueue_script('bp-editor', BP_PLUGIN_URL . 'assets/js/editor.js', ['jquery'], '1.0', true);

        wp_localize_script('bp-editor', 'bpData', [
            'ajax_url' => admin_url('admin-ajax.php'),
            'rest_url' => esc_url_raw(rest_url('bp/v1')),
            'nonce' => wp_create_nonce('wp_rest')
        ]);
    }
}
add_action('wp_enqueue_scripts', 'bp_enqueue_assets');

Is there something I am doing wrong? The path is exactly the same as used in the code.

How to judge next elements available in XML based on DTD schemas?

IT techey boys and girls, I need your help just as the title describes. I have parsed and generated elements sequence based on XML DTD files as below:

{
    "elementsInside": [
        "EFFECT",
        "CONEFFECT",
        "TITLEC",
        "TITLE",
        "WARNING",
        "CAUTION",
        "HNANOTE",
        "L3ITEM",
        "SIGNOFF"
    ],
    "schema": "(((EFFECT)?|(CONEFFECT)?)(TITLEC)?(TITLE)?(((WARNING)*(CAUTION)*(HNANOTE)*)(L3ITEM)(SIGNOFF)?(SIGNOFF)?)+)",
    "allFixedElements": [
        "EFFECT",
        "CONEFFECT",
        "TITLEC",
        "TITLE",
        "WARNING",
        "CAUTION",
        "HNANOTE",
        "L3ITEM",
        "SIGNOFF",
        "SIGNOFF"
    ]
}

How can I know which element next to be added can enroll? Like, if the element wrapper has no child, the first element child can be EFFECT or CONEFFECT or TITLE, or event L3ITEM. Then the next element adding must be applied by the rule here.

I know this problem may be so challenging, it’s just like AST parser of parsing your js or cpp files into a kind of code tree. I am not mastering any of this. I just configured this as a RegExp work, however it’s not that simple. You must match your element sequence from the start of this regexp. Hence, I’d like to know smarty and techey boys and girls do! Thanks for your helping.

Provided this kind of element sequence rule from DTD:

{
    "elementsInside": [
        "EFFECT",
        "CONEFFECT",
        "TITLEC",
        "TITLE",
        "WARNING",
        "CAUTION",
        "HNANOTE",
        "L3ITEM",
        "SIGNOFF"
    ],
    "schema": "(((EFFECT)?|(CONEFFECT)?)(TITLEC)?(TITLE)?(((WARNING)*(CAUTION)*(HNANOTE)*)(L3ITEM)(SIGNOFF)?(SIGNOFF)?)+)",
    "allFixedElements": [
        "EFFECT",
        "CONEFFECT",
        "TITLEC",
        "TITLE",
        "WARNING",
        "CAUTION",
        "HNANOTE",
        "L3ITEM",
        "SIGNOFF",
        "SIGNOFF"
    ]
}

Based on schema, the first element available could be EFFECT or any other elements obeying the rule, etc. If the first element is decided, then the next element sub-sequence will be determined.

Regex parameters in a function

I’m trying to replace a fixed string in a regex to a parameter in a function.
In my example I’m looking for a string that starts with XF-98 (two letters, a hyphen and a number)

var s = "XF-98 bananaas  ";

var regEx = (/XF-d+/mi); //NOT global
var result = s.match(regEx);
if (result != null) {
  alert(result);
  // do stuff
} else {
  alert("???" + s)
}

So far so good.
But how do I convert it into this format where prefix could be “XF-98”, “XF-99” or “AB-1000”??

function check_string(mystring, prefix)
{
  var regEx = (/prefix-d+/mi); //NOT global
  var result = mystring.match(regEx);
  if (result != null) {
    alert(mystring);
    // do stuff
  }
}

Adding a barcode to Excel using OfficeScript

So our IT department recently changed the office licenses, and most of our workers now only have access to the web version of Excel, rather than the app version we used before. This has caused one of our files to fail due to it relying on an external barcode font to generate barcodes, so now I’m looking for a way to insert barcodes into the web version of Excel using OfficeScript (rather than VBA that I used before).

I’m not as fluent in OfficeScript/TypeScript/JavaScript as I’d like to be, so I might be missing something obvious, but so far I’m looking at two things in particular:

JavaScript has an “ImageData” class that takes a byte array. Using that I should easily be able to create the necessary data for the barcode before creating the ImageData, but so far I’ve not found a way to add an ImageData to a worksheet. Is there such a way?

ExcelScript.Worksheet have a “.addImage()” method that takes a base64-encoded string that represent the image data, formatted in either JPEG or PNG format. Is there an easy way to encode an ImageData or similar to a PNG or JPEG so I can get the Base64 that way?

Zod: inner object keys based on outer enum values

I am using an API which returns data in the following way:

{
    "title": {
        "title-action": "some value",
        ...rest
    }
    "body": {
        "body-action": "some value",
        ...rest
    }
    ...
}

Very inelegant, but it is what it is. I would like to declare the following Zod enum and use it to parse this data:

const MyEnum = z.enum(["title", "body"])

However, I immediately have a problem on second level as I cannot figure out how to construct title-action key based on my enum:

const MySchema = z.object({
    [MyEnum.enum.title]: z.object({
        // what to do here?
    })
})

Any help would be appreciated!

The only implementation which I was able to compile is this:

const MySchema = z.object({
    [MyEnum.enum.title]: z.object({
        [MyEnum.enum.title + "-action"]: z.string()
    })
})

However, this loses any information on the value of inner keys, they are simply [x: string], and so my types become:

{
    title: {
        [x: string]: string
    }
    ...
}