Content on page moves left when p5.js finishes preload

I’m using p5.js to make an audio player. But the problem is that the elements on the page, which should be in the center of the page according to the css, always move to left a bit after the call to the preload() (the elements were in the center before the preload() returns).

My code:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #fff;
            transition: background-color 3s ease-in-out;
            margin: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
        }

        #music-player {
            max-width: 400px;
            padding: 30px;
            background-color: #f8f8f8;
            border-radius: 8px;
            box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
            text-align: center;
        }

        .control-icons {
            font-size: 24px;
            margin-bottom: 20px;
        }

            .control-icons i {
                opacity: 0.5;
                transition: opacity 0.3s ease;
                cursor: pointer;
            }

                .control-icons i:hover {
                    opacity: 1;
                }

                .control-icons i.active {
                    opacity: 1;
                }
    </style>
</head>
<body>
    <div id="music-player">
        <div class="control-icons">
            <i class="fas fa-spinner" id="p5_loading" title="Loading..."></i>
            <i class="fas fa-play-circle" onclick="playAudio()" id="playButton" title="Play" style="display: none;"></i>
            <i class="fas fa-pause-circle" onclick="pauseAudio()" id="pauseButton" title="Pause" style="display: none;"></i>
        </div>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/addons/p5.sound.min.js"></script>
    <script>
        const path = new URLSearchParams(window.location.search).get('path');
        const encodedPath = encodeURIComponent(path).replace(/%20/g, "+");
        const apiUrl = './audio';

        let audio;

        function setup() {
        }

        function preload() {
            audio = loadSound(`${apiUrl}?path=${encodedPath}`, finishLoading, errorLoading);
        }

        function errorLoading(e) {
            console.error("Error Loading Audio: " + e);
        }

        function finishLoading() {
            if (audio.isLoaded()) {
                playButton.style.display = 'inline-block';
            }
        }

        function playAudio() {
            if (audio.isLoaded() && !audio.isPlaying()) {
                playButton.style.display = 'none';
                pauseButton.style.display = 'inline-block';
                audio.play();
            }
        }

        function pauseAudio() {
            if (audio.isPlaying()) {
                playButton.style.display = 'inline-block';
                pauseButton.style.display = 'none';
                audio.pause();
            }
        }
    </script>
</body>
</html>

Any ideas what the cause is and how to make the elements stay in the center of the page?

Manual mocking of React hook with Jest

I moved the mock of my custom hook to the __mocks__ folder adjacent to the hook file. Earlier, the mock was working fine, but as soon as I moved it to the __mocks__ folder, it stopped working.

useToast.ts – in the __mocks__ folder:

export const mShowError = jest.fn();
export const mShowSuccess = jest.fn();

const useToast = jest.fn().mockReturnValue({
    showError: mShowError,
    showSuccess: mShowSuccess,
});

export default useToast;

loginForm.test.ts:

import {
    mShowError,
    mShowSuccess,
} from "../../../src/hooks/generic/__mocks__/useToast";

    it("displays error message in case of network error", async () => {
        const message = "Sorry. Something went wrong";
        process.env.VITE_BACKEND_URL = "http://invalidUrl";
        render(<LoginForm />);

        await act(async () => {
            fireEvent.change(screen.getByLabelText(/email/i), {
                target: { value: correctEmail },
            });
            fireEvent.change(screen.getByLabelText(/password/i), {
                target: { value: correctPassword },
            });

            const loginButton = screen.getByText(
                /login/i
            ) as HTMLButtonElement;
            loginButton.click();
        });

        expect(mShowError).toHaveBeenCalledWith(message);
    });

The mocked function mShowError is getting called, but Jest is not able to detect the call made.

test run error

What am I doing wrong?

Pixi text jumps around when scale and resolution is used

I am rendering text using Pixi.js. The text I am rendering is inside a container with a scale, so I have to reduce the font size to account for the scale.

const app = new PIXI.Application({ background: '#1099bb' });

document.body.appendChild(app.view);

const fontSize = 40;
const scale = 4

const text = new PIXI.Text(
    'Scaled',
    new PIXI.TextStyle({ fontSize: fontSize / scale })
);

const container = new PIXI.Container();
container.scale.set(scale);
container.addChild(text);
app.stage.addChild(container);

Because of the scale, the text gets blury since Pixi renders it with a smaller font size and then upscales it. This can be fixed with one line of code, setting a resolution to match the scale:

text.resolution = scale;

Now the text looks sharp. However, there is still a problem. When I animate the font size, I notice that the text jumps around slightly in the vertical direction, as can be seen in this fiddle. There appears to be some kind of rounding issue going on.

How can I get rid of this “jumpiness”, and have the text be correctly positioned?

Google Maps API Integration in React: Achieving Stable User Location and Device Orientation

I’m working on a Google Maps API integration in React to display a user’s dynamic location, orientation, and tilt based on their mobile or tablet device. However, I’m encountering an issue: even when the device is still, there are minor fluctuations in position (latitude/longitude) or tilt/orientation values.

I’ve managed to achieve the basic functionality, but the behavior differs from what I’ve observed in the official Google Maps app. I’d like to fine-tune my implementation to match the smooth and stable behavior of Google Maps. Could someone guide me on what might be causing these fluctuations or offer tips on how to improve my code?

Thanks in advance!

Code:-

import React, { useEffect, useRef, useState } from 'react';

let watchPositionId = null;
let isLocationPermission = false;
let map = null;
let userMarker = null; 

const GoogleMap = () => {
  const [longLat, setLongLat] = useState({ longitude: 0, latitude: 0 });
  const [orientation, setOrientation] = useState(0);
  const [autoAdjust, setAutoAdjust] = useState(true); // New state for auto adjustment
  const mapRef = useRef(null);

  useEffect(() => {
    const initMap = () => {
      if(!map){
        map = new window.google.maps.Map(mapRef.current, {
          center: {
            lat: longLat?.latitude,
            lng: longLat?.longitude,
          },
          zoom: 30,
          heading: 320,
          tilt: 47.5,
          mapId: "90f87356969d889c",
          mapTypeId: "satellite"
        });
      }else{

        // Remove previous user marker if it exists
        if (userMarker) {
          userMarker.setMap(null);
        }


        map.setCenter({
          lat: longLat.latitude,
          lng: longLat.longitude,
        });
      }

      const adjustMap = function (mode, amount) {
        switch (mode) {
          case "tilt":
            map.setTilt(map.getTilt() + amount);
            break;
          case "rotate":
            map.setHeading(map.getHeading() + amount);
            break;
          default:
            break;
        }
      };

      userMarker = new window.google.maps.Marker({
        position: {
          lat: longLat.latitude,
          lng: longLat.longitude,
        },
        map: map,
        title: 'My Location',
      });
    

      const handleOrientation = (event) => {
        const alpha = event.alpha;
        const beta = event.beta;
        const gamma = event.gamma;

        if (autoAdjust) {
          const direction = calculateHeading(alpha, beta, gamma);
          setOrientation(direction);

          console.info("calling now", {gamma, direction});
          // Automatically adjust the map based on the new orientation
          adjustMap("tilt", beta * 0.05); // Adjust the factor as needed
          const rotationVal = gamma * 0.02;
         
          adjustMap("rotate", rotationVal); // Adjust the factor as needed
        }
      };

      window.addEventListener('deviceorientation', handleOrientation, true);

    };

    if (window.google && mapRef.current) {
      if (isLocationPermission) {
        initMap();
      }
    } else {
      console.error("Google Maps API not loaded or mapRef not available");
    }

    return () => window.removeEventListener('deviceorientation', () => {});
  }, [isLocationPermission, autoAdjust, longLat]);

  useEffect(() => {
    if (window) {
      userDeviceOrientatationHandler(setOrientation);
      userLocationHandler(setLongLat);
    }

    return () => navigator?.geolocation?.clearWatch(watchPositionId);
  }, []);

  return (
    <>
      <div ref={mapRef} style={{ width: '100%', height: '100vh' }} />
    </>
  );
};

export default GoogleMap;


function calculateHeading(alpha, beta, gamma) {
  // Convert alpha (compass heading) to radians
  const compassHeadingRadians = alpha * (Math.PI / 180);

  // Convert beta and gamma to radians
  const betaRadians = beta * (Math.PI / 180);
  const gammaRadians = gamma * (Math.PI / 180);

  // Combine values to derive a more accurate heading
  
  const heading = compassHeadingRadians + betaRadians + gammaRadians;

  return heading;
}

function handleOrientation(event, setOrientation) {
  /**
   * gamma is the data of angle in degrees the device is tilted left-to-right, where right is positive.
   * alpha is the data of the direction the device is facing according to the compass.
   * beta is the data of the angle in degrees the device is tilted front-to-back, where front is positive.
  **/

  const alpha = event.alpha; // Z-Axis
  const beta  = event.beta;  // Y-Axis
  const gamma = event.gamma; // X-Axis 

  if(alpha && beta){
    const direction = calculateHeading(alpha, beta, gamma);
 
    setOrientation(direction);
  }
}

function userDeviceOrientatationHandler(setOrientation){
  if (window.DeviceOrientationEvent) {
    window.addEventListener('deviceorientation', (event) => handleOrientation(event, setOrientation), true);
  }else{
    alert("Device Orientation is not supported on your device or browser. Sorry.");
  }
}

function userCurrentPositionSuccessHandler(event, setLongLat){
  isLocationPermission = true;
  setLongLat({ longitude: event?.coords?.longitude, latitude: event?.coords?.latitude });
}

function userCurrentPositionErrorHandler(error){
  isLocationPermission = false;
  switch (error.code) {
    case error.PERMISSION_DENIED:
        alert("The request denied for geolocation.");
        break;
    case error.POSITION_UNAVAILABLE:
        alert("Location information is unavailable.");
        break;
    case error.TIMEOUT:
        alert("The request to get location timed out.");
        break;
    case error.UNKNOWN_ERROR:
        alert("An unknown error occurred.");
        break;
    default:
      alert("Something went wrong.");
      break;
  }
}

function userLocationHandler(setLongLat){
  watchPositionId = navigator?.geolocation?.watchPosition((event) => userCurrentPositionSuccessHandler(event, setLongLat), userCurrentPositionErrorHandler)
}

Angular “@ngx-translate/core” library TranslateModule is declared in the root but not overrided in the Child module

I’m using “@ngx-translate/core” library to apply internationalization, I’ve created a helper service for it and configured it in all my modules, I also installed “ngx-translate-multi-http-loader”, To allow reading more than one key and then fetching it’s values from english or french files depending on the language needed.
My problem is that the import in my app module is not overrided in the shild module, This is my code.

This is my Child module:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { CheckinCkeckoutRackRoutingModule } from './checkin-ckeckout-rack-routing.module';
import { IndexComponent } from './index/index.component';
import { LoadRackComponent } from './load-rack/load-rack.component';
import { RackInfoComponent } from './rack-info/rack-info.component';
import { RackActionComponent } from './rack-action/rack-action.component';
import { ReactiveFormsModule } from '@angular/forms';
import { RackService } from '../../setup/manage-rack/service/rack.service';
import { ModalModule } from 'ngx-bootstrap/modal';
import { RacktransactionService } from '../service/racktransaction.service';
import { ManagestorageService } from '../../setup/manage-storage/services/managestorage.service';
import { SamplestoragelogserviceService } from '../../sample-storage-log/services/samplestoragelogservice.service';
import { FormsModule } from '@angular/forms';
import { SearchCriteriaService } from '../service/searchcriteriadata.service';
import { HttpBackend } from '@angular/common/http';
import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { HttpLoaderFactory } from '@/shared/helpers/helper-transalation.service';



@NgModule({
  declarations: [IndexComponent, LoadRackComponent, RackInfoComponent, RackActionComponent],
  imports: [
    CommonModule,
    ReactiveFormsModule,
    FormsModule,
    CheckinCkeckoutRackRoutingModule,
    ModalModule.forRoot(),
    TranslateModule.forChild({
      loader: {
        provide: TranslateLoader,
        useFactory: (httpBackend: HttpBackend) => HttpLoaderFactory(httpBackend, 'sample-storage'), 
        deps: [HttpBackend]
      }
    })
  ],
  providers: [
    RackService,
    RacktransactionService,
    ManagestorageService,
    SamplestoragelogserviceService,
    RackService,
    SearchCriteriaService,  
  ],
})
export class CheckinCkeckoutRackModule { }

And this is my App module:

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { MegaMenuModule } from 'primeng/megamenu';
import { ButtonsModule } from '@progress/kendo-angular-buttons';
import { MenubarModule } from 'primeng/menubar';
import { DropdownModule } from 'primeng/dropdown';
import { MessageService } from 'primeng/api';
import { MessagesModule } from 'primeng/messages';
import { MessageModule } from 'primeng/message';
import { ToastModule } from 'primeng/toast';
import { MenuModule } from '@progress/kendo-angular-menu';
import { ToastyModule, ToastyService } from 'ng2-toasty';
import { AngularMaterialModule } from '@material-controls-module/angular-material.module';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import 'hammerjs';
import { GridModule } from '@progress/kendo-angular-grid';
import { ModalModule } from 'ngx-bootstrap/modal';
import { TreeViewModule } from '@progress/kendo-angular-treeview';
import { DropDownsModule } from '@progress/kendo-angular-dropdowns';
import { HttpClientModule, HttpClient, HttpBackend } from '@angular/common/http';
import { ConfigService } from '@core-services/config.service';
import { getBaseUrl } from '@shared-helpers/helper-url';
import { LayoutModule } from '@progress/kendo-angular-layout';
import { ConfirmDialogComponent } from '@shared-components/base-component/confirmDialog/confirm-dialog/confirm-dialog.component';
import { MatDialogModule } from '@angular/material/dialog';
import { InterceptorsList } from './core/interceptor/Interceptors';
import { LoaderServiceModule } from './core/layout/loader/loader-service.module';
import { TranslateLoader, TranslateModule } from '@ngx-translate/core';
import { RegistrationService } from './modules/registration/Services/registration.service';
import { ToolsModule } from './modules/tools/tools.module';
// tslint:disable-next-line:max-line-length
import { PatientLastVisitComponent } from './modules/registration/component/Dialogs/patient-last-visit/patient-last-visit.component';
import { DynamicFileUploadComponent } from './dynamic-control-module/controls/dynamic-file-upload/dynamic-file-upload.component';
import { SharedFileUploadComponent } from './dynamic-control-module/controls/shared-file-upload/shared-file-upload.component';
import { DatePipe } from '@angular/common';
import { DyanmicRegFormService } from './modules/registration/Services/DynamicRegisterationServices/reg-dynamic-form.service';
import { LoyaltyModule } from './modules/loyalty/loyalty.module';
import { APP_INITIALIZER, NgModule } from '@angular/core';
import { BrowserModule, Title } from '@angular/platform-browser';
import { HttpLoaderFactory } from './shared/helpers/helper-transalation.service';
import { KendoDatepickerComponent } from './shared/components/kendo-datepicker/kendo-datepicker.component';
import { KendoTimepickerComponent } from './shared/components/kendo-timepicker/kendo-timepicker.component';


@NgModule({
    declarations: [
        AppComponent,
        ConfirmDialogComponent,
        PatientLastVisitComponent,
        DynamicFileUploadComponent,
        SharedFileUploadComponent

    ],
    imports: [
        BrowserModule,
        AppRoutingModule,
        BrowserAnimationsModule,
        MegaMenuModule,
        ButtonsModule,
        MenubarModule,
        DropdownModule,
        ToastyModule,
        MessagesModule,
        MessageModule,
        ToastModule,
        MenuModule,
        GridModule,
        AngularMaterialModule,
        TreeViewModule,
        DropDownsModule,
        HttpClientModule,
        LayoutModule,
        ToolsModule,
        MatDialogModule,
        LoaderServiceModule,
        ModalModule.forRoot(),
        ToastyModule.forRoot(),
        TranslateModule.forRoot({
            loader: {
                provide: TranslateLoader,
                useFactory: (httpBackend: HttpBackend) => HttpLoaderFactory(httpBackend, 'app'),
                deps: [HttpBackend]
            }
        }),
        LoyaltyModule
    ],
    providers: [
        {
            provide: APP_INITIALIZER,
            useFactory: setConfig,
            multi: true,
            deps: [HttpClient, ConfigService]
        },
        DatePipe,
        MessageService,
        ToastyService,
        Title,
        InterceptorsList,
        RegistrationService,
        DyanmicRegFormService,
    ],
    bootstrap: [AppComponent]
})
export class AppModule { }

export function setConfig(http: HttpClient, configService: ConfigService) {
    return async () => {
        const resp = await http.get(getBaseUrl() + 'config.json').toPromise();
        configService.configuration = <any>resp;
    };
}

And This is my Translation helper service:

import { HttpBackend } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { TranslateService } from "@ngx-translate/core";
import { MultiTranslateHttpLoader } from "ngx-translate-multi-http-loader";

@Injectable({
    providedIn: 'root',
})
export class TranslationHelperService {
    /**
     *
     */
    constructor(private readonly translate: TranslateService) {
        this.translate.use('en');

    }
    /**
     * 
     * @param resourceKey 
     * @param resourceKeyParamters 
     * @returns Promise<string>
     */
   public async getTransaltedMsg(resourceKey: any, resourceKeyParamters: any = null):Promise<string> {
        if (!resourceKeyParamters) {
            return await this.translate.get(resourceKey).toPromise();
        } else {
            return await this.translate.get(resourceKey, resourceKeyParamters).toPromise();
        }
    }
}
 /**
  * 
  * @param _httpBackend 
  * @param moduleName 
  * @returns 
  */
export function HttpLoaderFactory(_httpBackend: HttpBackend, moduleName: string) {
    return new MultiTranslateHttpLoader(_httpBackend, [
      {prefix: './assets/i18n/shared/', suffix: '.json'},
      {prefix: `./assets/i18n/${moduleName}/`}
    ]);
}

The import: TranslateModule is not overrided in the child module and always sends the string: ‘app’ not ‘sample-storage’, Need to know the reason and how to solve?

What is the difference between these two approaches in the async-await pattern?

case – A

const BASE_URL = "https://bootcamp-api.codeit.kr/api";

export async function fetchData(endpoint) {
  const response = await fetch(`${BASE_URL}/sample/${endpoint}`);
  if (!response.ok) {
    throw new Error("Fail");
  }
  return await response.json();
}

export async function getFolders() {
  return await fetchData("folder");
}

export async function getUserProfile() {
  return await fetchData("user");
}

case – B

export async function fetchData(endpoint) {
  const response = await fetch(`${BASE_URL}/sample/${endpoint}`);
  if (!response.ok) {
    throw new Error("Fail");
  }
  return await response.json();
}

export function getFolders() {
  return fetchData('folder');
}

export function getUserProfile() {
  return fetchData('user');
}

What’s different in action ?

— Edited —

Why do we no need to add ‘async’ and ‘await’ keyword at case B ?
This code working same.

Why does form button need “method=POST” in order navigate other route in nodeJs?

I’m very new to nodeJs. I tried to add added user name to the txt file using form field and display that added user names in the ‘/users’ route from the text file call “users.txt” and show added user names using an unordered list. In approch this I was struggled to go from the’/’ route to the ‘/users’ route using from action button called “See Users” I tried a lot and I had no idea what had gone wrong. following are my files:

  • app.js file
const http = require('http');

const routes = require('./routes');

const sever = http.createServer(routes);

sever.listen(3000);
  • routes.js file
const fs = require('fs');

const requestHandler = (req, res) => {
    const url = req.url;
    const method = req.method;


    console.log('Requested URL:', url);
    console.log('Request Method:', method);

    if (url === '/') {
        res.setHeader('Content-type', 'text/html');
        res.write('<html>');
        res.write('<head><title>Create new users.</title></head>');
        res.write('<body>');
        res.write('<form action="/create-user" method="POST"><input type="text" name="userName"><button type="submit"> ADD</button></form>');
        res.write('<form action="/users"><input type="submit" value="See Users"></form>');
        res.write('</body>');
        res.write('</html>');
        return res.end();
    } else if (url === '/create-user' && method === 'POST') {
        const body = [];
        req.on('data', (chunk) => {
            body.push(chunk);
        });
        return req.on('end', () => {
            const praseBody = Buffer.concat(body).toString();
            const userName = praseBody.split('=')[1];
            console.log(userName);
            fs.appendFile('users.txt', userName + 'n', (err) => {
                if (err) {
                    console.error('Error appending to file:', err);
                    res.statusCode = 500;
                    res.end();
                } else {
                    res.statusCode = 302;
                    res.setHeader('Location', '/');
                    return res.end();
                }
            });
        });
    } else if (url === '/users' && method === "POST") {
        console.log('Handling /users route');
        if (fs.existsSync('users.txt')) {
            fs.readFile('users.txt', 'utf8', (err, data) => {
                if (err) {
                    console.error('Error reading file:', err);
                    res.statusCode = 500;
                    return res.end();
                }

                const userList = data.split('n').filter(Boolean);
                res.setHeader('Content-type', 'text/html');
                res.write('<html>');
                res.write('<head><title>All Users.</title></head>');
                res.write('<body>');
                res.write('<ul>');
                userList.forEach((userName) => {
                    res.write(`<li>${userName}</li>`);
                });
                res.write('</ul>');
                res.write('<form action="/"><input type="submit" value="Go Back"></form>');
                res.write('</body>');
                res.write('</html>');
                return res.end();
            });
        } else {
            res.setHeader('Content-type', 'text/html');
            res.write('<html>');
            res.write('<head><title>No Users Found.</title></head>');
            res.write('<body>');
            res.write('<h1>No user list to display. Please go back and add users.</h1>');
            res.write('</body>');
            res.write('</html>');
            return res.end();
        }
    } else {
        res.setHeader('Content-type', 'text/html');
        res.write('<html>');
        res.write('<head><title>My Node Sever.</title></head>');
        res.write('<body>');
        res.write('<h1>This is your node sever.</h1>');
        res.write('</body>');
        res.write('</html>');
        return res.end();
    }
}

module.exports = requestHandler;
  • So then I added a few “console.log( )” and printed the ‘URL’ and the ‘method’ of the request when I hit the from the button. At that time browser kept loading and in the terminal, it showed:

    Requested URL: /users?

    Request Method: GET

  • But when I go the “/users” route by manually entering “http://localhost:3000/users” in the browser it works perfectly and in the terminal, it shows:

    Requested URL: /users

    Request Method: GET

  • After spending more than a few hours I successfully corrected the error. I added "method="to the form tag first I set it as method="GET" but it did not work. Then I added method="POST" See Users from button and it works perfectly the code line was as follows:

    res.write('<form action="/users" method="POST"><input type="submit" value="See Users"></form>');
    
  • I’m curious why it’s necessary to use the POST method instead of the GET method when I’m not passing any data to the server. Could you please help me understand this? Thank you!

Innoextract will not start or run

I cannot get the program to run. I cannot run any commands either, it says missing or not found. When I try to run inno it just exits out and dissapears. What must I do to run it? I have basic Windows 10.

I tried clicking, dragging and dropping. Nothing works. I cannot find anything online about getting this program to run. Is it part of another program?

can someone explain why is the argument output is not what’s expected?

why is name returning steve for both players?

function Player(name, marker){
  this.name = name;
  this.marker = marker;
  this.sayName = function(parameter){
    console.log(parameter)
  }
}
const player1 = new Player("steve", "X");
const player2 = new Player("also steve", "O");
player1.sayName(this.name); // "steve"
player2.sayName(this.name); // "steve"

however when I change the code to this it returns what is expected:

function Player(name, marker){
  this.name = name;
  this.marker = marker;
  this.sayName = function(){
    console.log(name)
  }
}
const player1 = new Player("steve", "X");
const player2 = new Player("also steve", "O");
player1.sayName(); // "steve"
player2.sayName(); // "also steve"

I know it’s related to scope but I don’t understand it at all.

how does the manipulation of inputs type date work?

so i was trying to creat a page that asks the user to enter some infos including the birthday and then displays these informations in initially empty spans but i was wondering how does it work if
<input type="date" id="birth">
and then inside the script tags
<script> var a = document.getElementById('birth').value; </script>

is now the “a” a new date() with set values? or how does it work exactly?
because i was trying to execute a function if the user clicks on a button with the onclick event and it doesn t get executed which lead me to question how does the date type work to begin with
i tried to change the type date to a type text and let the user enter the date as “dd/mm/yyyy”
and then collect it but again i didnt know if per example we had
<input type="text" id="birth2">
if i do a
<script> var b = document.getElementById('birth2').value; </script>
can i transform the “b” into an Array() (each item is seperated by “/”) and then control if the date is correct(no negative values, the month is between 1 and 12 …..)?
if anyone knows anything about it please let me know

How could I sum all the elements in an array which is inside of an object and display to the DOM or HTML elemnet?

I can’t show to the browser the sum of the elements of an array inside of an object.

Here is my JavaScript code:

const products = {
    productName: [],
    description: [],
    quantity: [],
    unitOfMeasure: []
}
let countLog = products.quantity;`


function sumArray(sum) {

    let displaySumEl = document.getElementById('display-sum');
    sum = countLog.reduce((total, item) => total + item);
    displaySumEl.textContent = `Total: `;
    displaySumEl.textContent += `${parseInt(sum)}`;



    console.log(countLog);

}

Problem in here is that sum variable only shows the numbers in an array not the sum of the numbers in countLog varibale.

I am getting js.experimental-foreign-object-prototype while running Karate tests

I get this error when I run a karate test

java.lang.IllegalArgumentException: Could not find option with name js.experimental-foreign-object-prototype.
Did you mean one of the following?
js.foreign-object-prototype=
at org.graalvm.truffle/com.oracle.truffle.polyglot.PolyglotEngineException.illegalArgument(PolyglotEngineException.java:131)

I have GraalVM 22 and it has JS also.

I think, there is some option missing in my local environment, because the tests run on the server.