javascript code to select a fixed number of questions from json file

I have the code for a MCQ app that uses HTML, CSS, and JS. The code asks all the questions that are in the array object (which in this case is 8). However, I want the app to select only five random questions from the list of questions.

const quizData = [
    {
        question: "What is the most used programming language in 2019?",
        a: "Java",
        b: "C",
        c: "Python",
        d: "JavaScript",
        correct: "d",
    },
    {
        question: "Who is the President of US?",
        a: "Florin Pop",
        b: "Donald Trump",
        c: "Ivan Saldano",
        d: "Mihai Andrei",
        correct: "b",
    },
    {
        question: "What does HTML stand for?",
        a: "Hypertext Markup Language",
        b: "Cascading Style Sheet",
        c: "Jason Object Notation",
        d: "Helicopters Terminals Motorboats Lamborginis",
        correct: "a",
    },
    {
        question: "What year was JavaScript launched?",
        a: "1996",
        b: "1995",
        c: "1994",
        d: "none of the above",
        correct: "b",
    },
    {
        question: "Which is the largest animal in the world?",
        a: "Shark",
        b: "Blue Whale",
        c: "Elephant",
        d: "Giraffe",
        correct: "b",
    },
    {
        question: "Which is the smallest country in the world?",
        a: "Vatican City",
        b: "Bhutan",
        c: "Nepal",
        d: "Sri Lanka",
        correct: "a",
    },
    {
        question: "Which is the largest desert in the world?",
        a: "Kalahari",
        b: "Gobi",
        c: "Sahara",
        d: "Antarctica",
        correct: "d",
    },
    {
        question: "Which is the smallest continent in the world?",
        a: "Asia",
        b: "Australia",
        c: "Arctic",
        d: "Africa",
        correct: "b",
    },
];

const quiz = document.getElementById("quiz");
const answerEls = document.querySelectorAll(".answer");
const questionEl = document.getElementById("question");
const a_text = document.getElementById("a_text");
const b_text = document.getElementById("b_text");
const c_text = document.getElementById("c_text");
const d_text = document.getElementById("d_text");
const submitBtn = document.getElementById("submit");

let currentQuiz = 0;
let score = 0;

loadQuiz();

function loadQuiz() {
    deselectAnswers();

    const currentQuizData = quizData[currentQuiz];

    questionEl.innerText = currentQuizData.question;
    a_text.innerText = currentQuizData.a;
    b_text.innerText = currentQuizData.b;
    c_text.innerText = currentQuizData.c;
    d_text.innerText = currentQuizData.d;
}

function getSelected() {
    let answer = undefined;

    answerEls.forEach((answerEl) => {
        if (answerEl.checked) {
            answer = answerEl.id;
        }
    });

    return answer;
}

function deselectAnswers() {
    answerEls.forEach((answerEl) => {
        answerEl.checked = false;
    });
}

submitBtn.addEventListener("click", () => {
    // check to see the answer
    const answer = getSelected();

    if (answer) {
        if (answer === quizData[currentQuiz].correct) {
            score++;
        }

        currentQuiz++;
        if (currentQuiz < quizData.length) {
            loadQuiz();
        } else {
            quiz.innerHTML = `
                <h2>You answered correctly at ${score}/${quizData.length} questions.</h2>

                <button onclick="location.reload()">Reload</button>
            `;
        }
    }
});

I know that I can use the random function like this within some kind of loop:

Math.floor(Math.random() * quizData.length);

But I am not sure how to use this within the code.
The project is here: codepen

Login page can’t correctly direct to secret page

I am trying to build a simple sign up page and login page. Here is my code below

const express = require("express");
const app = express();
const mongoose = require("mongoose");
const cookieParser = require('cookie-parser')
const session = require('express-session')
const bodyParser = require("body-parser");
const ejs = require("ejs");
const User = require("./models/user")
const bcrypt = require("bcrypt")
const saltRounds = 10;
require('dotenv').config()


app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(cookieParser ("This is my secret"))
app.use(session({
  secret: process.env.SECRET,
  resave: false,
  saveUninitialized:false,

}))
app.use(bodyParser.urlencoded({extended:true}))



app.get("/", (req,res)=>{
  console.log(process.env.SECRET)
  res.send("welcome to homepage")
})  

app.get("/signup",(req, res)=>{
  res.render("signup")
})

app.post("/signup", (req,res, next)=>{
  let {username, password} = req.body
  bcrypt.genSalt(saltRounds, (err, salt)=>{
    if (err){
      next(err)
    }
    console.log(salt)
    bcrypt.hash(password, salt, (err, hash)=>{
      let newUser = new User({username, password})
      try{
        newUser.save().then(()=>{
          console.log(req.body)
          res.send("data has been saved")
        }).catch((e)=>{
          res.send("error")
          console.log(e)
        })
      }catch(e){
        next(e)
      }
    })
    })
  })
  
  

app.get("/login", (req,res)=>{
  res.render("login")
})


app.post("/login", async (req, res, next) => {
  let { username, password } = req.body;
  try {
    let foundUser = await User.findOne({ username });
    if (!foundUser) {
      res.send("User not found");
    } else {
      const isMatch = bcrypt.compare(password, foundUser.password);
      if (!isMatch) {
        res.send("Password incorrect");
      } else {
        // Password is correct, render the secret page
        res.render("secret");
      }
    }
  } catch (e) {
    next(e);
  }
});



app.get("/*", (req, res)=>{
  res.status(404).send("404 page not found")
})


//global error settintg
app.use((err, req, res, next)=>{
  console.log(err)
  res.status(500).send("Something wrong happened")
})

mongoose.connect('mongodb://127.0.0.1:27017/studentDB').then(()=>{
    console.log("U success")
}).catch(e =>{
    console.log("connection failed");
    console.log(e);
})
app.listen(3000, () => {
  console.log("Server running on port 3000.");
});

What I have found is that at the phase of

app.post("/login", async (req, res, next) => {
  let { username, password } = req.body;
  try {
    let foundUser = await User.findOne({ username });
    if (!foundUser) {
      res.send("User not found");
    } else {
      const isMatch = bcrypt.compare(password, foundUser.password);
      if (!isMatch) {
        res.send("Password incorrect");
      } else {
        // Password is correct, render the secret page
        res.render("secret");
      }
    }
  } catch (e) {
    next(e);
  }
});

whether the password is correct or not , it can still get to the secret page

Then I ask chatgpt, it told me to add await before bcrypt.compare looks like

app.post("/login", async (req, res, next) => {
  let { username, password } = req.body;
  try {
    let foundUser = await User.findOne({ username });
    if (!foundUser) {
      res.send("User not found");
    } else {
      const isMatch = await bcrypt.compare(password, foundUser.password);
      if (!isMatch) {
        res.send("Password incorrect");
      } else {
        // Password is correct, render the secret page
        res.render("secret");
      }
    }
  } catch (e) {
    next(e);
  }
});

The sign up page works well it returns “data has been saved” and console correct username and password. such as username:[email protected] password: 1234
Then I checked the console at login page
It returns exactly the same thing that at the sign up page
but it turns to return password incorrect whether the password is correct or not

Iterating a Landsat image collection to display as a layer in google earth engine

I am working with Landsat 8/9 in Google Earth Engine (GEE) and would like some help. I have a list of Landsat images and want to do dNBR calculations to each of them and later displaying each as a layer. I get this list using variable dates so I believe it would be best to have a function where I can iterate over the list, apply the calculation and then display the scene using a designated name. I pretty new to GEE so I wanted to ask for help. I would greatly appreciate some guidance. Thank you!

I wrote code that displays images using specific numbers for example:
var img1 = ee.Image(listofImages.get(0));
but this relies heavily on me editing the code to get each layer.

These image do not have the NBR calculation applied to it but I believe:

.normalizedDifference([‘B5’, ‘B7’])

should work within a function that can iterate throughout the list as well as subtracting the scene by the prefire scene to get the dNBR by using:

var dNBR= preNBR.subtract(postNBR)

CSV download for formated csv file from json in Salesforce LWC

I have a json with multiple nodes and formatted incoming json response from a service call. It is formatted in apex to display multiple tables as desired. From json structured to have different tables in csv. During download action encountering error as Error generating CSV Error: Lightning Web Security: Unsupported MIME type. I need to resolve this error to complete download action.

handlerDownloadCSV(csvContentFromJSON) {
try {
const csvData = btoa(unescape(encodeURIComponent(csvContentFromJSON)));
const blob = new Blob([csvData], { type: 'text/csv' });
if ('download' in document.createElement('a')) {
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'data.csv';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
} else {
const csvUrl = 'data:application/octet-stream;base64,' + csvData;
window.open(csvUrl, '_blank');
}
} catch (error) {
console.error('Error generating CSV', error);
}
}

Need to resolve Error generating CSV Error: Lightning Web Security: Unsupported MIME type.

How to make the toggle switch show/hide an array object?

I am trying to show/hide the description when I toggle the switch. I also want the switch to be checked at first. When The switch is checked, the description of each result should show. each result have their own description.

My code doesn’t do any of that. Instead, all of the descriptions are showing for each result. The toggle switch is not showing the descriptions but it is hiding them.

// imports

const results = [...]

const upvoteSVG = '...';

const downvoteSVG = '...';

export default function SearchResults() {
    const [page, setPage] = useState(0); 
    const [description, setDescription] = useState(Array.isArray(results) ? results.map(result => result.description) : []);

    const List = () => {
        return (
            <>
            {
                results.slice(page * 10, page * 10 + 10).map((result) => {
                    return (
                        <div className="bg-gray-800 shadow-lg shadow-red-500 m-5">
                            <div className="flex flex-row gap-4 p-5">
                                <div className="flex flex-col w-1/2">
                                    <div className="flex flex-row gap-4">
                                        <p className="text-lg font-bold">{result.name}</p>
                                        <p className="text-blue-500"><Link href={result.url}>Website</Link></p>
                                    </div>
                                    <p>{result.categories.slice(0, 3).join(", ")}</p>
                                </div>
                                <div className="flex flex-row flex-wrap w-1/2">
                                    <p>{description}</p>
                                </div>
                            </div>
                            <div className="flex flex-row bottom-0 gap-4 bg-gray-900 justify-items-end justify-end pr-2">
                                <p>{result.upvotes}<button className="rounded-full bg-red-500 w-fit h-fit p-2 m-2"><Image src="upvote.svg" alt="upvote" width={20} height={20}/></button></p>
                                <p>{result.downvotes} <button className="rounded-full bg-red-500 w-fit h-fit p-2 m-2"><Image src="downvote.svg" alt="downvote" width={20} height={20}/></button></p>
                            </div>
                        </div>
                    )
                })
            }
            </>
        )
    }

    const prevPage = () => {...}

    const nextPage = () => {...}

    const showDescription = () => {
        description ? setDescription([]) : setDescription(results.map(result => result.description));
    }

    const PaginationNumbers = () => {...}

    const NOP = () => {...}

    return (
        <div className="flex flex-col justify-center items-center">
            <div>
                <Search/>
            </div>
            <div className="flex flex-row justify-center items-center">
                <div className="w-1/2">
                    <List/>
                </div>
                <div className="w-1/2 m-2 p-2 flex flex-col justify-center items-center bg-gray-800">
                    <label className="inline-flex items-center cursor-pointer">
                        <input type="checkbox" value="" className="sr-only peer" id="toggle" onChange={showDescription}/>
                        <span className="ms-3 text-sm font-medium text-gray-900 dark:text-gray-300 m-2">Show Description</span>
                        <div className="relative w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-red-500 dark:peer-focus:ring-red-800 rounded-full peer dark:bg-gray-700 peer-checked:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all dark:border-gray-600 peer-checked:bg-red-600" ></div> 
                    </label>
                </div>
            </div>
            <div className="flex flex-row justify-center items-center flex-wrap w-1/2">
                <button onClick={prevPage} className="bg-gray-800 text-white m-2 p-2 hover:bg-white hover:text-black rounded-lg">Prev</button>
                <PaginationNumbers/>
                <button onClick={nextPage} className="bg-gray-800 text-white m-2 p-2 hover:bg-white hover:text-black rounded-lg">Next</button>
            </div>
        </div>
    )
}

Question about returns statements and function parameters

I’m new to software and there is this piece of code which is a solution to an array exercise but I don’t understand why it works. First of all the first thing it does is to return the string you enter in the function as a parameter, shouldn’t then the rest of the code be ignored and not executed? why does it execute?, I also don’t understand why the arrow function inside the map() method has two parameters called “word” and “index” respectively,how does the javascript engine know that the parameter “word” refers to one of the words that’s inside the array that’s being worked on by the function? (same for the word index, how does it know that the parameter refers to the index of the array?).

Here is the code:

function camelize(str) {
  return str
    .split('-') // splits 'my-long-word' into 
array ['my', 'long', 'word']
    .map(
      // capitalizes first letters of all array 
items except the first one
      // converts ['my', 'long', 'word'] into 
['my', 'Long', 'Word']
      (word, index) => index == 0 ? word : 
word[0].toUpperCase() + word.slice(1)
    )
    .join(''); // joins ['my', 'Long', 'Word'] 
into 'myLongWord'
}

The exercise in question: https://javascript.info/task/camelcase

I tried looking up on Google but get no relevant answers in the search results.

change value of dropdown based on two other dropdown menus

I’m trying to make it so that when the user chooses a specific station and direction from their respective dropdown menus, it shows different timeslots in the timeslot dropdown as well. the snippet for the dropdowns is here:

<div class="input-box" id="station-box">
                  <span class="details">Station</span>
                  <select name="station" id="station" required>
                    <option value="">Pinagbuhatan</option>
                    <option value="">Kalawaan</option>
                    <option value="">San Joaquin</option>
                    <option value="">Guadalupe</option>
                    <option value="">Hulo</option>
                    <option value="">Valenzuela</option>
                    <option value="">Lambingan</option>
                    <option value="">Sta-Ana</option>
                    <option value="">PUP</option>
                    <option value="">Quinta</option>
                    <option value="">Lawton</option>
                    <option value="">Escolta</option>
                </select>
                </div>
                <div class="input-box">
                    <span class="details">Direction</span>
                    <select name="direction" id="direction" required>
                        <option value="downstream">Downstream</option>
                        <option value="upstream">Upstream</option>
                    </select>
                  </div>
                  <div class="input-box">
                    <span class="details">Timeslot</span>
                    <select name="timeslot" id="timeslot" required>
                      <option value=""></option>
                  </select>
                  </div>
window.onload = function() {
    // Stations and their respective timeslots
    var stations = {
        'Pinagbuhatan': {
            'Upstream': ['A', 'B', 'C'],
            'Downstream': ['D', 'E', 'F']
        },
        'Kalawaan': {
            'Upstream': ['G', 'H', 'I'],
            'Downstream': ['J', 'K', 'L']
        }
    };
    
    // Get references to the station, direction, and timeslot dropdowns
    var stationSelect = document.getElementById('station');
    var directionSelect = document.getElementById('direction');
    var timeslotSelect = document.getElementById('timeslot');
  
    // Function to populate the timeslot dropdown based on the selected station and direction
    function populateTimeslots() {
        var selectedStation = stationSelect.value;
        var selectedDirection = directionSelect.value;
        
        // Clear out any existing options
        timeslotSelect.innerHTML = '';
        
        // If both station and direction are selected
        if (selectedStation && selectedDirection) {
            // Get the timeslots associated with the selected station and direction
            var timeslots = stations[selectedStation][selectedDirection];
            
            // Populate the timeslot dropdown with the timeslots
            timeslots.forEach(function(timeslot) {
                var option = document.createElement('option');
                option.value = timeslot;
                option.textContent = timeslot;
                timeslotSelect.appendChild(option);
            });
        }
    }
    
    // Attach change event listeners to the station and direction dropdowns
    stationSelect.addEventListener('change', populateTimeslots);
    directionSelect.addEventListener('change', populateTimeslots);
      
    // Populate the timeslot dropdown initially
    populateTimeslots();
};

I’ve been testing with the first two stations at first, but to no avail. I’m guessing it’s with how the stations are called since there’s a category for the station and sub-categories for whether upstream or downstream, but I’m stumped on how I would fix that.

React chrome extension, active tab detect element on scroll is not working

Active tab’s element on scroll is not working in react chrome extension.
Below is my code to detect active tab’s document’s element on scroll. But it’s not working as expected.

I want ‘Scrolled to end’ to be consoled on scroll happens(when scroll ends… even if a small scroll happens).

Active tab’s element on scroll is not working in react chrome extension.
Below is my code to detect active tab’s document’s element on scroll. But it’s not working as expected.
App.tsx

import React, { useEffect } from 'react';
import './App.css';
import { useRecoilState } from 'recoil';
import messagesState from './states/messages';
function App() {
  const [htmlContent, setHtmlContent] = useRecoilState<any>(messagesState);


  useEffect(() => {
    const handleMessage = (event: any) => {
      if (event.data && event.data.type === 'scrollEnd') {
        console.log('Scrolled to end');
      }
    };
    window.addEventListener('message', handleMessage);
    return () => {
      window.removeEventListener('message', handleMessage);
    };
  }, []);
  return (
    <div className="App">
     
    </div>
  );
}

export default App;

background.js

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.type === 'scrollEnd') {
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
      const activeTab = tabs[0];
      chrome.scripting.executeScript({
        target: { tabId: activeTab.id },
        func: () => {
          window.postMessage({ type: 'scrollEnd' }, '*');
        },
      });
    });
  }
});

contentScript.js

let scrollTimeout;
const targetDiv = document.querySelector('.c-scrollbar__hider');

function sendScrollEndMessage() {
  chrome.runtime.sendMessage({ type: 'scrollEnd' });
}

targetDiv.addEventListener('scroll', () => {
  clearTimeout(scrollTimeout);
  scrollTimeout = setTimeout(sendScrollEndMessage, 300);
});

manifest.json

{
  "manifest_version": 3,
  "name": "ASDF",
  "version": "1.0",
  "description": "ASDF",
  "host_permissions": ["<all_urls>"],
  "icons": {
    "16": "images/slack-logo.png",
    "32": "images/slack-logo.png",
    "180": "images/slack-logo.png",
    "192": "images/slack-logo.png",
    "512": "images/slack-logo.png"
  },
  "offline_enabled": true,
  "permissions": ["storage", "activeTab", "contextMenus", "tabs", "scripting"],
  "background": {
    "service_worker": "background.js"
  },
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["contentScript.js"]
    }
  ],
  "action": {
    "default_popup": "index.html"
  }
}

I want ‘Scrolled to end’ to be consoled on scroll happens(when scroll ends… even if a small scroll happens).

Chat Engine not reactive – reload

My chat engine react components are not reactive as when i add a chat id doesnt show the new chat in the chat list and similiarly when i add new people in that the new members are only shown the refresh button is created

import ChatList2 from './ChatList'
import { useSelector } from 'react-redux';
import ChatFeed from './ChatList';
import Navbar from "../navbar"

export default function ChatRoom() {
  const user = useSelector((state) => state.user);
  const projectID="819a1503-c401-42af-ba29-96a83c02033d";
  const userName=user.email;
  const userSecret=user.firstname;
  return (
    <div >
      <Navbar/>
       <ChatEngine
        height="calc(100vh - 66px)"  // Corrected the CSS here
        projectID={projectID}
        userName={userName}
        userSecret={userSecret}
      /> 
    </div>
  );
}


How can I implement this text scrolling effect just by using html, css and javascript?

I wanted to create a some cool slider for my website.
I got one reference video for the slider but I have no idea of how to implement the text scrolling effect used in that slider.
I tried using a container for each text and keeping the overflow-y to hidden and then manipulate them using javascript.
However, when the text size vary, it doesn’t looks good.
Can some one give me any ideas of how to implement this idea?

[https://drive.google.com/file/d/1Z9Gid5shAGLxar9Tj_3TLqqQ7Z-zaThw/view?usp=sharing]

I want the text to move independently like in this video.
This effect should occur onScroll event.
Just give me a basic idea, and I don’t want to use any library like gasp, etc.,
I am only expecting the solution in HTML, CSS, JavaScript.

Thank you.

I found error FirebaseError: No document to update: projects/local-eats-discovery/databases/(default)/documents/userChats/pmTVrOVTm1fVLn7WODarHl2WKir2

I am building a chat application with react and firebae following a youtube channel, but I get:

FirebaseError: No document to update: projects/local-eats-discovery/databases/(default)/documents/userChats/pmTVrOVTm1fVLn7WODarHl2WKir2.

I don’t understand in which part i made a mistake. Please help me to solve this problem.

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


import { db } from '../../Firebase/firebase.config';
import { collection, doc, getDoc, getDocs, query, serverTimestamp, setDoc, updateDoc, where } from 'firebase/firestore';
import { AuthContext } from '../../providers/AuthProviders/AuthProviders';

const SearchUser = () => {
    const [userName, setUserName] = useState('');
    const [user, setUser] = useState(null);
    const [err, setErr] = useState(false);
    const [loding,setLoding] = useState(false)
    const { user: currentUser} = useContext(AuthContext);
    console.log(currentUser?.uid);

   useEffect(() => {
    if (!currentUser) {
        setLoding(true)
    }
    setLoding(false)
   },[currentUser])
   
    const handelSearch = async () => { 
        const q = query(collection(db, 'users'), where('displayName', '==', userName));

        try {
            const querySnapshot = await getDocs(q);
            querySnapshot.forEach((doc) => {
                setUser(doc.data());
            });
        } catch (err) { 
            setErr(true);
        }
    }
   
    const handelKey = (e) => { 
        e.code === 'Enter' && handelSearch();
    }


    const handelSelect = async () => {
        // here chacking the group chats in the firebase is exist or not , if not then creat

        { 
            loding && <span> loading...</span>
        }

        const combinedId = currentUser.uid > user.uid ? currentUser.uid + user.uid : user.uid + currentUser.uid;
        
        try {
            const res = await getDoc(doc(db, 'chats', combinedId));
            if (!res.exists()) {
                // create chat in chats collection 
                await setDoc(doc(db, 'chats', combinedId), { message: [] });
            }
        
            // Update userChats documents
            await updateDoc(doc(db, 'userChats', currentUser.uid), {
                [combinedId + '.userInfo']: {
                    uid: user.uid,
                    displayName: user.displayName,
                    photoURL: user.photoURL
                },
                [combinedId + '.date']: serverTimestamp()
            });
        
            await updateDoc(doc(db, 'userChats', user.uid), {
                [combinedId + '.userInfo']: {
                    uid: currentUser.uid,
                    displayName: currentUser.displayName,
                    photoURL: currentUser.photoURL
                },
                [combinedId + '.date']: serverTimestamp()
            });
        } catch (err) {
            console.log(err);
        }
    }
    return (
        <div className="py-3 px-2">
            <div className="w-full flex justify-start items-start gap-3">
                <input 
                    type="text" 
                    className="border-gray-300 border-2 w-full px-3 py-2 rounded-md" 
                    onKeyDown={handelKey} 
                    onChange={e => setUserName(e.target.value)}
                />
            </div>

            {err && <span>User not found</span>}
            {user && 
                <div className='flex justify-start items-start gap-3 p-5 drop-shadow-md bg-gray-100 mt-4' onClick={handelSelect}>
                    <div><img src={user?.photoURL} alt="" className='w-20'/></div>
                    <div>
                        <h4 className='text-2xs font-bold'>{user?.displayName}</h4>
                        <p className='text-sm text-gray-500'>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ea harum veniam aspernatur voluptatem ex non ....</p>
                    </div>
                </div>
            }
        </div>
    );
};

export default SearchUser;





I want to mention that my current user data came little bit late.i console the currentUser, initial render it gives undefind then after few second it gives current user data.

merge 2 array and correct order from checkbox

I’m having trouble merging two arrays. The problem is that the order of the elements displayed is not in the correct order when I click the checkbox.

Elements of arr2 are always located after the array arr1.

here is my code

enter image description here

enter image description here

is there any way for me to get the correct order when the clickbox is like arr1 in the combined array arr3?