Problème de configuration au niveau de: const data = new SlashCommandBuilder()

Bonjour ! Je suis français et j’apprends au niveau de la programmation. Je sais que j’ai fait une faute au niveau de la ligne 23 car il y a deux fois const data = new SlashCommandBuilder() puisque je l’ai déja utilisé à la ligne 13.

Voilà ce que ça me met comme faute de syntax:

Uncaught SyntaxError /Users/ge.gourjon/Documents/bot discord/projet Athéna/index.js:23
const data = new SlashCommandBuilder()
^
enter image description here

Ce que souhaiterai est de créer la même commande de la ligne 23 qu’à la ligne 13, c’est à dire un Slash Command. Mais lorsqu’on fait le Slash Command, on est obligé d’id quelqu’un.

Par example: (voire lien ci-dessous)

enter image description here

Merci de votre compréhension et de toutes aides apportés.

Issue with navigation in React Native between TabNavigator and StackNavigator

for a few days I’ve been stumbling over a problem and I can’t find the solution… In my application I have a tabNavigator and a stackNavigator.

My problem is that in my tabNavigator I want to put an icon in my headerRight and when you click on it you go to the stack corresponding to my shopping cart. When I enter the name of my stack in the navigator, which is “Cart”, I get an error: The action 'NAVIGATE' with payload {"name": "Cart"} was not handled by any navigator. Do you have a screen named 'Cart'?

I can only navigate to a tab.Screen when I need to navigate to my Stack.

Their is my TabNavigator :

const Tab = createBottomTabNavigator();

const TabNavigator = () => {
  const navigation = useNavigation();
  return (
    <Tab.Navigator
      screenOptions={() => ({
        headerStyle: {
          backgroundColor: appColors.primary,
          height: Platform.OS === "ios" ? 60 : undefined,
        },
        headerTitle: () => <Logo />,
        headerTitleAlign: "center",
        headerRight: () => (
          <Feather
            name="shopping-cart"
            size={24}
            color="white"
            onPress={() => {
              navigation.navigate("Cart");
            }}
          />
        ),
        headerRightContainerStyle: {
          paddingEnd: 10,
        },
      })}
    >
      <Tab.Screen
        name="News"
        component={HomePageStack}
        options={{
          tabBarIcon: ({ focused, color, size }) => (
            <Entypo name="news" size={40} color="black" />
          ),
          tabBarShowLabel: false,
        }}
      />
      <Tab.Screen
        name="Cheval"
        component={HorseStack}
        options={{
          tabBarIcon: ({ focused, color, size }) => (
            <MaterialCommunityIcons name="horse" size={40} color="black" />
          ),
          tabBarShowLabel: false,
        }}
      />
      <Tab.Screen
        name="Sell"
        component={SellStack}
        options={{
          tabBarIcon: ({ focused, color, size }) => (
            <Entypo name="shopping-basket" size={40} color="black" />
          ),
          tabBarShowLabel: false,
        }}
      />
    </Tab.Navigator>
  );
};

export default TabNavigator;

And my StackNavigator :

const Stack = createStackNavigator<RootStackParamList>();

const MainStackNavigator = () => {
  return (
    <Stack.Navigator>
      <Stack.Screen
        name="HomePage"
        component={HomePageStack}
        options={{
          headerShown: false,
        }}
      />
    </Stack.Navigator>
  );
};

// Stack for the news
const HomePageStack = () => {
  return (
    <Stack.Navigator>
      <Stack.Screen
        name="Home"
        component={Home}
        options={{
          headerShown: false,
        }}
      />
      <Stack.Screen
        name="DetailsNewsScreen"
        component={DetailsNewsScreen}
        options={{
          headerShown: false,
        }}
      />
    </Stack.Navigator>
  );
};

const HorseStack = () => {
  return (
    <Stack.Navigator>
      <Stack.Screen
        name="Horse"
        component={HorseScreen}
        options={{
          headerShown: false,
        }}
      />
    </Stack.Navigator>
  );
};

const SellStack = () => {
  return (
    <Stack.Navigator>
      <Stack.Screen
        name="SellStack"
        component={HomeSellScreen}
        options={{
          headerShown: false,
        }}
      />
      <Stack.Screen
        name="ServicesSell"
        component={ServicesScreen}
        options={{
          title: "",
          headerBackTitle: "Retour",
        }}
      />
      <Stack.Screen
        name="ClothesScreen"
        component={ClothesScreen}
        options={{
          title: "",
          headerBackTitle: "Retour",
        }}
      />
      <Stack.Screen
        name="HorseActivity"
        component={HorseActivityScreen}
        options={{
          title: "",
          headerBackTitle: "Retour",
        }}
      />
    </Stack.Navigator>
  );
};

const LoginStack = () => {
  return (
    <Stack.Navigator>
      <Stack.Screen
        name="Login"
        component={LoginScreen}
        options={{
          headerShown: false,
        }}
      />
    </Stack.Navigator>
  );
};

const CartStack = () => {
  return (
    <Stack.Navigator>
      <Stack.Screen
        name="Cart"
        component={HomeScreenCart}
        options={{
          headerShown: false,
        }}
      />
    </Stack.Navigator>
  );
};

export {
  MainStackNavigator,
  HomePageStack,
  HorseStack,
  SellStack,
  LoginStack,
  CartStack,
};

I tried to use the props of the screenOptions it doesn’t works. I also tried to use the navigation with useNavigation and same it doesn’t work.

prompt is not taking input in vs code

I’m unable to take user input in vs code in javascript by using prompt (I know it is made for browser but it works in vs code too). Its not showing any error but when I’m typing something its not taking it as input and I have to terminate the program manually.

I have installed node, I have used “npm install prompt-sync” command in terminal (it installed some json files) , I have defined prompt in program { const prompt = require(‘prompt-sync)(); } but when I’m using it, It’s not showing any error and running program properly but its not accepting any input that I am giving, and I have to manually terminate the program.

const prompt = require('prompt-sync');
let age = prompt("enter your age: ");
console.log(age);

Why Set-Cookie in the response header is ignored? using httpsCallable from @angular/fire/functions

My goal is to store the session cookie, and use it to create custom token, to share auth between subdomain1.example.com and subdomain2.example.com. If the session cookie is missing, then when user visit subdomain1.example.com, it will logout.

My expected result: when I send request to Cloud Function createSessionCookie, it return Set-Cookie in the response header, then it should store the cookie in the browser.

The actual result: when I send request to Cloud Function createSessionCookie, the server does respond with the Set-Cookie header. However, it is not stored in the browser.

The repository: https://github.com/jasonrichdarmawan/angular-firebase-authentication-across-subdomains

The domain:

  1. https://account.topoint.org
  2. https://experiences.topoint.org
  3. https://checkout.topoint.org

Cloud Function createSessionCookie

/* eslint-disable max-len */
import {onRequest} from "firebase-functions/v2/https";
import {Request, Response} from "express";

import * as admin from "firebase-admin";

// eslint-disable-next-line @typescript-eslint/no-var-requires
import serviceAccountKey from "../../../serviceAccountKeys.json";


admin.initializeApp({
  credential: admin.credential.cert(serviceAccountKey as admin.ServiceAccount),
});

/**
 * @todo CSRF protection
 * @bug Set-Cookie header in the response is ignored by Chrome in localhost.
 */
export const createSessionToken = onRequest(
  async (req: Request, res: Response) => {
    handleCors(req, res);


    const idToken = req.body.data.idToken;

    // Set session expiration to 5 days.
    const expiresIn = 60 * 60 * 24 * 5 * 1000;

    admin.auth().verifyIdToken(idToken).then(function(decodedClaims) {
      // we are enforcing that the user signed in in the last 5 minutes.
      if (new Date().getTime() / 1000 - decodedClaims.auth_time < 5 * 60) {
        return admin.auth().createSessionCookie(idToken, {expiresIn: expiresIn});
      }
      throw new Error("unauthorized request");
    })
      .then(function(sessionCookie) {
        // Note httpOnly cookie will not be accessible from javascript.
        // secure flag should be set to true in production.
        const options = {
          maxAge: expiresIn,
          httpOnly: true,
          secure: process.env.FUNCTIONS_EMULATOR === "true" ? false : true, /* to test in localhost */
        };
        res.cookie("session", sessionCookie, options);
        res.send({data: "success"});
      })
      .catch(function() {
        res.status(401).send({data: "unauthorized"});
      });
  });

// eslint-disable-next-line valid-jsdoc
/**
 * @todo staging and dev environment.
 */
const handleCors = (req: Request, res: Response) => {
  const allowedOrigins = ["https://account.topoint.org", "https://experiences.topoint.org", "https://checkout.topoint.org"];
  const origin = req.get("origin") ?? "";


  if (allowedOrigins.includes(origin)) {
    res.set("Access-Control-Allow-Origin", origin);
  }

  if (process.env.FUNCTIONS_EMULATOR) {
    res.set("Access-Control-Allow-Origin", "*");
  }

  if (req.method === "OPTIONS") {
    // Send response to OPTIONS requests
    res.set("Access-Control-Allow-Methods", "GET");
    res.set("Access-Control-Allow-Headers", "Authorization, Content-Type");
    res.set("Access-Control-Max-Age", "3600");
    res.status(204).send("");
    return;
  }
};

httpsCallable in Angular.

  /**
   * @bug Set-Cookie in the response header is ignored.
   */
  private async createSessionToken(idToken: string) {
    if (isPlatformServer(this.platformId)) { return; }

    const callable = httpsCallable<{idToken: string}>(this.functions, "createSessionToken",);
    const { data } = await callable({idToken: idToken});
  }

MacOS media keys not activating navigator.mediaSession.setActionHandler(…)

In our problem we set up our media key listeners with simple call to the setActionHandler function: navigator.mediaSession.setActionHandler('play', playCb). This works cross-browser on Windows, but with MacOS it doesn’t work on any browser I’ve tried– Firefox, Chrome, and Safari. I tried using the media keys on YouTube and they work just fine MacOS, across all three browsers. This problem exists across users so it’s not localized. Any ideas?

Array of objects stored in instance variable is considred empty even if its not [duplicate]

I am working with a controller that has a list of Objects, the problem is i cant access the Objects stored in the objList array of the CondController. Which gives me this error:

build_strategy_page.js:103 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'insert_cond')
    at build_conds (build_strategy_page.js:103:17)

Upon debugging i found out that there is problem with Values of the arrays in the CondController Instance
When i console log the instance of the object. At first glance it seems like the arrays of the object are empty but when i fold out the info, it is clear that they are not.

enter image description here

When i console.log lenght of the array “objList” it is 0 and when i console.log the array itself by calling the instance variable “condListController.objList”

i get a conflicted message again, where the console says [[prototype]]:Array(0) but shows values when pressed and folded out:

I am completely lost here i never had a bug so weird before, anyone have a clue what could be wrong?
enter image description here

const condListController = new CondController();
async function build_conds() {
  const json = await getJson("load_conditions");
  const buy_conds = json.buy_conds;
  const sell_conds = json.sell_conds;

  optimizer_params(buy_conds, "_BUY", "param_buy");
  // optimizer_params(sell_conds, "_SELL", "param_sell");
  console.log(buy_conds);

  for (let i = 0; i < buy_conds.length; i++) {
    console.log(buy_conds[i].fk_list_id, "cond");
    console.log(condListController, "condListController this outputs the controller");
    console.log(condListController.objList.length); // outputs 0
    console.log(condListController.objList); // but it is not empty
    let condManager = condListController.getKey(buy_conds[i].fk_list_id);
    condManager.insert_cond(buy_conds[i].indicator_json, which_row(buy_conds[i].list_row), buy_conds[i].condition_id);
  }
}


export class CondController {
  constructor() {
    this.objList = [];
    this.obj = {};
    //ensure incrementing id
    this.countArray = [];
  }
  count() {
    return this.countArray.length;
  }

  createCondManager(identifier, primary_key) {
    this.identifier = identifier;
    this.primary_key = primary_key;

    const taskManager = new CondManager(this.identifier, this.primary_key);
    this.objList.push(taskManager);

    // Assign the TaskManager instance to this.obj using the identifier as the key
    this.obj[this.identifier] = taskManager;

    // just pushing something of no value
    this.countArray.push(0);

    return taskManager;
  }

  addCond(identifier, text, column) {
    this.identifier = identifier;
    this.text = text;
    this.column = column;
    const current_cond_list = this.obj[this.identifier];
    current_cond_list.insert_cond(this.text, this.column);
  }

  getKey(key) {
    this.key = key;

    const result = [];
    for (let i = 0; i < this.objList.length; i++) {
      if (this.objList[i].primary_key === this.key) {
        return this.objList[i];
      }
    }
  }
}

class CondManager {
  constructor(identifier, primary_key) {
    this.primary_key = primary_key;
    this.identifier = identifier;
    this.conds = [];
  }
  insert_cond(text, column, id) {
    this.conds.push({ text, column, id });
  }
}


rxjs update observable of array after each iteration

I have an Observable containing an array that i use in the UI with an async pipe to display a table of contracts. One column in that table shows a status value which is ‘not processed’ on page load.

contracts$: Observable<ContractDto[]>

On view init I load the contracts from an API like this.contracts$ = this.api.getContracts()

That works fine, now to my problem:

Via a button click the user can start a process running over all contracts to perform an action per contract. Each action houses an API call and can take 1-3 seconds.

Now i want to update the view to show to the user which contracts are already processed so he gets an indicator on how far the process is. So i want to iterate over the contracts in that observable and update the status field to ‘processed’ when the action has been executed.

But i can’t find a way to iterate over the contracts observable and update this.contracts$ on each iteration. Only thing i could make work was iterating and processing one by one but only update this.contracts$ when all actions have been processed.

my current code looks like this:

// this only gets updated once all contracts have been processed
this.contracts$ = this.contracts$
            .pipe(
                // flatten array of contracts
                concatMap(contract => contract),

                // executing the process one by one; returning the updated contract
                concatMap(contract => this.deploy(contract)),

                // without toArray() i get an error on this.contracts$ assignment because 
                // ContractDto can not be assigned to ContractDto[] - which is correct.
                // and here is my missing link because I want to update this.contracts$ after EACH iteration.
                toArray(),
            )

Many thanks in advance for your time

PointerLockControls.js – TypeError: Cannot read properties of undefined (reading ‘lock’) at HTMLDivElement

I’m extremely new to Javascript and Three.js (and to posting on stackOverflow). I’m attempting to implement a first person camera using three.js by converting the example implementation of PointerLockControls.js found here:
PointerLockControls example

My issue is that the error ‘TypeError: Cannot read properties of undefined (reading ‘lock’)
at HTMLDivElement.’ is thrown – caused by line 204 of my code (full code below) which reads:

 // initialise locks: 
    const blocker = document.getElementById( 'blocker' );
    const instructions = document.getElementById( 'instructions' );
        
    instructions.addEventListener( 'click', function () {
    // LINE 204: ERROR
    this.controls_.lock;
    } );

The example defines this lock as:

instructions.addEventListener( 'click', function () {

                    controls.lock();

                } );

Previously, I analogously defined

instructions.addEventListener( 'click', function () {
            this.controls_.lock();
        } );

where PointerCamera.lock was defined as

lock() {
       this.controls.lock();
}

I’ve attempted to redefine my lock functions using const = function () {...}, which led to the type error occurring in the PointerLockControls.js file.

Any help would be greatly appreciated!

Full Javascript:

import * as THREE from '../three.js-r134/three.js-r134/build/three.module.js';
import { FirstPersonControls } from '../three.js-r134/three.js-r134/examples/jsm/controls/FirstPersonControls.js';
import { PointerLockControls } from '../three.js-r134/three.js-r134/examples/jsm/controls/PointerLockControls.js';

// class for handling the camera

// camera implemented using the example: https://threejs.org/examples/?q=pointerlock#misc_controls_pointerlock


// listener is domElement used to listen for mouse/touch events
class PointerCamera {
    constructor(camera, dElement, objects) {
        this.camera = camera;
        this.dElement = dElement
        this.objects = objects;
        this.raycaster = null;
        this.moveForward = false;
        this.moveBackward = false;
        this.moveLeft = false;
        this.moveRight = false;
        this.canJump = false;
        this.controls = null;

        //minHeight initialised to initial value of y-coordinate of camera
        this.minHeight = camera.position.y;


        // this.prevTime
        // may not need this if we pass it to the update from update in the main render

        this.velocity = new THREE.Vector3();
        this.direction = new THREE.Vector3();
        this.vertex = new THREE.Vector3();
        this.color = new THREE.Color();

        // initialise movement
        this.dElement.addEventListener( 'keydown', this.onKeyDown);
        this.dElement.addEventListener( 'keyup', this.onKeyUp);

        this.initControls();
    }

    initControls() {
        this.controls = new PointerLockControls(this.camera, this.dElement);

        // locks
        this.lock = function () {
            this.controls.lock();
        }

        this.unlock = function () {
            this.controls.unlock();
        }
    }

    changeMinHeight(newHeight) {
        const oldHeight = this.minHeight;
        this.minHeight = newHeight;

        return oldHeight;
    }

    // keydown function
    onKeyDown( event ) {

        switch ( event.code ) {

            case 'ArrowUp':
            case 'KeyW':
                this.moveForward = true;
                break;

            case 'ArrowLeft':
            case 'KeyA':
                this.moveLeft = true;
                break;

            case 'ArrowDown':
            case 'KeyS':
                this.moveBackward = true;
                break;

            case 'ArrowRight':
            case 'KeyD':
                this.moveRight = true;
                break;

            case 'Space':
                if ( canJump === true ) velocity.y += 350;
                this.canJump = false;
                break;

        }
    }
    
    //keyupfunction
    //if domElement doesn't work, try passing full document to the class.

    onKeyUp = function ( event ) {

        switch ( event.code ) {

            case 'ArrowUp':
            case 'KeyW':
                this.moveForward = false;
                break;

            case 'ArrowLeft':
            case 'KeyA':
                this.moveLeft = false;
                break;

            case 'ArrowDown':
            case 'KeyS':
                this.moveBackward = false;
                break;

            case 'ArrowRight':
            case 'KeyD':
                this.moveRight = false;
                break;

        }

    }

    update(timeElapsedS) {

        if (this.controls.isLocked === true) {

            // to adjust vertical acceleration, need to calculate whether on the ground or not.
            const delta = timeElapsedS; // time elapsed in seconds

            // may need to double check this hits 0.
            this.velocity.x -= this.velocity.x * 10 * delta;
            this.velocity.z -= this.velocity.z * 10 * delta;

            // simulate gravity: 
            this.velocity.y -= 9.8 * 100 * delta; // 100.0 = mass of player

            this.direction.z = Number(this.moveForward) - Number(this.moveBackward);
            this.direction.x = Number(this.moveRight) - Number(this.moveLeft);
            this.direction.normalize(); // ensures consistent movement in all directions


            if (this.moveForward || this.moveBackward) this.velocity.z -= this.direction.z * 400 * delta;
            if (this.moveLeft || this.moveRight) this.velocity.x -= this.direction.x * 400 * delta;


            // add object interaction with ray casting here
            
            // update camera position: 
            this.controls.moveRight( - this.velocity.x * delta);
            this.controls.moveForward( - this.velocity.z * delta);

            this.controls.getObject().position.y += ( this.velocity.y * delta ); // new behavior

            // detect if camera falls below minimum: 

            if ( controls.getObject().position.y < 10 ) {
                this.velocity.y = 0;
                this.controls.getObject().position.y = 10;
                this.canJump = true;
            }
        }
    }
}

class FirstPersonCameraDemo {
    constructor() {
        this.initialize_();
    }

    initialize_() {
        this.initializeRenderer_();
        this.initializeLights_();
        this.initializeScene_();
        this.initializeDemo_();

        this.previousRAF_ = null;
        this.raf_();
        this.onWindowResize_();
    }

    initializeDemo_() {
        this.controls_ = new PointerCamera(this.camera_, document.body, []);
        this.controls_.controls.lookSpeed = 0.8;
        this.controls_.controls.movementSpeed = 5;
        this.controls_.controls.heightCoef = 0;
        // const controlLock = function () {this.controls_.lock};

        // initialise locks: 
        const blocker = document.getElementById( 'blocker' );
        const instructions = document.getElementById( 'instructions' );
        
        instructions.addEventListener( 'click', function () {
            this.controls_.lock;
        } );

        this.controls_.controls.addEventListener( 'lock', function () {
            instructions.style.display = 'none';
            blocker.style.display = 'none';
        } );

        this.controls_.controls.addEventListener( 'unlock', function () {
            blocker.style.display = 'block';
            instructions.style.display = '';
        } );
        
        this.scene_.add(this.controls_.controls.getObject());
    }

    initializeRenderer_() {
        this.threejs_ = new THREE.WebGLRenderer({
            antialias: false,
        });
        this.threejs_.shadowMap.enabled = true;
        this.threejs_.shadowMap.type = THREE.PCFSoftShadowMap;
        this.threejs_.setPixelRatio(window.devicePixelRatio);
        this.threejs_.setSize(window.innerWidth, window.innerHeight);
        this.threejs_.physicallyCorrectLights = true;
        this.threejs_.outputEncoding = THREE.sRGBEncoding;
    
        document.body.appendChild(this.threejs_.domElement);

        window.addEventListener('resize', () => {
            this.onWindowResize_();
        }, false);


        // initialise CAMERA
        this.minHeight = 10;
        const fov = 60;
        const aspect = window.innerWidth / window.innerHeight;
        const near = 1.0;
        const far = 1000.0;
        this.camera_ = new THREE.PerspectiveCamera(fov, aspect, near, far);
        // minimum and default height (10 - change to variable later)
        this.camera_.position.set(0, this.minHeight, 0);

        this.scene_ = new THREE.Scene();
    }

    initializeScene_() {
        const loader = new THREE.CubeTextureLoader();
        const texture = loader.load([
            './bkg/bkg/red/bkg1_right1.png',
            './bkg/bkg/red/bkg1_left2.png',
            './bkg/bkg/red/bkg1_top3.png',
            './bkg/bkg/red/bkg1_bottom4.png',
            './bkg/bkg/red/bkg1_front5.png',
            './bkg/bkg/red/bkg1_back6.png'
        ]);

        this.scene_.background = texture;

        const planegeo = new THREE.PlaneGeometry(100, 100, 10, 10);
        // plane.castShadow = false;
        // plane.receiveShadow = true;
        planegeo.rotateX(-Math.PI / 2);
        const material = new THREE.MeshBasicMaterial( {color: 0xffff00, side: THREE.DoubleSide} );
        const plane = new THREE.Mesh( planegeo, material );
        this.scene_.add(plane);
    }

    initializeLights_() { 

        // his light: 
    const distance = 50.0;
    const angle = Math.PI / 4.0;
    const penumbra = 0.5;
    const decay = 1.0;

    let light = new THREE.SpotLight(
        0xFFFFFF, 100.0, distance, angle, penumbra, decay);
    light.castShadow = true;
    light.shadow.bias = -0.00001;
    light.shadow.mapSize.width = 4096;
    light.shadow.mapSize.height = 4096;
    light.shadow.camera.near = 1;
    light.shadow.camera.far = 100;

    light.position.set(25, 25, 0);
    light.lookAt(0, 0, 0);
    this.scene_.add(light);

    const upColour = 0xFFFF80;
    const downColour = 0x808080;
    light = new THREE.HemisphereLight(upColour, downColour, 0.5);
    light.color.setHSL( 0.6, 1, 0.6 );
    light.groundColor.setHSL( 0.095, 1, 0.75 );
    light.position.set(0, 4, 0);
    this.scene_.add(light);
    }

    onWindowResize_() {
        this.camera_.aspect = window.innerWidth / window.innerHeight;
        this.camera_.updateProjectionMatrix();

        this.threejs_.setSize(window.innerWidth, window.innerHeight);
    }

    raf_() {
        requestAnimationFrame((t) => {
            if (this.previousRAF_ === null) {
              this.previousRAF_ = t;
            }
      
            this.step_(t - this.previousRAF_);
            this.threejs_.autoClear = true;
            this.threejs_.render(this.scene_, this.camera_);
            console.log("just tried to render");
            this.threejs_.autoClear = false;
            this.previousRAF_ = t;
            this.raf_();
          }); 
    }

    step_(timeElapsed) {
        // console.log("in demo step");
        const timeElapsedS = timeElapsed * 0.01;
        // may need to change above to 0.001

        this.controls_.update(timeElapsedS);
    }
}

// run
let _APP = null;

window.addEventListener('DOMContentLoaded', () => {
    console.log("successful print");
    _APP = new FirstPersonCameraDemo();
});

HTML:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Trying to get basic FPS control</title>
        <style>
            body { margin: 0; }

            #blocker {
                position: absolute;
                width: 100%;
                height: 100%;
                background-color: rgba(0, 0, 0, 0.5);
            }

            #instructions {
                width: 100%;
                height: 100%;

                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;

                text-align: center;
                font-size: 14px;
                cursor: pointer;
            }
        </style>
    </head>
    <body>
        <div id="blocker">
            <div id="instructions">
                <p style="font-size:36px">
                    Click to play
                </p>
                <p>
                    Move: WASD<br/>
                    Jump: SPACE<br/>
                    Look: MOUSE
                </p>
            </div>
        </div>
        <script type="module" src="./fpsbasic.js"></script>
    </body>
</html>

Adding a function to the PHP Script stops script from running

The following Javascript is in PHP file on a website. The site will show images and I’d like it if the viewer clicks on an image, the image enlarges. Clicks again and it goes back to the original size. The images are in a table, like this:

<tr>
<td align="center" valign="middle"><img class="img-responsive" style="max-width:400px;width:100%"  
height="auto" src="/images/xyz.jpg" id="img1" onclick="enlargeImg()" 
</td>
</tr>

<script>
    function test() {
        //echo "test";
    }
        // Get the img object using its Id
        img = document.getElementById("img1");
        // Function to increase image size
     
        function enlargeImg() {
         
            img.style.transform = "scale(1.3)";
            // Animation effect
            img.style.transition = "transform 0.25s ease";
        $enlarged=true; 
    }
        // Function to reset image size
        function resetImg() {
            // Set image size to original
            img.style.transform = "scale(1)";
            img.style.transition = "transform 0.25s ease";
            $enlarged=false;
        }
</script>

This works (at least the enlarging). BUT if I uncomment the echo “test”; line in the test() function, the enlarging does not work. Why?

Thanks in advance

why is the error not being processed in async function?

const promiseAllAsyncAwait = async function() {
  if (!arguments.length) {
    return null;
  }
  let args = arguments;
  if (args.length === 1 && Array.isArray(args[0])) {
    args = args[0];
  }
  const total = args.length;
  const result = [];
  for (let i = 0; i < total; i++) {
    try {
      const res = await Promise.resolve(args[i]);
      if (res) {
        result.push(res);
      }
    } catch (err) {
      console.log(123);
      return err;

    }
  }
  return result;
};

const asyncTask1 = new Promise((resolve) => setTimeout(() => resolve('Task 1'), 1000));
const asyncTask2 = new Promise((resolve, reject) => setTimeout(() => reject('Error in Task 2'), 500));
const asyncTask3 = new Promise((resolve) => setTimeout(() => resolve('Task 3'), 1500));

(async () => {
  try {
    const results = await promiseAllAsyncAwait([asyncTask1, asyncTask2, asyncTask3]);
    console.log(results);
  } catch (error) {
    console.error('Error in promiseAllAsync:', error);
  }
})();

it should output 123 to the console, but it does not output.
it just outputs this error ‘[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason “Error in Task 2”.] {
code: ‘ERR_UNHANDLED_REJECTION’
}’

I want to remove an attribute at loading time if window width is lower than something, it doesn’t work

The following code should work as explained:
Links in the article should see its target attribute removed (so it displays in the browser and not the iframe) but it doesn’t. I make sure the window (with developper’s tool) is the appropriate size, reload with ctrl+r, and it doesn’t change.
I wish for this:

<a href="/glossaire/une-demarche-pionniere/" onclick="document.querySelector(&quot;iframe&quot;).removeAttribute(&quot;hidden&quot;)" target="iframe_glossary">démarche pionnière</a>

to loose its target attribute.

I tried:

<script>
if (screen.availWidth <= 604) {
   document.querySelector('p a').removeAttribute('target');
}
</script>

Is there any way to create one shared ResizeObserver for multiple Modules in javaScript

Basically, I have several JavaScript Modules that each contain a own ResizeObserver with a specific code only for that module.

Is it possible to create only one resize observer in the first module that is being loaded, and then in other modules add the necessary code in that first RersizeObserver?

The reason I’m asking is about performance – when the browser is resized, 4 observers are executed instead of just one.

Module1.js
Module2.js
Module3.js
Module4.js

//module1.js
    onResize() {
        const resizeObserver = new ResizeObserver(() => {
            globalThis.viewportWidth =  window.innerWidth;; 
            globalThis.viewportHeight = window.innerHeight;  
        });
        resizeObserver.observe(document.body);

    }


//module2.js
    onResize() {
        const resizeObserver = new ResizeObserver(() => {
            ...  
        });
        resizeObserver.observe(document.body);

    }


//module3.js
    onResize() {
        const resizeObserver = new ResizeObserver(() => {
            ...  
        });
        resizeObserver.observe(document.body);

    }


//module4.js
    onResize() {
        const resizeObserver = new ResizeObserver(() => {
            ...  
        });
        resizeObserver.observe(document.body);

    }

Function takes an object with a name property and returns an object

The task I have is:
The makeGuestList function takes an object with a name property whose value will be a string consisting of a first name and a last name, separated by a space. The function should return an object.

The function should remove the name property, replace it with firstName and lastName properties, as shown in the examples below
makeGuestList({ name: “Hannah Fry”, age: 46 });
// should return { firstName: “Hannah”, lastName: “Fry”, age: 46 }

My code is thus:

function makeGuestList(person) {
    const [firstName, lastName] = person.name.split(" ");
    return { "firstName": firstName, "lastName": lastName };
}

const guest = { name: "Ada Lovelace" };
console.log(makeGuestList(guest));

When I run the code I am getting the error message:
All other properties on the object are unchanged

✕ AssertionError: expected { firstName: ‘Ada’, …(1) } to deeply equal { firstName: ‘Ada’, …(3) }

Unable to selected other rows except first on Datatables with Iphone

Good afternoon.
I use this code to select a row in a jQuery datatable :

<script type="text/javascript">
            $(document).ready(function () {
                var table = $('#empTable').DataTable();
                $('#empTable').on('click', 'tr', function () {
                    if ($(this).hasClass('selected')) {
                        $(this).removeClass('selected');
                    } else {
                         $('#clientescelto').val(this.cells[0].innerHTML);
                        table.$('tr.selected').removeClass('selected');
                        $(this).addClass('selected');
                    }
                });

            });
</script>

It work fine (I can select any row of my datatable) both on Windows browsers and Apple Tablet.
But on Iphone I’m able only to select the first row of the list, I’ve not effects trying to select other rows.

Any idea?

Thanks

Chico

I’ve tried on other Iphone models, but the problem is not solved.