Express Session Management: userid is undefined

Server (omitted the helping functions as they are not relevant to the question):

const express = require('express');
const cors = require('cors');
const app = express();
const sessions = require('express-session');
const cookieParser = require('cookie-parser');
const bcrypt = require('bcrypt');
const mysql = require('mysql');
require('dotenv').config();

const con = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: process.env.PASSWORD,
  database: "password"
});
const oneDay = 1000 * 60 * 60 * 24

app.use(express.json());
app.use((req, res, next) => {
  res.setHeader('Access-Control-Allow-Origin', 'http://127.0.0.1:5500');
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
  res.setHeader('Access-Control-Allow-Credentials', 'true')
  next();
});
app.use(sessions({
  secret: "secret",
  saveUninitialized:true,
  cookie: { path : '/', maxAge: oneDay },
  resave: false,
}));
app.use(cookieParser());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

app.get('/', (req, res) => {
  res.send('Welcome to the server!');
});

//signin function, gets hashed password from database and compares it with user supplied password.
app.post('/compare', async (req, res) => {
  const { password, user } = req.body;

  try {
    const hashDB = await getHash(user);
    const confirm = await confirmHash(password, hashDB);
    //if user supplied password matches DB password, set session info and send session token to client.
    if (confirm) {
      req.session.userid = user;
      res.cookie('sessionID', req.sessionID, { maxAge: oneDay, httpOnly: true });
      res.send({ success: true });
    } else {
      res.status(401).send({ success: false, message: 'Authentication failed' });
    }
  } catch (error) {
    console.error('Error:', error);
    res.status(500).send('Confirm failed');
  }
});

//if user session is valid, get session info.
app.get('/protected', (req, res) => {
  const userId = req.session.userid;
  if (userId) {
    res.send(`User ID: ${userId}`);
  } else {
    res.status(401).send('Unauthorized');
  }
});

const port = 8080;
app.listen(port, () => {
  console.log(`Server is listening on port ${port}`);
});

Client :

function signin(username, password) {
  const compareRequestBody = JSON.stringify({ user: username, password });

  const compareRequestOptions = {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Content-Length': compareRequestBody.length,
    },
    body: compareRequestBody,
  };

  fetch('http://localhost:8080/compare', compareRequestOptions)
    .then(response => response.json())
    .then(data => {
      console.log(data); 
    })
    .catch(error => {
      console.error('Error:', error);
    });
}

function getProfile(){
  const getProfileOptions = {
    method: 'GET',
    credentials: 'include'
  }
  fetch('http://localhost:8080/protected', getProfileOptions)
    .then(response=>{
      if (response.ok){
        console.log(response)
      } else {
        console.error('Error: ', response.status)
      }
    })
    .catch(error => {
      console.error('Error: ', error)
  })
}

I have a server which upon a successful user log in, will set req.session.userid = user, and send the session token to the client. After I log in, I can see the sessionID in the Set-Cookie header, however when I try to access the /protected endpoint with getProfile(), req.session.userid is undefined.

Troubling With Walls

So, I am currently just testing some things out and experiencing an overlap error. I can seem to find the problem and hope someone else could help. If you can, thank you. Here’s the code, make a remix of it if you want to.

https://studio.code.org/projects/gamelab/Xz18Oi1d5n8QDBZCFQcRYWQW03Yo_AWHSIcOTNykJno

I had hoped for the walls to work accordingly as I would like it to work which is just two walls the player(s) can’t go through and two walls that damages the player(s) but upon both player 1 & 2 dying, I received an overlapping error and I don’t know why it is happening.

d3.csvParse inside d3.text => problem of sync

I am not expert in d3.js and i have to modify a program using it.

I have not found a good answer for my problem, i need to modify a file before to parse it: so i use this piece of code: (d3.js v4)

    d3.text(file, function (d) {
        //modify the content of file loaded
        d = d.replace(/ (édito)/g, "_edito")
            .replace(/ (startup)/g, "_startup");
        //parse after
        d3.csvParse(d, function (d) {
            console.log(d);
        });
    });
    console.log("next");

but the problem is d3.text, d3.csv are asynchronous and so console.log("next") is executed before the content of file line par line with console.log(d).

How i can wait the result of d3.txt ? before to continue…and without blocking the UI

I am using AsyncSelect from “react-select/async”. Is there a way I can use legend(fieldset)

<AsyncSelect
            className={className}
            loadingMessage={() => loadingMsg}
            value={value}
            placeholder={placeholder}
            isLoading={isCustomLoading || isLoading}
            onChange={onChange}
            isClearable
        />

I am working on a project. where I have to put but label(legend). Is there a way or someone has already face or done the same thing and How can I use label on other build in library or component in reactjs. I have one more use while using simple HTML fieldset and Legend in my project it’s not working.

Inconsistent behavior of the URL constructor between Safari and Chrome, when working with custom URL schema

I am trying to figure out why there is a difference between two identical URL constructor calls in Safari and Chrome

Here is the example from Safari:

Safari

And here is an example from Chrome:

Chrome

I’m working on an application that embeds inside a webview for various mobile platforms such as Android and Ios. This behavior of the URL constructor creates problems.

As you can in the chrome pathname includes localhost which is incorrect, the hostname and host are also empty, in safari everything seems fine

I was trying to set up manifest.json locally to test is there a way to control this behavior by registering custom URL schema, also I was trying to play with navigator.registerProtocolHandler, here is the link to the docs.

Basketball Game Phaser JS

I’m making a basketball game and the shooting doesn’t seem to be working. I have spent a very long time on this and I’m almost at my deadline so I need a little bit of help.

If anyone could help me that would be very appreciated.

Here’s the code of the game.

It’s in the Phaser CE Framework, and this is the main JS file.

// To-Do
// Fix player movement

let r = document.querySelector(':root');
let rs = getComputedStyle(r);
viewHeight = rs.getPropertyValue('--fh');
viewWidth = rs.getPropertyValue('--fw');


let game = new Phaser.Game(1000, 1000, Phaser.CANVAS, 'my-game', { preload: preload, create: create, update: update });


let x0, y0, x1, y1, vX, vY, g;
let dX, dY, t, vX0;
let xNow, yNow;

// declare other global variables (for sprites, etc.)
let allowMovement = true;

let arrowKey;
// let shootKey;
let player;
let player1;
let player2;

let hoop;

let groundnewSpriteplayer;
let ball; 

let playerCount = 2;
let playerList = {};

let keyW;
let keyA;
let keyD;
 
let keyI;
let keyJ;
let keyL;
 
let KeyT;
let keyF;
let keyH;




let score = {
    player1: {
        score: 0
    },
    player2: {
        score: 0
    }
}


// preload game assets - runs one time when webpage first loads
function preload() {
    game.load.image('player', 'assets/images/real person.png');
    game.load.image('player', 'assets/images/player_temp.png');
    game.load.image('ground', 'assets/images/court_temp.png');
    game.load.image('cursorPosition', 'assets/images/bigball.png');
    game.load.image('ball', 'assets/images/Ball.png');
    game.load.image('hoop', 'assets/images/Hoop.png');     
    game.load.image('scoreboard', 'assets/images/scoreboard.png');
    game.load.image('stands', 'assets/images/Stands.png');
    game.load.image('ref', 'assets/images/ref.png');
    game.load.image('background', 'assets/images/Background.png');
    game.load.image('streetcourt', 'assets/images/streetcourt.png');
    game.load.audio('dribbling', 'assests/sounds/dribbling.wav');
    game.load.audio('whistle' , 'assets/sounds/whistle.wav');
    game.load.image('streethoop', 'assets/image/streethoop.png');
    game.load.image('waving', 'assets/images/standsanimation.png');
    game.load.image('0', 'assets/images/number/0.png');
    game.load.image('1', 'assets/images/number/1.png');
    game.load.image('2', 'assets/images/number/2.png');
    game.load.image('3', 'assets/images/number/3.png');
    game.load.image('4', 'assets/images/number/4.png');
    game.load.image('5', 'assets/images/number/5.png');
    game.load.image('6', 'assets/images/number/6.png');
    game.load.image('7', 'assets/images/number/7.png');
    game.load.image('8', 'assets/images/number/8.png');
    game.load.image('9', 'assets/images/number/9.png');
    
    // Shorts and Jerseys
    
    game.load.image('heatS', 'assets/images/shorts/heat.png');
    game.load.image('heatJ', 'assets/images/jerseys/heat.png');
    game.load.image('bucksS', 'assets/images/shorts/bucks.png');
    game.load.image('bucksJ', 'assets/images/jerseys/bucks.png');
    game.load.image('mavsS', 'assets/images/shorts/mavs.png');
    game.load.image('mavsJ', 'assets/images/jerseys/mavs.png');
    game.load.image('grizzliesS', 'assets/images/shorts/grizzlies.png');
    game.load.image('grizzliesJ', 'assets/images/jerseys/grizzlies.png');
    game.load.image('clippersS', 'assets/images/shorts/clippers.png');
    game.load.image('clippersJ', 'assets/images/jerseys/clippers.png');
    game.load.image('warriorsS', 'assets/images/shorts/warriors.png');
    game.load.image('warriorsJ', 'assets/images/jerseys/warriors.png');
    game.load.image('lakersS', 'assets/images/shorts/lakers.png');
    game.load.image('lakersJ', 'assets/images/jerseys/lakers.png');
    game.load.image('cavsS', 'assets/images/shorts/cavs.png');
    game.load.image('cavsJ', 'assets/images/jerseys/cavs.png');
    game.load.image('bullsS', 'assets/images/shorts/bulls.png');
    game.load.image('bullsJ', 'assets/images/jerseys/bulls.png');
    game.load.image('jazzS', 'assets/images/shorts/jazz.png');
    game.load.image('jazzJ', 'assets/images/jerseys/jazz.png');
    game.load.image('hornetsS', 'assets/images/shorts/hornets.png');
    game.load.image('hornetsJ', 'assets/images/jerseys/hornets.png');
    game.load.image('blazersS', 'assets/images/shorts/blazers.png');
    game.load.image('blazersJ', 'assets/images/jerseys/blazers.png');
    game.load.image('knicksS', 'assets/images/shorts/knicks.png');
    game.load.image('knicksJ', 'assets/images/jerseys/knicks.png');
    game.load.image('celticsS', 'assets/images/shorts/celtics.png');
    game.load.image('celticsJ', 'assets/images/jerseys/celtics.png');
    game.load.image('hawksS', 'assets/images/shorts/hawks.png');
    game.load.image('hawksJ', 'assets/images/jerseys/hawks.png');
    game.load.image('kingsS', 'assets/images/shorts/kings.png');
    game.load.image('kingsJ', 'assets/images/jerseys/kings.png');
    game.load.image('magicS', 'assets/images/shorts/magic.png');
    game.load.image('magicJ', 'assets/images/jerseys/magic.png');
    game.load.image('pistonsS', 'assets/images/shorts/pistons.png');
    game.load.image('pistonsJ', 'assets/images/jerseys/pistons.png');
    game.load.image('nuggetsS', 'assets/images/shorts/nuggets.png');
    game.load.image('nuggetsJ', 'assets/images/jerseys/nuggets.png');
    game.load.image('raptorsS', 'assets/images/shorts/raptors.png');
    game.load.image('raptorsJ', 'assets/images/jerseys/raptors.png');
    game.load.image('rocketsS', 'assets/images/shorts/rockets.png');
    game.load.image('rocketsJ', 'assets/images/jerseys/rockets.png');
    game.load.image('sixersS', 'assets/images/shorts/sixers.png');
    game.load.image('sixersJ', 'assets/images/jerseys/sixers.png');
    game.load.image('spursS', 'assets/images/shorts/spurs.png');
    game.load.image('spursJ', 'assets/images/jerseys/spurs.png');
    game.load.image('sunsS', 'assets/images/shorts/suns.png');
    game.load.image('sunsJ', 'assets/images/jerseys/suns.png');
    game.load.image('thunderS', 'assets/images/shorts/thunder.png');
    game.load.image('thunderJ', 'assets/images/jerseys/thunder.png');
    game.load.image('wolvesS', 'assets/images/shorts/wolves.png');
    game.load.image('wolvesJ', 'assets/images/jerseys/wolves.png');
    game.load.image('wizardsS', 'assets/images/shorts/wizards.png');
    game.load.image('wizardsJ', 'assets/images/jerseys/wizards.png');
    game.load.image('pelicansS', 'assets/images/shorts/pelicans.png');
    game.load.image('pelicansJ', 'assets/images/jerseys/pelicans.png');
    game.load.image('netsS', 'assets/images/shorts/nets.png');
    game.load.image('netsJ', 'assets/images/jerseys/nets.png');
    game.load.image('pacersS', 'assets/images/shorts/pacers.png');
    game.load.image('pacersJ', 'assets/images/jerseys/pacers.png');

    //Shoes
    game.load.image('Green Shoes', 'assests/images/shoes/Green Shoes.png');
    game.load.image('Black_White Shoes', 'assests/imges/shoes/black , white Shoes.png');
    game.load.image('Black Shoes', 'assests/images/shoes/Black shoes.png');
    game.load.image('Blue Shoes', 'assests/images/shoes/blue Shoes.png');
    game.load.image('Bright_purple Shoes', 'assests/images/shoes/bright purple Shoes.png');
    game.load.image('Grey Shoes', 'assests/images/shoes/Grey Shoes.png');
    game.load.image('Lime_Green Shoes', 'assests/images/shoes/Lime Green shoes.png');
    game.load.image('Orange Shoes', 'assests/imaages/shoes/Orange Shoes.png');
    game.load.image('Pink Shoes', 'assests/images/shoes/Pink Shoes.png');
    game.load.image('purple_blue Shoes', 'assests/images/shoes/purple and blue Shoes.png');
    game.load.image('Purple Shoes', 'assests/imaages/shoes/Purple Shorts.png');
    game.load.image('Red Shoes', 'assests/imaages/shoes/Red Shoes.png');
    game.load.image('Sky_Blue Shoes', 'assests/imaages/shoes/SkyBlue shoes.png');
    game.load.image('Teal Shoes', 'assests/imaages/shoes/Teal  shoes.png');
    game.load.image('White Shoes', 'assests/imaages/shoes/White shoes.png');
    game.load.image('Yellow Shoes', 'assests/imaages/shoes/Yellow Shoes.png');
   
       

}

// create game world - runs one time after preload finishes
function create() {
    
    arrowKey = game.input.keyboard.createCursorKeys();
    // shootKey = game.input.keyboard.addKey(Phaser.KeyCode.SPACEBAR);

    keyW = game.input.keyboard.addKey(Phaser.KeyCode.W);
    keyA = game.input.keyboard.addKey(Phaser.KeyCode.A);
    keyD = game.input.keyboard.addKey(Phaser.KeyCode.D);

    keyY = game.input.keyboard.addKey(Phaser.KeyCode.Y);
    keyG = game.input.keyboard.addKey(Phaser.KeyCode.G);
    keyJ = game.input.keyboard.addKey(Phaser.KeyCode.J);


    
    // background

    background = game.add.sprite(0,0, 'background');

    // make Ground
    ground = game.add.sprite(0,300, 'ground');

    // streetcourt = game.add.sprite(0,300, 'streetcourt', false);

    // Stands
    
    stands = new Sprite(0,95, 'stands', true);
    stands.animations.add('moving', [0, 1, ], 10, true);
    
    
    // stands.height = 30 * 7;
    // stands.width = 40 * 20;
    


    // Ref

    ref = new Sprite(300, 250, 'ref', true);
    // ref.height *= 2;
    // ref.width *= 2;



    // Scoreboard

    scoreboard = new Sprite(300, 0, 'scoreboard', true);
    // scoreboard.height = 50 * 3;
    // scoreboard.width = 75 * 3;
    console.log(scoreboard);

    // numbers 

    n1 = new Sprite(300,0, '1', false);
    n2 = new Sprite(300,0, '2', false);
    n3 = new Sprite(300,0, '3', false);
    n4 = new Sprite(300,0, '4', false);
    n5 = new Sprite(300,0, '5', false);
    n6 = new Sprite(300,0, '6', false);
    n7 = new Sprite(300,0, '7', false);
    n8 = new Sprite(300,0, '8', false);
    n9 = new Sprite(300,0, '9', false);
    n0 = new Sprite(300,0, '0', false);


    

    // Players

    player1 = new Player(100, 100, 'player');
    player2 = new Player(100, 100, 'player');

    player1.height *= 2.0;
    player1.width *= 1.5;

    player2.height *= 2.0;
    player2.width *= 1.5;

    playerList = {
        player1: player1,
        player2: player2,
    }


    player1.shootKey = game.input.keyboard.addKey(Phaser.KeyCode.F1);
    player2.shootKey = game.input.keyboard.addKey(Phaser.KeyCode.F10);
   

    // Ball
    
    ball = new Sprite(100, 300, 'ball', true);
    // ball.gravity = 0.3;
    ball.gravity = 0.1;
    ball.control = {
        controller: player1,
        inControl: true
    };
    ball.bounceVelocity = 5;
    // ball.scale = 1/2;
    // ball.width  = 8;
    // ball.height = 8;

    // console.log(ball)
    
    
    cursorPosition = game.add.sprite(800, 150, 'cursorPosition');
    cursorPosition.visible = false;
    // cursosrPosition.rotation = 16;

    testItem = game.add.sprite(760, 194, 'cursorPosition');
    testItem.width = 10;
    testItem.height = 20;
    testItem.Collision = true;
    testItem.visible = false;

    // break

    //Hoop

    streethoop = new Sprite(715, 115, 'streethoop', false);
    streethoop.height = 300;
    streethoop.width = 150;
    streethoop.visible = false;

    hoop = new Sprite(715, 115, 'hoop', true);
    hoop.height = 300;
    hoop.width = 150;
    hoop.visible = true;
    // console.log(`Hoop height: ${hoop.height}`);
   
}





// update game - runs repeatedly in loop after create finishes
function update() {

    // player1.height *= 1.002;
    // player1.width *= 1.002;
    
    for (let i = 1; i <= playerCount; i++) {
        let player = playerList['player' + i]; /* Establish player */
        gravity(player);
        applyFriction(player);
        collision(player);
        keyboardInput(player);
        
    }

    gravity(ball);

    // Movement

    movement(player1, arrowKey.right, arrowKey.left, arrowKey.up, false);
    movement(player2, keyD, keyA, keyW);
    // movement(player3, keyG, keyJ, keyY);
    //movement(player4, keyFOUR, keySIX, keyEIGHT);
   
    
    
    
    for (let i = 1; i <= playerCount; i++) {
        let player = playerList['player' + i];
        applyVelocity(player);
    }
    
    
    hoopCollision(ball, cursorPosition); // Fix this function so it doesn't extend below the hoop

    // keyboardInput();
    applyVelocity(ball);
    ballControl();
    ballCollision();
}


// Stands 
// stands.animations.play('moving');


// Helper Functions

function Key(key) {
    if (key == undefined) return;
    return game.input.keyboard.addKey(Phaser.KeyCode.key);
}

function ballControl() {
    if (ball.control.inControl) {
        ball.x = ball.control.controller.x + ball.control.controller.width - (ball.width / 2);
        ball.y = ball.control.controller.y + ball.control.controller.height / 10;
        ball.velocityY = 0;
        ball.bounceVelocity = 5; 
    }
    if (ball.bounceVelocity < 0) {
        ball.bounceVelocity = 0;
        ball.velocityY = 0;
        ball.velocityX = 0;
    }
}

function keyboardInput(entity) {
    // if (entity.x > 512) {
    //     handleShooting(entity, 2, -6.2);
    // }

    handleShooting(entity);

    // console.log(`Y ${entity.y}`);
}

// function initializePositions() {
//     x0 = ball.x
//     y0 = ball.y
//     x1 = cursosrPosition.x - 10;
//     y1 = testItem.y;

//     vX = 5;
//     vY = 10;
//     g = ball.gravity

//     dX = x1 - x0;
//     dY = y1 - y0;
//     t = (2 * vY) / g;
//     vX0 = dX / t;
// }

// function updateShooting() {
//     let tNow = game.time.totalElapsedSeconds();
//     let dt = tNow - tStart;
// }

function handleShooting(entity) {
    if (entity.shootKey.isDown && ball.control.inControl && ball.control.controller == entity) {
        
        ball.dy += ball.gravity;
        ball.dx = (cursorPosition.x - ball.x);
    
        ballNorm = sqrt(ball.dx^2 + ball.dy^2);
        ball.dx /= ballNorm;
    
    
        ball.x += ball.dx;
        ball.y += ball.dy



    }
}


function Player(x, y, key) {
    let newPlayer = new Sprite(x, y, key, true);
    newPlayer.x = x;
    newPlayer.y = y;
    newPlayer.velocityX = 0;
    newPlayer.velocityY = 0;
    newPlayer.movementSpeed = 4;
    newPlayer.gravity = 1;
    newPlayer.isTouchingGround = false;
    newPlayer.jumpVelocity = 20;

    return newPlayer;
}

function Sprite(x, y, key, visible) {
    let newSprite = game.add.sprite(x, y, key);
    if (!visible) newSprite.visible = false;
    newSprite.isTouching = function(collider) {
        collider.left = collider.x;
        collider.right = collider.x + collider.width;
        collider.up = collider.y;
        collider.down = collider.y + collider.height;

        newSprite.left = newSprite.x;
        newSprite.right = newSprite.x + newSprite.width;
        newSprite.up = newSprite.y;
        newSprite.down = newSprite.y + newSprite.height;

        let touchingRight = false;
        let touchingLeft = false;
        let touchingUp = false;
        let touchingDown = false;

        let touching = false;

        if (newSprite.right > collider.left) touchingRight = true;
        if (newSprite.left < collider.right) touchingLeft = true;

        if (newSprite.up < collider.down) touchingUp = true;
        if (newSprite.down > collider.up) touchingDown = true;

        if (touchingRight && touchingLeft && touchingUp && touchingDown) touching = true;
        return touching;
    }

    return newSprite;
}

function applyVelocity(entity) {
    if (entity.velocityX == null) return;
    entity.y += entity.velocityY;
    entity.x += entity.velocityX;
    // if (entity = player1) {
    //     console.log(`AppVelocityVelocityX: ${entity.velocityX}`);
    //     console.log(`AppVelocityEntityX ${entity.x}`);
    // }
}

function gravity(entity) {
    // Applies gravity to the given entity, usually the player or an enemy
    if (entity.gravity == null) return;
    entity.velocityY += entity.gravity;
}

function collision(entity) {
    if (ground.y + ground.height / 2 < entity.y + entity.height + entity.velocityY) {
        entity.velocityY = 0;
        entity.isTouchingGround = true;
        entity.y = ground.y + ground.height / 2 - entity.height;
    }
    if(ball.isTouching(entity) && !ball.control.inControl) {
        ball.control.inControl = true;
        ball.control.controller = entity; 
    }
}

function checkWallCollision(entity, right, left, up) {
    if (entity.x <= 0) {
        if (left.isDown) {
            entity.velocityX = 0;
        }
    }
    if (entity.x >= game.width - entity.width) {
        if (right.isDown) {
            entity.velocityX = 0;
        }
    }
    ballCollision();
}

function ballCollision() {
    if (ball.y >= ground.y + ground.height / 2 - ball.height) {
        jump(ball, ball.bounceVelocity, true);
        ball.bounceVelocity -= 1;
        ball.y = ball.y = ground.y + ground.height / 2 - ball.height
        if (ball.bounceVelocity <= 0) ball.y = ball.y = ground.y + ground.height / 2 - ball.height
    }
}



function movement(entity, right, left, up, log) {
    entity.moveRight = false;
    entity.moveLeft = false;
    entity.tryJump = false;

    if (right.isDown) entity.moveRight = true;
    if (left.isDown) entity.moveLeft = true;
    if (up.isDown) entity.tryJump = true;

    if (entity.moveRight) entity.velocityX += entity.movementSpeed;
    if (entity.moveLeft) entity.velocityX -= entity.movementSpeed;

    if (entity.tryJump) jump(entity, entity.jumpVelocity, false);

    if (log == undefined) log = false;
    if (log) {
        for (let i = 0; i < 50; i++) console.log("");
        console.log(`Movement Speed: ${entity.movementSpeed}`);
        console.log(`velocityX: ${entity.velocityX}`);
        
    }

    checkWallCollision(entity, right, left, up);
}

function jump(entity, velocity, override) {
    if (!override) {
        if (!entity.isTouchingGround) return;
    }
    if (entity == undefined) return;
    if (velocity == undefined) return;

    entity.velocityY -= velocity;
    entity.isTouchingGround = false;
    return;
    
    
}

function applyFriction(entity) {
    if (entity.velocityX > 6) entity.velocityX =  6;
    if (entity.velocityX < 6) entity.velocityX = -6;
    entity.velocityX = 0;

    if (entity.velocityX > 0) entity.velocityX -= 1;
    if (entity.velocityX < 0) entity.velocityX += 1;

}


function moveTowardSolidEntity(entity, ground) {
    
}

function hoopCollision(entity, hoop) {
    if (entity.x + entity.width >= hoop.x) {
        if (entity.y + entity.height >= hoop.y) {
            if (entity.y <= hoop.y + hoop.height) {
                return entity.velocityX *= -1;
            }
        }

    }

     if (ball.x <= testItem.x + testItem.width) {
         if (ball.x + ball.width >= testItem.width) {
             return ball.velocityX *= -1;
        }
     }
    if (ball.x <= testItem.x + testItem.width) {
        if (ball.x + ball.width >= testItem.x) {
            if (ball.y + ball.height >= testItem.y) {
                if (ball.y<= testItem.y + testItem.width) {
                    return ball.velocityX *= -1;
                }
            }
        }
    }

     if (ball.y + ball.height >= testItem.y) {
         if (ball.y<= testItem.y + testItem.width) {
             return ball.velocityX *= -1;
         }
     }

    if (entity.x + entity.width >= hoop.x) {
        if (entity.x <= hoop.x + hoop.width) {
            // If good on the x


            if (entity.y + entity.height >= hoop.y) {
                if (entity.y + entity.height >= hoop.y + 10) {
                    if (entity.y <= hoop.y - hoop.height) {
                        entity.velocityY *= -1;
                    }
                }
            }
        }
    }
}

function setScoreboardNumber(score) {
    
}


I tried to fix it and it did not work.

When you shoot nothing happens and I cannot for the life of me figure it out.

Why isn’t my JavaScript code modifying the HTML canvas element on my PythonAnywhere Django website?

on pythonAnywhere with django JavaScript doesn’t interact with html canvas

i’m making a website on pythonanywhere using Django framework, my html template has canvas element in it and it is referenced in js static file modifying the canvas, when page is loaded canvas has no changes but script is loaded

website

here is how default template looks

<!DOCTYPE html>
<html lang="en">
<head>
    {% load static %}
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{% block title %}{% endblock %}</title>
    <link rel="stylesheet" href="{% static 'style.css' %}">
    <link rel="icon" type="image/x-icon" href="{% static 'MEGALUL.ico' %}">
</head>
<body onload="Main()">
    <canvas id="canvas"></canvas>
    <div class="wrapper">
        <header>
            <img src="{% static 'logo.png' %}" width="50px" height="50px">
            cudeCoder
            <div id="space"></div>
            <a href="https://cudecoder.pythonanywhere.com">home</a>
            <a href="https://cudecoder.pythonanywhere.com/projects">&#160 projects</a>
        </header>
        <main>
            {% block content %}{% endblock %}
        </main>
    </div>
    <script type="text/javascript" src="{% static 'script.js' %}">
    </script>
</body>
</html>

this is how script.js looks

ctx = canv.getContext('2d');

canv.width = window.innerWidth;
canv.height = window.innerHeight;
function clear(){
    //background color
    const bg = ctx.createLinearGradient(window.innerWidth/2,0,window.innerWidth/2,window.innerHeight);
    //color backround
    bg.addColorStop(0, "#000014");
    bg.addColorStop(1, "#100333");
    //fill rect with bg
    ctx.fillStyle = bg;
    ctx.fillRect(0, 0, window.innerWidth, window.innerHeight);
}
function stars(amount){
    let starsArr = []
    for(i=0;i<amount;i++){
        starsArr[i] = [Math.round(window.innerWidth*Math.random()),Math.round(window.innerHeight*Math.random())];
    }
    return starsArr;
}
function draw(){
    for(i=0;i<AllStars.length;i++){
        ctx.fillStyle = 'white';
        ctx.beginPath();
        ctx.arc(AllStars[i][0], AllStars[i][1], 5*Math.random(), 0, 2 * Math.PI);
        ctx.stroke();
        ctx.fill();
    }
}
function Main(){
    clear();
    AllStars = stars(30);
    draw();
    console.log("script loaded");
}

i tried adding console.log to script and it works just fine printing out inputted text

How to determine if an array index is within n positions from another index?

I am working on a circular carousel. Given an array of n items, n>6 in my case, i want to calculate all the items within the array that are less than or equal to 3 positions away from a particular index (currentIndex) in a circular fashion e.g.

//  currentIndex = 0
//  i       0    1    2    3    4    5    6    7    8    9   
// --------------------------------------------------------
// offset   0   +1   +2   +3   +3   +3   +3   -3   -2   -1

In the above example, 0 is the currentIndex. Indices 1,2,3 are within currentIndex + 3 places. Also, indices 7, 8, 9 are also within currentIndex – 3 positions in a circular fashion. All other indices that lie out side the range are considered to be of value 3. These positive and negative values will ultimately map to positions on the screen.

I have written the following function to calculate the offset position of a given index relative to a currentIndex

function getOffset(currentIndex: number, index: number, length: number) {
  const diff = index - currentIndex;

  if (diff === 0) {
    return 0;
  } else if (diff < 0) {
    if (diff < -3) {
      return Math.min(length - currentIndex + index, 3);
    } else {
      return Math.min(diff, 3);
    }
  } else {
    if (diff < length - 3) {
      return Math.min(diff, 3);
    } else {
      return Math.max(diff - length, -3);
    }
  }
}

// getOffset(0, 0, 10) -> 0
// getOffset(0, 1, 10) -> 1
// getOffset(0, 9, 10) -> -1
// getOffset(0, 6, 10) -> 3

This algorithm works but is verbose. Is there a simpler way to do this?

Submitting form data that includes files/images to a back end server function in google app script

As the title states, I’m trying to submit some form data to a back end server function to handle that data and do what I want with it. This data will also occasionally hold either images or files. The files and image handling is what I’m having the most trouble with. The issue I’m running in to is that, because this is in google app script, all of the more common ways of doing this, such as using the File API, is not available to me, and I’m not sure of similar methodologies to the File API in google app script.

What’s supposed to happen after the form is successfully submitted is that all of the information, besides the files and images are saved to a google sheet, and an email is sent out, populated with all of the data from the form. Everything worked successfully until I needed to potentially have files or images sent with the email as well.

My thought process was, on the front-end, have the images saved to google drive, and then, when I needed them in the code, I could pull them out of the folder after passing their file IDs down to the back end function. Pulling them from their file IDs would be done in the back end server function. The issue is just actually getting the files saved INTO google drive, as nothing I’ve done has been successful so far. I am also open to other suggestions.

I haven’t been able to find a suitable solution anywhere, and would really appreciate some assistance. I can provide further details as necessary. Below is my front end function:

function saveAlert(){
    let out = []
    //Setting controls object to each of the html input elements in the form
    let controls = {
      alertSelect: document.getElementById('alertSelect'),
      alertLocation: document.getElementById('alertLocation'),
      alertCode: document.getElementById('alertCode'),
      servicesAffected: document.getElementById('servicesAffected'),
      alertAddress: document.getElementById('alertAddress'),
      alertSubject: document.getElementById('alertSubject'),
      alertBody: tinymce.activeEditor.getContent(),
      alertDate: document.getElementById('alertDate'),
      alertEndDate: document.getElementById('alertEndDate'),
      imageUpload: document.getElementById('imageUpload'),
      userEmail: document.getElementById('userEmail'),
    }
    //If-check to make sure form is filled out properly
    if(validateInput(controls)){
      let modalSpinner = document.getElementById('modalSpinner')
      modalSpinner.hidden = false
      let alertDateFinal = controls.alertDate.value.replaceAll('-','/')
      let alertEndDateFinal = controls.alertEndDate.value.replaceAll('-','/')
      alertDate.value === '' ? new Date(alertDateFinal).toLocaleDateString() : new Date(alertDateFinal)
      alertEndDate.value === '' ? new Date(alertEndDateFinal).toLocaleDateString() : new Date(alertEndDateFinal)
      
      //My attempt
      let fileInput = controls.imageUpload;
      let formData = new FormData();

      for (let i = 0; i < fileInput.files.length; i++) {
        let file = fileInput.files[i];
        formData.append('images[]', file, file.name);
      }

      //Creating new record based on values in the controls object
      let record = {
        'Alert Type': controls.alertSelect.value,
        'Alert Location': controls.alertLocation.value,
        'Alert Code': controls.alertCode.value,
        'Services Affected': controls.servicesAffected.value,
        'Alert Address': controls.alertAddress.value,
        'Alert Subject': controls.alertSubject.value,
        'Alert Details': controls.alertBody,
        'Alert Date': alertDateFinal,
        'Alert End Date': alertEndDateFinal,
        'User Email': controls.userEmail.value,
        //This causes an error in the code
        'Images': formData,
        'Alert Active': true
      }
    
      //Pushing the record to the server side function 'saveAlerts()', which adds the alert created from the form to the google sheet
      out.push(record)      
      google.script.run.withSuccessHandler(clearForm).saveAlerts(out)
      
    } else{
      window.alert('Please Check Input')
    }
  }

And this is my server side function. I haven’t updated anything yet, as I haven’t been able to pass the files/images to it successfully, but it’s important for context:

function saveAlerts(data) {
  Logger.log(data)
  //Gets all the data in the alerts sheet
  let sheetData = alerts.getDataRange().getDisplayValues()
  //Get keys from the first row of the sheet
  let keys = sheetData[0]
  //For each alert in the array, create a temporary array containing the values for each column in the sheet
  data.forEach(el => {
    let temp = []
    keys.forEach(key => {
      temp.push(el[key])
    })
    //Append the temporary array as a new row in the sheet
    alerts.appendRow(temp)
  })

  let template = HtmlService.createTemplateFromFile('htmlEmail');
  template.data = data;
  template.alertDetails = HtmlService.createHtmlOutput(data[0]['Alert Details']).getContent()
  let message = template.evaluate().getContent();

  //Takes the data variable and pulls out the the 'Alert Subject' and 'Alert Details', and appends them to an email that is sent out when the form is submitted
  MailApp.sendEmail({
    to: 'YOUR EMAIL',
    subject: `${data[0]['Alert Subject']}`,
    htmlBody: message,
    replyTo: `${data[0]['User Email']}`
  })
}

Thank you for any assistance

getImageData will not work with loaded images

I am trying to load an image to a webpage and read a pixel value. Every reference describes the same use of getImageData, but while it works nicely with pixels I write directly to the canvas (using fillRect), it cannot read anything after adding an image to the canvas. It simply crashes.

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var imageObj1 = new Image();
imageObj1.src = "world_.png";
imageObj1.onload = function() {
 ctx.drawImage(imageObj1, 0, 0, 500, 250);
 setTimeout(function() {
  alert("1");
  alert(ctx.getImageData(0,0,1,1).data);
  alert("2");
 }, 100); // Adjust the delay time as needed
};

I added the setTimeout to take into account asynchronous loading times, but I have tried with and without that, and every other permutation or trick I can think of. Nothing works. The alerts simply stop after 1. I have tried with .png and .bmp versions of the image. All files are in the same directory on my laptop. It is run on Firefox 107.0. getImageData crashes it all, every time. And I have no idea why.

How can I retreive images from the shopify buy sdk (with a custom query)?

I am simply trying to fetch products by tag with the shopify buy sdk. Unfortunately this is not supported by the SDK by default, so I am forced to “build your own query”.

I am able to fetch the products properly, with a few static fields, but fields that are arrays of other data types are not cooperating.

Here was my initial attempt:

        product.add('images', (image) => {
            image.add('src');
        });

I have tried many many variations, but they always end in an error, such as

  • there is no field of name “src” found on type “ImageConnection” in schema
  • there is no field of name “pageInfo” found on type “ImageEdge” in schema
  • there is no field of name “pageInfo” found on type “Image” in schema
  • connections must include the selections “pageInfo { hasNextPage, hasPreviousPage }”.
  • Parse error on “}” (RCURLY) at [1, 217] { line: 1, column: 217 }

here is my full code:

async function getProductsByTag (tag) {
    const productsQuery = client.graphQLClient.query((root) => {
        root.addConnection('products', { args: { first: 250, query: 'tag:'+tag } }, (product) => {
            product.add('title');
            product.add('handle');
            product.add('productType');
            product.add('images', (image) => {
                image.add('src');
            });
        });
    });
    let result = await client.graphQLClient.send(productsQuery);
    return result.data.products.edges.map(p => p.node);
}

This version seems more right, but still returns the No field of name "pageInfo" found on type "ImageEdge" in schema error.

        product.add('images', { args: { first: 250 } }, (imageConnection) => {
            imageConnection.addConnection('edges', { args: { first: 250 } }, (image) => {
                image.add('node', (node) => {
                    node.add('src');
                });
            });
        });

My site work on api from binance i want to change it to other

when I connect binance api, I can make a virtual deposit on a demo account and trade it, everything works, I want to do the same but using other api that will be easier to set up, for example, from kucoin

Found kucoin-php-sdk-master on github but still hard for me to connect it to composer and test on my website. Language is php and js
Thank you in advance
I am also looking for an enthusiast who will like my startup and we can cooperate

Split array object to nested array for each separator

I am trying to split the below array

{
    "Base/Brand/0101-color-brand-primary-red": "#fe414d",
    "Base/Brand/0106-color-brand-secondary-green": "#00e6c3",
    "Base/Brand/0102-color-brand-primary-light-gray": "#eaecf0",
    "Base/Brand/0107-color-brand-secondary-black": "#000000",
    "Base/Brand/0103-color-brand-primary-white": "#ffffff",
    "Base/Brand/0108-color-brand-secondary-dark-gray": "#b4b4b4",
    "Base/Brand/0104-color-brand-secondary-blue": "#079fff",
    "Base/Light/Extended/Red/0201-color-extended-900-red": "#7f1d1d",
    "Base/Brand/0105-color-brand-secondary-yellow": "#ffe63b",
    "Base/Light/Extended/Red/0202-color-extended-800-red": "#991b1b"
}

to something like this

{
  "Base": {
    "Brand": {
      "0101-color-brand-primary-red": "#fe414d",
      "0106-color-brand-secondary-green": "#00e6c3",
      "Light": {
        "Extended": {
          "Red": {
            "0201-color-extended-900-red": "#7f1d1d",
            "0202-color-extended-800-red": "#991b1b"
          }
        }
      }
    }
  }
}

Basically I need to split array by ‘/’ and create nested array
Please help how can I achieve this.

CSS animation on load

Hi there I want to copy this animation into my portfolio but i found it a Little bit problematic, can you help me with this?
Video

When I tried I just achieved a color flowing through the boxes which disappeared in gaps between the boxes which obviously is ruining whole concept