How do I convert a number to a string?

I’m trying to create the rock, paper, scissors task from The Odin Project. When I run the code, the computerPlay function name shows a random number from 0-2 because of the Math.random function. How do I turn 0-2 into the choices [‘rock’, ‘paper’, ‘scissors’]?

let playerScore = 0;
let computerScore = 0;

const choices = ['rock', 'paper', 'scissors'];

function computerPlay() {
    let computerResult = [Math.floor(Math.random() * choices.length)];
    return computerResult;}

console.log(`Player Score: ${playerScore}`);
console.log(`Computer Score: ${computerScore}`);
console.log(computerPlay());

How to get the clicked button id to be used repeatedly later in different functions?

I want to store what is being clicked on, so that it can be used for multiple times in a game of rock-paper-scissors. I need to use this until player or computer scores 5. Any suggestions will be appreciated!

HTML file:

<div class = buttons>
       <button id="rock">Rock</button>
       <button id="paper">Paper</button>
       <button id="scissors">Scissors</button>
   </div>

JavaScript file:

I am able to log the button.id however it’s not useful as I’m unable to use it in any other functions.

const buttons = document.querySelectorAll('button');
buttons.forEach(button => button.addEventListener('click', () => {
console.log(button.id)}); //get the button.id

Trying to understand the unique key in React.js [duplicate]

I’m trying to make a component where will be a name list. But it shows me the error like this ‘Each child in a list should have a unique “key” prop.’ I tried everywhere put unique key where is possible but it’s still showing error

This is the key:

 key={item._id}'

where should I put the key?

 const listAdded = () => {
const [items]=useItems();
                                                                                    
 return (

          <div>
                {
                    items.map(item=>
                     <>
                    <div>
                    <img className='ms-5'  src={item.image} alt="" />
                    <h3>{item.name}</h3>
                    </div>
                    </>)
                }
          </div>
      );
   };


            
            
      

Copy elements from one object to another and show it as json

I have an object and I want to add new elements inside it and remove some elements

console.log("bookmark", bookmark)
[
   {
       "__type": "BookmarksApp.Bookmark",
       "BookmarkID": 1,
       "name": "San Diego, CA",
       "xmin": "-13048800",
       "ymin": "3844800",
       "xmax": "-13037800",
       "ymax": "3870400",
       "UserID": 6
   },
   {
       "__type": "BookmarksApp.Bookmark",
       "BookmarkID": 2,
       "name": "Redlands, California",
       "xmin": "-13052100",
       "ymin": "4024900",
       "xmax": "-13041100",
       "ymax": "4050500",
       "UserID": 6
   }
]

I trayed many ways but it doesn’t work with me one of them like this:-

 bookmarkjson = {

                extent: {
                    xmin: JSON.stringify(bookmark.map(a => a.xmin)),
                    ymin: JSON.stringify(bookmark.map(a => a.ymin)),
                    xmax: JSON.stringify(bookmark.map(a => a.xmax)),
                    ymax: JSON.stringify(bookmark.map(a => a.ymax)),
                "spatialreference": {
                "wkid": 102100,
                "latestwkid": 3857
               },
             },
         name:bookmark.map(a => a.name),

 };

the result come like this all objects in one object how can I edit it :-

{
    "xmin": "["-13048800","-13052100"]",
    "ymin": "["3844800","4024900"]",
    "xmax": "["-13037800","-13041100"]",
    "ymax": "["3870400","4050500"]",
    "spatialreference": {
        "wkid": 102100,
        "latestwkid": 3857
    }
}

how can I change it to be like this

 {
                    first: {
                        "extent": {
                            "xmin": -12975100,
                            "ymin": 3993900,
                            "xmax": -12964100,
                            "ymax": 4019500,
                            "spatialReference": {
                                "wkid": 102100,
                                "latestWkid": 3857
                            }
                        },
                        "name": "Palm Springs, CA"
                    },
                    second: {
                        "extent": {
                            "xmin": -13052100,
                            "ymin": 4024900,
                            "xmax": -13041100,
                            "ymax": 4050500,
                            "spatialReference": {
                                "wkid": 102100,
                                "latestWkid": 3857
                            }
                        },
                        "name": "Redlands, California"
                    },
                   
                }

the bookmark is dynamic can has more than 2 objects

Selenium JavaScript Try Catch block is not working as expected

I am trying to throw an error on the console if the first link of bing search results is clicked. My code is working fine until the first link is opened, but I am not seeing any message on the console that first link is successfully clicked and when I make an intentional code change to catch error, catch is not throwing error. I am using node.js, selenium and edge webdriver. Please help me fix this.

const { Builder, By } = require('selenium-webdriver');
async function launchEdgeBing() {
  let driver = await new Builder().forBrowser('MicrosoftEdge').build();

  await driver.get('https://bing.com');
  await driver.manage().window().maximize();

  const element = await driver.findElement(By.id('sb_form_q'));
  await driver.sleep(5000);
  await element.sendKeys('latest news');
  await element.submit();
  await driver.sleep(5000);
  try {
    const clickFirstResult = await driver.findElement(
      
      By.className('b_title')
    );
    clickFirstResult.click();
    await driver.sleep(5000);
   
    var title = await driver.getTitle();
    console.log('Title is:', title);
  } catch (e) {
    if (e == null) {
      console.log('First link opened successfully');
    } else {
      console.log('Error is:', e);
    }
  } finally {
    await driver.quit();
  }
}
launchEdgeBing();

Display Bar Chart on Flask API using Chart.js

I’m trying to display pie and bar chart using Flask API on html page using chart.js. I am able to display pie chart but bar chart is getting below error.
“cannot read property of undefined (reading ‘offsetWidth’)” under “/nutrition_analysis” route.

enter image description here

Please find below Python main.py code,

    
# importing the necessary dependencies
from flask import Flask, render_template, request,jsonify
from flask_cors import CORS, cross_origin
import pandas as pd

from flask import send_file
#import matplotlib.pyplot as plt
#%matplotlib inline
import logging


from datetime import datetime

app = Flask(__name__)  # initializing a flask app


@app.route('/', methods=['GET', 'POST'])  # route to display the home page
@cross_origin()
def homePage():
    return render_template("home.html")



@app.route('/form_fill',methods=['GET','POST'])  # route to display the home page
@cross_origin()

def form_fill():
    return render_template("form_fill.html")

@app.route('/download_file',methods=['GET','POST'])  # route to display the home page
@cross_origin()

def download_file():
    path = 'Daily Nutrition Requirement.xlsx'
    return send_file(path, as_attachment=True)


@app.route('/nutrition_analysis',methods=['POST','GET']) # route to show the predictions in a web UI
@cross_origin()
def nutrition_analysis():
    if request.method == 'POST':
        try:
            #  reading the inputs given by the user
            name = (request.form['name'])
            age = float(request.form['age'])
            weight = float(request.form['weight'])
            reference = (request.form['reference'])
            phone = float(request.form['phone'])
            emailid = (request.form['emailid'])

            file = request.form['customer_data']
            customer_data = pd.read_excel(file)

            RDA = pd.read_excel('Recommended_Nutrition.xlsx')

            df = pd.concat([RDA, customer_data], ignore_index=True)

            df_Carbs = df[df["Nutrients"] == "Carbohydrate"]
            df_Fat = df[df["Nutrients"] == "Fats"]
            df_Prot = df[df["Nutrients"] == "Proteins"]
            df_Fbr = df[df["Nutrients"] == "Fiber"]

            df_Macros = pd.concat([df_Carbs, df_Fat, df_Prot, df_Fbr])

            df_Macros_Exp = df_Macros[df_Macros["Category"] == "Exp"]
            # df_Macros_Obs = df_Macros[df_Macros["Category"] == "Obs"]


            # plt.pie(df_Macros_Exp["Value"], labels=df_Macros_Exp["Nutrients"], autopct='%1.1f%%')
            # plt.title("Expected Macros as per RDA", fontweight='bold')
            # plt.savefig('chart.png')

            values = df_Macros_Exp["Value"].tolist()
            labels = df_Macros_Exp["Nutrients"].tolist()
            colors = ["#F7464A", "#46BFBD", "#FDB45C", "#FEDCBA"]

            # Bar Chart

            df_stack = pd.merge(RDA,customer_data[['Nutrients','Value']],on='Nutrients', how='left')

            df_stack1=df_stack[['Nutrients','Value_x','Value_y']].copy()
            df_stack1["RDA"]=100
            df_stack1["Intake"]=((df_stack1["Value_y"] - df_stack1["Value_x"])/df_stack1["Value_x"])*100
            df_stack1.drop(["Value_x", "Value_y"], axis = 1, inplace = True)

            def color(x):
                if x < 0 or x > 50 :
                    return '#F7464A'
                else:
                    return '#46BFBD'

            df_stack1["Color"]=df_stack1["Intake"].apply(color)

            values_bar = df_stack1["Intake"].tolist()
            labels_bar = df_stack1["Nutrients"].tolist()
            colors_bar = df_stack1["Color"].tolist()


            #dt=datetime.now()
            
            # showing the prediction results in a UI
            return render_template('nutrition_analysis.html',s1=name,s2=age,s3=weight,s4=reference,s5=phone,s6=emailid,set=zip(values, labels, colors),set2=zip(values_bar,labels_bar,colors_bar))
        except Exception as e:
            print('The Exception message is: ',e)
            logging.debug(e)
            return 'something is wrong'
    # return render_template('results.html')
    else:
        return render_template('home.html')
        



if __name__ == "__main__":

    logging.basicConfig(filename='Nutrition_Analysis.log', level=logging.DEBUG)
    app.run(host='127.0.0.1', port=8001, debug=True)
    #app.run(debug=True) # running the app

Please find html page which need to be rendered below,

<head>
  <meta charset="utf-8" />
  <title>Macro Analysis</title>
  <script src='https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js'></script>
</head>

<body>
<div class="item active" style="display: flex; height: 100px;">
   <div style=" width: 30%;">
      <h1><p>Liv365 Nutrition Analysis Report  :</p></h1>

      <br>name : {{s1}}</br>
      <br>age : {{s2}}</br>
      <br>weight : {{s3}}</br>
      <br>reference : {{s4}}</br>
      <br>phone : {{s5}}</br>
      <br>emailid : {{s6}}</br>

       </div>


        <div style=" width: 30%;">



    <h1>Macro Analysis</h1>

    <canvas id="chart" width="400" height="200"></canvas>
    <script>
      var pieData = [
        {% for values, labels, colors in set %}
          {
            value: {{values}},
            label: "{{labels}}",
            color : "{{colors}}"
          },
        {% endfor %}
      ];


      // draw pie chart
      new Chart(document.getElementById("chart").getContext("2d")).Pie(pieData);

      </script>

    </div>
<div style=" width: 40%;">

    <h1>Micro Analysis</h1>

         <canvas id="bar" width="400" height="200"></canvas>
    <script>
      var barData = [
        {% for values_bar, labels_bar, colors_bar in set2 %}
          {
            value: {{values_bar}},
            label: "{{labels_bar}}",
            color : "{{colors_bar}}"
          },
        {% endfor %}
      ];

       new Chart(document.getElementById("bar"), {
          type: 'bar',
          data: {
            labels: barData["label"],
            datasets: [
              {
                label: "Population (millions)",
                backgroundColor: barData["color"],
                data: barData["value"]
              }
            ]
          },
          options: {
            legend: { display: false },
            title: {
              display: true,
              text: 'Total Confirmed Cases of COVID in May'
            }
          }
      });

    </script>

</div>


</div>

   



</body>

</html>

Please help me resolve this issue.

Thanks in advance!!!

Regards,
Rohan

Why python server not able to receive and send messages?

I have a chatbot in python and want to integrate it to my react website. I am getting the following error while sending data to python server at localhost:/5000 from localhost:/3000:

 Could not proxy request /js/jquery-1.11.0.min.js from localhost:3000 to http://localhost:5000/.

The code for my python and js file:

from flask import Flask
app=Flask(__name__)

@app.route("/members")
def members():
    return {"members":["Member1","Member2","Member3"]}

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

The message file:

import axios from 'axios'
import './Message.css';
import React, {useState,useEffect} from 'react';
const Message=()=>
{
    // state ={
    //     chat:[],
    //     msg:''
    // }
    const [chat,setChat]=useState(["hellos zdfgzsdfgsfdg","dfgsdfgsdfgsdfgsdfgs","sdfgsdfgsdfgsdfgsdfgsdfg"]);
    const [msg,setMsg]=useState("");
    const[data,setData]=useState([{}])

    useEffect(()=>{
        fetch("/members").then(
            res=>res.json()
        ).then(
            data=>{
                setData(data)
                console.log(data)
            }
        )
    },[])
    return(
            <div  >
                
            </div>
        )
    
}
export default Message;

How do i post to mongodb database ? I have tried this but it still thrwoing error

const data = { name, price, quantity, image, desc, sup_name, email }
    fetch('https://gentle-plateau-90897.herokuapp.com/fruits', {
        method: 'POST',
        headers: {
            'content-type': 'application/json'
        },
        body:(data)
    })
        .then(res => res.json())
        .then(data => {
            console.log(data)
            window.alert('Item added')
            e.target.reset()
        })

I am trying to post method to send data to my mongodb database, but it throwing an error saying ‘Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0’

IntersectionObserver – toggle a class when sticky element intersects with viewport + top property

I wanted to add a class when the header was sticky but with a condition that it should not be with respect to viewport. It should be viewport plus some top ( css ) value. My sticky component is having a top property to adjust from where it will sticky with respect to viewport.

I tried many things such as changing rootMargin but was unsuccessful, some help would be appreciated

const stickyElm = document.querySelector('.automations-dashboard > div > span:nth-child(3)');
const observer = new IntersectionObserver(
  ([e]) => e.target.classList.toggle('isSticky', e.intersectionRatio < 1),
  { rootMargin: '0px 0px 0px 0px' }
);
if (stickyElm) observer.observe(stickyElm);

Reference SO – Event to detect when position:sticky is triggered

How to set useState for change view on reactJs

Now I’m trying to learn React and how to build a single Page application without a redirect page. so every change UI will just trigger by the button. However, I’m struggling with how to implement it if the trigger button is on another view…

I build a simple code to change the route view from <Home/> to <Payment/> with a button.

app.js

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

import Home from './views/Home';
import Payment from './views/Payment'; 
import Header from './components/Header';
import Footer from './components/Footer';

function App(props) {  

    const [changePage, setPage] = useState(false);
  
    useEffect(() => {
      console.log(changePage);
      if (changePage) {
        setPage(true);
      }
    } );
  
    const handleClick = () => setPage(true);
   
  return ( 
      <div>
        <Header/>
          <button onClick={!changePage ? handleClick : null} >
            Goto Payment
          </button>

          {changePage ? <Payment/> : <Home/>}

        <Footer/>      
      </div>
 
  );
}

export default App;

The above code can work when clicking the button. However, I plan to move the trigger button from app.js to ./view/Home, so the code on ./view/home I set with this code

import React from 'react'; 

function Home(props) {
    return (
        <div>
            HOME

            <button onClick={!changePage ? handleClick : null} >
            Goto Payment
          </button>
        </div>
        
    );
}

export default Home; 

but it returns an error

Compiled with problems:X

ERROR


src/views/Home.js
  Line 8:31:  'changePage' is not defined   no-undef
  Line 8:44:  'handleClick' is not defined  no-undef

Search for the keywords to learn more about each error.

From my code, how do I able to set the trigger button on file ./view/Home but still change the page on app.js…

please help

using req.params vs req.query in Next.js dynamic api routes

I am trying to access params in my Next.js API routes. I am just wondering why in order to access a certain dynamic route id I must use req.query when normally in express I would access the id via params. Is req.query the correct way of accessing the id?

I have the following api folder structure.

/pages
  /api
    /posts
      -index.js
      -[postId].js

In my [postId] file I have the following

function handler(req, res) {
  // shows undefined
  console.log(req.params);
  const postId = req.params.postId;

and my api call is as follows:

fetch(`/api/posts/${id}`)