Score “undefined” javascript

In this Odin course there is a task to make a “Rock, paper, scissors” game. When trying to add a scorecounter, the score comes back as “undefined”, even though the score for both the player and computer is tracked correctly through the program. Any suggestions on how to fix this?

Code:

let Choices = ["Rock", "Paper", "Scissors"];
let playerScore = 0;
let computerScore = 0;


function getComputerChoice() {
    let random = Math.floor(Math.random() * Choices.length);

    return Choices[random];
}

function playRound(playerSelection, computerSelection) {
    if (playerSelection === computerSelection) {
        return "Draw!";
    }
    else if (playerSelection.toLowerCase() === "rock" && computerSelection === "Paper") {
        computerScore++;
        return ("Computer Wins!");
    }
    else if (playerSelection.toLowerCase() === "rock" && computerSelection === "Scissors") {
        playerScore++;
        return ("You Win!");
    }
    else if (playerSelection.toLowerCase() === "paper" && computerSelection === "Rock") {
        playerScore++;
        return ("You Win!");
    }
    else if (playerSelection.toLowerCase() === "paper" && computerSelection === "Scissors") {
        computerScore++;
        return ("Computer Wins!");
    }
    else if (playerSelection.toLowerCase() === "scissors" && computerSelection === "Rock") {
        computerScore++;
        return ("Computer Wins!");
    }
    else {
        return ("You Win!");
    }
}

function playGame(playerScore, computerScore) {
    for (let i = 0; i < 5; i++){
        let computerSelection = getComputerChoice();
        let playerSelection = "Rock";
        console.log(playRound(playerSelection, computerSelection));
        console.log(`Player: ${playerScore}nComputer: ${computerScore}`);
    }
}

console.log(playGame());

I’ve checked if the “playerScore” and “computerScore” is tracked correctly, by using “console.log()” prior to the “return statements” in the “if statement”. However when trying to output the code correctly in the “for loop” it just says “undefined”.

Browser console

opening the window depending on the variable

<html>
  <body>
    <button onclick="previous()">previous</button>
    <button onclick="next()">next</button>
    <img src="https://th.bing.com/th/id/OIP.-d3JKGX5ZJ3Y3U7ybY8h8gHaE7?rs=1&pid=ImgDetMain" onclick="reDirect()"></img>

<script>
maxnum=4
num=0
function previous(){
  if(num>0) {
    num++
  }
  else{}
}

function next(){
  if(num<maxnum){
    num++
  }
  else{}
}

function reDirect(){
  if(num=0) {
    window.open("https://youtube.com");
  }
  else{}
  }
</script>

  </body>
</html>

I wanted a function that checks the variable and redirects to another page according to the variable.

this was needed because the whole script i wanted to make had the image also change according to the variable, and if the page for the image was not made the function would be useless so i also wanted it to be selective.

I have a script to zoom/full screen an image. But it has a big problem

Thanks for taking the time to read me, and maybe help me on a small problem i’m encountering.

So, long story short, i’m a french astronomer, and i’m trying to build a small website for family/friends/myself to store and display my different night sky pictures.

Funny.

But.
Right now, i have a javascript who handle zooming, de-zooming, reset and displaying a single image in full screen. But. The way it works from what i get ( i’m not really good with js, and since to my knowledge php / css won’t do the deal, i’m stuck with it ), it have a flaw: if i place two same image container ( which i’ll be forced to do on the same page ), it doesn’t “know” which image to zoom in. Basically, here’s my html:

<div class="image-group">
    <div class="image-container">
        <img class="image" src="/Uploads/Images/IMG_7342_pipp_top_100r__651_regedited-2.jpg" alt="">
    </div>
    <div class="fullscreenImageContainer" onclick="closeFullscreen()">
        <span class="closeButton">X</span>
        <img class="fullscreenImage" src="/Uploads/Images/IMG_7342_pipp_top_100r__651_regedited-2.jpg" alt="">
    </div>
    <div class="zoombuttons">
        <button onclick="zoomIn(this)">Zoom +</button>
        <button onclick="zoomOut(this)">Zoom -</button>
        <button onclick="resetZoom(this)">Réinitialiser</button>
        <button onclick="openFullscreen(this)">Plein écran</button>
    </div>
</div>

And my JS:

<sc   <script>
const image = document.getElementById('image');
    const container = document.getElementById('image-container');
let scale = 1;
let isDragging = false;
let startX, startY;
let posX = 0, posY = 0;

function zoomIn() {
    scale *= 1.1;
    updateImageTransform();
}

function zoomOut() {
    const initialScale = 1; // échelle initiale de l'image
    if (scale > initialScale) {
        scale = Math.max(initialScale, scale / 1.1); // Empêche le zoom d'aller en dessous de l'échelle initiale
        constrainPosition();
        updateImageTransform();
    }
}

function resetZoom() {
    scale = 1;
    posX = posY = 0;
    updateImageTransform();
}

function updateImageTransform() {
    image.style.transform = `translate(${posX}px, ${posY}px) scale(${scale})`;
}

function constrainPosition() {
    const imageRect = image.getBoundingClientRect();
    const containerRect = image.parentElement.getBoundingClientRect();

    const maxPosX = (imageRect.width - containerRect.width) / 2;
    const maxPosY = (imageRect.height - containerRect.height) / 2;

    posX = Math.min(Math.max(posX, -maxPosX), maxPosX);
    posY = Math.min(Math.max(posY, -maxPosY), maxPosY);
}

image.addEventListener('mousedown', (e) => {
    e.preventDefault();
    isDragging = true;
    startX = e.clientX;
    startY = e.clientY;
});

window.addEventListener('mousemove', (e) => {
    if (!isDragging) return;
    const dx = e.clientX - startX;
    const dy = e.clientY - startY;
    startX = e.clientX;
    startY = e.clientY;
    posX += dx;
    posY += dy;
    constrainPosition();
    updateImageTransform();
});

window.addEventListener('mouseup', () => {
    isDragging = false;
});

image.addEventListener('touchstart', (e) => {
    if (e.touches.length === 1) {
        startX = e.touches[0].clientX;
        startY = e.touches[0].clientY;
    }
    if (e.touches.length === 2) {
        const touch1 = e.touches[0];
        const touch2 = e.touches[1];
        initialDistance = Math.hypot(touch2.clientX - touch1.clientX, touch2.clientY - touch1.clientY);
        initialScale = scale;
    }
});

image.addEventListener('touchmove', (e) => {
    e.preventDefault();
    if (e.touches.length === 1) {
        const dx = e.touches[0].clientX - startX;
        const dy = e.touches[0].clientY - startY;
        startX = e.touches[0].clientX;
        startY = e.touches[0].clientY;
        posX += dx;
        posY += dy;
        constrainPosition();
        updateImageTransform();
    }
    if (e.touches.length === 2) {
        const touch1 = e.touches[0];
        const touch2 = e.touches[1];
        const currentDistance = Math.hypot(touch2.clientX - touch1.clientX, touch2.clientY - touch1.clientY);
        const delta = currentDistance - initialDistance;
        scale = Math.max(1, initialScale + delta * 0.01); // Ajustez le facteur de zoom
        constrainPosition();
        updateImageTransform();
    }
});

image.addEventListener('touchend', (e) => {
    // Rien à faire lors de la fin du toucher
});</script>
<script>


window.addEventListener('load', function() {
    function adjustContainerSize() {
        const imageRect = image.getBoundingClientRect();
        const containerHeight = image.parentElement.clientHeight;
        const imageHeight = imageRect.height;
        const imageWidth = imageRect.width;

        const containerWidth = (imageWidth / imageHeight) * containerHeight;
        image.parentElement.style.width = containerWidth + 'px';
    }

    adjustContainerSize();

    window.addEventListener('resize', adjustContainerSize);
});   </script>
 <script>
     // Fonction pour ouvrir l'image en plein écran
    function openFullscreen() {
        const fullscreenImageContainer = document.getElementById('fullscreenImageContainer');
        fullscreenImageContainer.style.display = 'flex';
    }

    // Fonction pour fermer l'image en plein écran
    function closeFullscreen() {
        const fullscreenImageContainer = document.getElementById('fullscreenImageContainer');
        fullscreenImageContainer.style.display = 'none';
    }

    // Gestion de l'événement ESC pour fermer l'image en plein écran
    document.addEventListener('keydown', function(event) {
        if (event.key === 'Escape') {
            closeFullscreen();
        }
    });
ript>
 <script>
     // Fonction pour ouvrir l'image en plein écran
    function openFullscreen() {
        const fullscreenImageContainer = document.getElementById('fullscreenImageContainer');
        fullscreenImageContainer.style.display = 'flex';
    }

    // Fonction pour fermer l'image en plein écran
    function closeFullscreen() {
        const fullscreenImageContainer = document.getElementById('fullscreenImageContainer');
        fullscreenImageContainer.style.display = 'none';
    }

    // Gestion de l'événement ESC pour fermer l'image en plein écran
    document.addEventListener('keydown', function(event) {
        if (event.key === 'Escape') {
            closeFullscreen();
        }
    });
 </script>   


What i would like it to do is to be linked to the the action is happening in. If i have two of them, the actions are hapenning in the one where the button is clicked, not the other same underneath.
( for demo purpose, you can see how it is integrated here: http://astrostuff.franceserv.com/Ref/Public/Post.php?ID=9D466F87-FC78-31C7-5C05-5AD6A55F6897 ).

The ideal situation would be to have multiple image-group, like this:

<div class="image-group">
    <div class="image-container">
        <img class="image" src="/Uploads/Images/IMG_7342_pipp_top_100r__651_regedited-2.jpg" alt="">
    </div>
    <div class="fullscreenImageContainer" onclick="closeFullscreen()">
        <span class="closeButton">X</span>
        <img class="fullscreenImage" src="/Uploads/Images/IMG_7342_pipp_top_100r__651_regedited-2.jpg" alt="">
    </div>
    <div class="zoombuttons">
        <button onclick="zoomIn(this)">Zoom +</button>
        <button onclick="zoomOut(this)">Zoom -</button>
        <button onclick="resetZoom(this)">Réinitialiser</button>
        <button onclick="openFullscreen(this)">Plein écran</button>
    </div>
</div>

And another one

And another one

without interaction conflict.

But to be honest, this is not my code, i only have a few basics for simple things in js, and i have no clue of how to get it to work ( long story short, i tried a few approaches who were pretty much a disaster. So if anyone have any idea, i would really appreciate some help on this 🙂 !
Thanks and have a nice day !

I deleted the approaches i tried, so sadly i don’t have any examples. But basically, i tried an approach similar to this:

        <button onclick="zoomIn(this)">Zoom +</button>

<script>
    function zoomIn(button) {
        const imageGroup = button.closest('.image-group');
        const image = imageGroup.querySelector('.image');
        let scale = parseFloat(image.dataset.scale) || 1;
        scale *= 1.1;
        image.dataset.scale = scale;
        updateImageTransform(image);
    }
</script>
and it didn't work very well. ( it prevented the top image to interact with the bottom one, but the top image still react to the button of the bottom one. )

How are event handlers dealt with by JavaScript? [closed]

Say we have a button to which we attach a click event listener with addEventListener() (I don’t know if any other method to add event handlers is handled a different way). Obviously, everytime we click the button, the callback passed into addEventListener will execute.

But how exactly does this work? If I recall correctly, the callback is added to the callback queue, not directly on the callstack and only when the callstack is empty, the event loop will push it onto the callstack.

But, how does JavaScript know to add that callback on the callback queue everytime we click a button? Or actually, is JavaScript actually handling this? addEventListener is a Web API if I’m not wrong, so it must be handled somewhere in the background and all JavaScript do is just reach the event listener registration, it passes it to thr Web API then it never cares about it again?

Why does the Google OAuth 2 authentication page not offer even though I do not have a valid token

I’m trying to make a third-party Google connection to an Angular application via “angular-oauth2-oidc” But when I have a null or invalid token it’s supposed to send me to the Google authentication page. But nothing happens

import { Injectable } from '@angular/core';
import { AuthConfig, OAuthService, OAuthEvent, OAuthSuccessEvent } from 'angular-oauth2-oidc';
import { UserService } from './user.service';
import { Router } from '@angular/router';
import { from, of, Observable } from 'rxjs';
import { switchMap, tap } from 'rxjs/operators';

const oAuthConfig: AuthConfig = {
  issuer: 'https://accounts.google.com',
  strictDiscoveryDocumentValidation: false,
  redirectUri: window.location.origin,
  clientId: 'MY KEY',
  scope: 'openid profile email',
  
}

@Injectable({
  providedIn: 'root'
})

export class GoogleApiService {

    constructor(private oauthService: OAuthService, private userService: UserService, private router: Router) {
      oauthService.configure(oAuthConfig);
    }

    logout() {
      this.oauthService.logOut();
    }

    login() {
      this.oauthService.loadDiscoveryDocument().then(() => {
        this.oauthService.tryLoginImplicitFlow().then(() => {
          if(!this.oauthService.hasValidAccessToken()) {
            
            
          }else{
            this.oauthService.loadUserProfile().then((userProfile) => {
              console.log('User profile', userProfile);
              this.userService.setUserProfile(userProfile); // Store user profile in UserService
            });
            this.router.navigate(['/admin/users']);
            
          }
          /*this.oauthService.loadUserProfile().then((userProfile) => {
            console.log('User profile', userProfile);
            this.userService.setUserProfile(userProfile); // Store user profile in UserService
          });
          this.logout();*/

        });
      });
    }
}
loginWithGoogle() {
    this.google.login();
  }

I try by all means to ensure that if I have a valid token then I can retrieve the information from the email to be able to send it to the back. But if the token is not valid then I ask the user to authenticate through Google

Frida keys extract

I have a file named lib.so that contains functions from which I want to extract keys. These keys could be SHA or MD5 hashes. How can I do this using “Frida“, knowing that the lib.so file is located in an Android application?

I try to use attach but I don’t know how

Why am I not getting the audio file form the front end react to python server

This is the React code:

import React ,{ ChangeEvent, useState } from "react"

const FileUpload: React.FC = () => {
    const [selectedFile, setFile] = useState<File| null>(null);
    

    const HandleAudioChange = (event:ChangeEvent<HTMLInputElement>) => {
        const file: File | null = event.target.files?.[0] || null;
        setFile(file)
        // console.log("Selected file", file)
    }

    const UploadAudio = () => {
        if(selectedFile){
            const formData : FormData = new FormData();
            formData.append('file',selectedFile)

            fetch('http://127.0.0.1:5000/upload', {
            method:'POST',
            body:formData,
        }).then(res => res.json())
        .then(data => {
            console.log("Server response", data)
        })
        .catch(error => {
            console.error("This is the error ", error);
        })
        .finally(() => {
            console.log("File has been uploaded")
        })
        }

        
    }
    

  return (
    <div className="flex justify-center mx-auto">
    <input className="rounded-full bg-white bg-opacity-70 text-xs text-blue-600 uppercase font-SF sm:px-3 font-semibold hover:shadow-md  sm:py-3 mx-auto" type="file" accept="audio/*" onChange={HandleAudioChange} />
    <button  onClick={UploadAudio}>
        
    </button>
    </div>
  )
}

export default FileUpload

and this is the python server code:

from flask import Flask, request, jsonify
from flask_cors import CORS


app = Flask(__name__)
CORS(app)


@app.route("/upload", methods=["GET", "POST"])
def upload_audio():
    try:

        audio_file = request.files["file"]
        # Process the audio file as needed
        # For example, save it to disk or perform analysis
        return jsonify({"status": "success", "message": "Audio received successfully"})
    except KeyError:
        return jsonify(
            {
                "status": "error",
                "message": "No audio file received",
            }
        )


if __name__ == "__main__":
    app.run(debug=True)

If you can help me, I would really appreciate it!
The audio file is uploading and it’s showing in the console

I tried to get the audio file from the server but I am not getting the files

This is the Python response:
enter image description here

I want All Excel Files(*xls ; *.xlsx ;*.xlt; *.xlsm ; *.xltm; *.xltx) as a drop down but All type and custom type is showing in drop down of File exp [closed]

When I click add button file explorer open file window is opening but i want All Excel Files(xls ; .xlsx ;.xlt; .xlsm ; .xltm; .xltx) as a drop down but All type and custom type is showing in drop down. How to get only All Excel Files(xls ; .xlsx ;.xlt; .xlsm ; .xltm; .xltx) as a drop down .enter image description here

I want only All Excel Files(xls ; .xlsx ;.xlt; .xlsm ; .xltm; .xltx) as a drop down to show in drop down of file explorer open file window dialog when click add button.enter image description here

Problem updating the height of my timeline in a dynamic react component

I have a Timeline component that I’ve implemented twice on my page. In this component I have a “timeline” div whose height increases with scroll to reach the bottom of its container. It works fine when I scroll in the 1st component, but when I get to the second the height of the “timeline” div is already at 100%.

Here’s my code:

const DesktopProcess = ({ datas }) => {
  const phase1 = datas?.phases[0];
  const phase2 = datas?.phases[1];
  return (
    <>
      <div className="dekstop-view-regul-white">{parse(datas?.teaser)}</div>;
      <div className="dekstop-view-regul-no-bg">
        <Title
          textColor={"black"}
          dateBg={"#0aa2a5"}
          title={phase1?.title}
          durea={phase1?.durea}
          dateTextColor={"white"}
          addMargin={""}
        />
        <TimeLine
          lengthLine={phase1?.datas?.length}
          datas={phase1?.datas}
          bgBubble={""}
        />
      </div>
      <div className="dekstop-view-regul-green">
        <Title
          textColor={"#14b5bf"}
          dateBg={"black"}
          title={phase2?.title}
          durea={phase2?.durea}
          dateTextColor={"white"}
          addMargin={"add-margin-b-title"}
        />
        <TimeLine
          lengthLine={phase2?.datas?.length}
          datas={phase2?.datas}
          bgBubble={"bubble-green"}
        />
      </div>
    </>
  );
};

const TimeLine = ({ lengthLine, datas, bgBubble }) => {
  const [scrollPosition, setScrollPosition] = useState(0);
  const [endReached, setEndReached] = useState(false);
  const timelineRef = useRef(null);

  const handleScroll = () => {
    if (timelineRef.current && !endReached) {
      // Continuez à ajuster seulement si la fin n'est pas encore atteinte
      const position = window.pageYOffset - timelineRef.current.offsetTop;
      setScrollPosition(position + 50);
      console.log("height:", scrollPosition);
      console.log("ref:", timelineRef.current);
    }
  };

  useEffect(() => {
    window.addEventListener("scroll", handleScroll, { passive: true });
    return () => {
      window.removeEventListener("scroll", handleScroll);
    };
  }, [timelineRef]);

  useEffect(() => {
    if (endReached) {
      setScrollPosition(0);
    }
  }, [endReached]);

  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        const entry = entries[0];
        if (entry.isIntersecting) {
          setEndReached(true); // L'élément de fin est visible, fixez la hauteur de la timeline
        }
      },
      {
        root: null, // surveille l'intersection par rapport au viewport
        threshold: 0.1, // déclenche lorsque 10% de l'élément observé est visible
      }
    );

    const endElement = document.querySelector(".end");
    if (endElement) {
      observer.observe(endElement);
    }

    return () => {
      if (endElement) {
        observer.unobserve(endElement); // Nettoyage
      }
    };
  }, []);

  const bubbles = Array.from({ length: lengthLine }, (_, index) => (
    <Bubble key={index} index={index} bgBubble={bgBubble} />
  ));

  return (
    <div className="time-line-container" ref={timelineRef}>
      <span className="start"></span>
      {bubbles}
      <div
        className="timeline"
        style={{ height: endReached ? "100%" : `${scrollPosition}px` }}
      ></div>
      <div className="container-steps-time-line">
        {datas &&
          datas?.map((i, index) => {
            return <Steps datas={i} key={index} index={index} />;
          })}
      </div>
      <span className="end"></span>
    </div>
  );
};

Thank you for your help

Random number generator not functioning properly in javaScript

this:

`const minInput = document.getElementById("input-min");
const maxInput = document.getElementById("input-max");
const result = document.getElementById("result");
const gen = document.getElementById("generate");

gen.onclick = function(){
    const min = parseInt(minInput.value);
    const max = parseInt(maxInput.value);
    if (isNaN(min) || isNaN(max)) {
        result.textContent = "Please enter valid numbers for min and max.";
    } else {
        let display = Math.floor(Math.random() * (max - min + 1)) + min;
        result.textContent = display;
    }
}`

works.

but, this:

`const min = document.getElementById("input-min");
const max = document.getElementById("input-max");
const result = document.getElementById("result");
const gen = document.getElementById("generate");

gen.onclick = function(){
    const min = parseInt(min.value);
    const max = parseInt(max.value);
    if (isNAN(min) || isNAN(max)) {
        result.textContent = "please enter valid numbers";
    } else {
        let display = Math.floor(Math.random() * (max - min)) + min;
        result.textContent = display;
    }`

doesn’t work an I would like to know why, thanks.

this first generator works properly, but the second doesn’t function at all, the first one is from chat gpt and the second one I wrote

Read json to extract complete item when searched with a particular strin

I am writing a jenkins pipeline where i want to read a json file which contains below data, i want to search with Env and it should return complete section wherever SIT env is present

example:
{
“Project”:”1111″,
“url”:”foo”,
“Env”:”SIT”
},
{
“Project”:”2222″,
“url”:”dccc”,
“Env”:”SIT”
},
{
“Project”:”3333″,
“url”:”foo”,
“Env”:”OAT”
},
{
“Project”:”4444″,
“url”:”gggg”,
“Env”:”OAT”
}

It should return project, url and env details of only those where sit is mentioned.

Error while creating react app in visual code

npm WARN config global --global, --local are deprecated. Use --location=global instead.
Creating a new React app in C:UsersmidhuOneDriveDocumentsprojectonepro1app.
npm WARN config global --global, --local are deprecated. Use --location=global instead.
Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts with cra-template…
npm WARN config global --global, --local are deprecated. Use --location=global instead.
changed 1491 packages in 37s
253 packages are looking for funding
run npm fund for details
Missing dependencies in package.json

this error keeps rising, i’ve tried reinstalling node and possible other ways also

help me to resolve this issue

Consumer isAuthenticated doesn’t get updated when set bya function in AuthContext

I’m trying to get my navigation bar to update the signout button when the user is authenticated. I’m using React Context to keep track of the isAuthenticated value. I wrapped my AuthProvider in layout.tsx and page.tsx (root file). I have other components. Could this be an asynchronous or scope issue? I tried using useEffect to keep track of global changes.

// AuthContext.tsx
...

export const AuthProvider: React.FC<AuthProviderProps> = ({ children }: AuthProviderProps) => {
    const [isAuthenticated, setIsAuthenticated] = useState(false)

    useEffect(() => {
        console.log(isAuthenticated)
    }, [isAuthenticated])

    const login = async () => {
        setIsAuthenticated(true);
        console.log("Logged in user")
    }

    const logout = async () => {
        setIsAuthenticated(false)
        console.log("Logged out user")
    }

    return (
        <AuthContext.Provider value={{ isAuthenticated, login, logout }}>
            {children}
        </AuthContext.Provider>
    );
};
// Navigation.tsx
...

export default function Navigation() {
    const { isAuthenticated, login } = useAuth();
    useEffect(() => {
        console.log(isAuthenticated)
    }, [isAuthenticated, login])

    return (
        <nav className='bg-white border-b border-gray-200 py-4 shadow-sm'>
            <ul className='flex justify-center space-x-10'>
                {navCategories.map((category) => (
                    <li key={category.label} className='text-gray-600 hover:text-blue-600'>
                        <Link href={category.href}>
                            <span className='text-md font-semibold tracking-wide transition-colors duration-300'>
                                {category.label}
                            </span>
                        </Link>
                    </li>
                ))}
            </ul>
            {isAuthenticated &&
                <Signout />
            }
        </nav>
    )
}
// layout.tsx
...

export default function RootLayout({
    children,
}: Readonly<{
    children: React.ReactNode;
}>) {
    return (
        <html lang="en">
            <body className={inter.className}>
                <AuthProvider>
                    <Navigation />
                </AuthProvider>
                {children}
            </body>
        </html>
    );
}