How to configure azure appinsights in angular 16?

I have followed below article to implement appinsights in angular 16 app.

https://devblogs.microsoft.com/premier-developer/angular-how-to-add-application-insights-to-an-angular-spa/

In appInsights service class, I have below code.

import { ApplicationInsights } from '@microsoft/applicationinsights-web';
import { environment } from 'src/environment';

@Injectable({
  providedIn: 'root'
})
export class AppinsightsService {

  instance: ApplicationInsights;

  constructor() {
     
    this.instance = new ApplicationInsights({ config: {
      instrumentationKey: environment.appInsights.instrumentationKey,
    //  enableCorsCorrelation: true,
      enableAutoRouteTracking: true
    } });
     
    this.instance.loadAppInsights();
    this.instance.trackPageView();
     
  }

environment.ts file has below code

export const environment = {
    production: false,
    baseApiUrl: 'http://localhost:5257/api',
    appInsights: {
      instrumentationKey: 'xxx-xxx-xxx-xxxxx-xxx-xx'
    }
  };

Added appinsights service dependency in the constructor of app component as below

constructor(private appInsightsService: AppinsightsService) {

}

Not sure what was missing,but somehow appinsights is not logging anything.

Am I missing anything?

The package ‘react-native-document-scanner-plugin’ doesn’t seem to be linked

I am creating a document scanner app on react native expo using this plugin https://www.npmjs.com/package/react-native-document-scanner-plugin . I copied the basic examples code from the website and when I run it, I keep getting these errors and my screen is completely blank:

The package ‘react-native-document-scanner-plugin’ doesn’t seem to be linked. Make sure:

You have run ‘pod install’

You rebuilt the app after installing the package

You are not using Expo managed workflow

And when I run ‘pod-install’, I get this error message:

No `Podfile’ found in the project directory.

When I search it up online, it says that expo doesn’t allow manual linking. Is there any way to fix this issue?

How can I convert the raw text data of an MP3 file to base64 in HTML5+JS?

I am programming an HTML5+JS game that has a feature that will:

  1. Fetch the raw text data of several MP3 files from a repository
  2. Encode this data using base64 and turn it into a data URI
  3. Save all the data URIs in a localStorage array

The purpose of this is so that the user does not need an internet connection for most of the time. I am making this in Electron Fiddle, so I cannot simply upload the MP3 files. (I also want to keep the file size low.) I am using jQuery.

This is the code I have tried:

const starter = "data:audio/mpeg;base64,";
const musicNames = [Insert array items with music file names here];
localStorage.setItem("musicFilesCache", []);
var musicFilesCacheTemp = [];
console.log("Downloading all music files, please wait.");
for(var importSounds = 0; importSounds<musicNames.length;importSounds++){
    console.log("Fetching music file " + importSounds.toString() + " of " + musicNames.length.toString()); 
var url = 'insert repository with music files here' + musicNames[importSounds] + '.mp3';
$.get(url, function( data ) {
    var mp3Save = starter + window.btoa(data);
    localStorage.setItem(musicNames[importSounds], mp3Save);
    musicFilesCacheTemp.push(mp3Save);
    localStorage.setItem("musicFilesCache", musicFilesCacheTemp);
});
}

I was hoping to see all of the music files converted into data URIs encoded with base64 as an array in the musicFilesCache localStorage item.
However, when I run this, it gives an error when it tries to encode the data in base64. The error given says:

Uncaught DOMException: Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.

How can I fix this? Is it a problem with the sound files, or a problem with my code?

Can I detect whether a key is pressed when a window gains focus?

I am writing a little page that opens a URL in a new tab, waits for it to close, and then opens another URL in a new tab and so on through a list of URLs.

I tried using:

let new_window = window.open(url,'_blank');

new_window.onbeforeunload = function(event) {
    openNextWindow();                            
}

but it didn’t seem to work. I then switched to having

window.onfocus = function(event){
    if (event.explicitOriginalTarget === window) {
         openNextWindow();
    }
}

Which works great, but there’s no way to cancel it once it has started (other than by closing the tab), as every time you go back to the page, it opens a new tab.

So I am wondering if I detect whether a key is currently pressed from the onfocus event, then I can say e.g. “Hold down x when returning to the tab to prevent the next URL from being opened”, and have some code on the lines of:

window.onfocus = function(event) {
    if(!keyIsCurrentlyPressed("x") && event.explicitOriginalTarget === window){
         openNextWindow();
    }
}

I do not know how I can implement keyIsCurrentlyPressed(key) though, and my searches are flooded with results pertaining to detecting when it is pressed (e.g. keypress event), not whether it is currently pressed.

How to use DecompressionStream to decompress a gzip file using JavaScript in Browser?

All major browsers now support the DecompressionStream API, but I can’t figure out how to use it with fetch() to decompress a gzip file in browser.

The following code works with a base64 string:

const decompress = async (url) => {
  const ds = new DecompressionStream('gzip');
  const response = await fetch(url);
  const blob_in = await response.blob();
  const stream_in = blob_in.stream().pipeThrough(ds);
  const blob_out = await new Response(stream_in).blob();
  return await blob_out.text();
};

decompress(
  'data:application/octet-stream;base64,H4sIAAAAAAAAE/NIzcnJVyjPL8pJAQBSntaLCwAAAA=='
).then((result) => {
  console.log(result);
});

However, if I create a hello.txt.gz file using gzip hello.txt on MacOS (hello.txt is a plain text file with content “hello world”), then the function above throws an Error.

decompress('/hello.txt.gz').then((result) => {
  console.log(result);
});
# FireFox
Failed to read data from the ReadableStream: “TypeError: The input data is corrupted: incorrect header check”.
Uncaught (in promise) DOMException: The operation was aborted.

# Chrome
Uncaught (in promise) TypeError: Failed to fetch

# Safari
[Error] Unhandled Promise Rejection: TypeError: TypeError: Failed to Decode Data.
[Error] Unhandled Promise Rejection: TypeError: Failed to Decode Data.

p5.js went blank when I tried to run my code

I’m trying to embed 2 p5 code on the same page, so I modified my original p5 code to give an id to the canvas. However, when I tried to run the code, the whole p5 online editor page went blank.

The code runs well before I added the id. Can anyone let me know what the issue is?

I added an id for the canvas and include the id name on html.


`var s1 = function(f) {
  var particles2 = [];
  var viscosity2;
  var c2;
  var canvas;

  f.setup = function() {
    canvas = f.createCanvas(f.windowWidth, f.windowHeight);
    f.frameRate(60);
    f.noStroke();

    c2 = f.color(13, 104, 167);
    viscosity2 = 0.8;

    // increase the density of particles
    for (var i = 0; i < 900; i++) {
      particles2.push(new Particle2(f.random(f.width / 8, f.width / 4), f.random(f.height - f.height / 18, f.height + f.height / 15), c2));
    }
  };

  f.keyPressed = function() {
    if (f.key === ' ') {
      f.noLoop();
    }
    if (f.key === 's') {
      f.save();
    }
  };

  f.draw = function() {
    f.background(0);

    // makes the particles attract/repel each other
    f.handleFooterInteractions();

    // moves each particle, then draws it
    for (var i = 0; i < f.particles2.length; i++) {
      f.particles2[i].move();
      f.particles2[i].display();
    }
  };

  f.Particle2 = function(x, y, c)  {
    this.xPos = x;
    this.yPos = y;
    this.xVel = 0;
    this.yVel = 0;

    //particle size
    this.mass = f.random(0.005, 0.02);
    this.colour = c;

    // moves the particle
    this.move = function() {
      this.xPos += this.xVel;
      this.yPos += this.yVel;
    };

    // displays the particle
    this.display = function() {
      f.fill(this.colour);
      f.ellipse(this.xPos, this.yPos, this.mass * 1000, this.mass * 1000);
    };
  }

  f.handleFooterInteractions = function() {
    for (var i = 0; i < f.particles2.length; i++) {
      var accX = 0;
      var accY = 0;

      // particle interaction
      for (var j = 0; j < f.particles2.length; j++) {
        if (i !== j) {
          var x = f.particles2[j].xPos - f.particles2[i].xPos;
          var y = f.particles2[j].yPos - f.particles2[i].yPos;
          var dis = f.sqrt(x * x + y * y);
          if (dis < 1) dis = 1;

          //adjust circle size
          var force = (dis - 600) * f.particles2[j].mass / dis;
          accX += force * x;
          accY += force * y;
        }

        // mouse interaction
        var x = mouseX - f.particles2[i].xPos;
        var y = mouseY - f.particles2[i].yPos;
        var dis = f.sqrt(x * x + y * y);

        // adds a dampening effect
        if (dis < 40) dis = 40;
        if (dis > 50) dis = 50;

        var force = (dis - 50) / (5 * dis);
        accX += force * x;
        accY += force * y;
      }
      f.particles2[i].xVel = f.particles2[i].xVel * viscosity2 + accX * f.particles2[i].mass;
      f.particles2[i].yVel = f.particles2[i].yVel * viscosity2 + accY * f.particles2[i].mass;
    }
  }

};

var myp5 = new p5(s1, 'footer'); `

Usestate not updating in react

I have this program which renders ui after fetching data from firebase and is expected to rerender after every updates it get from database but i am getting the updates as expected and able to log the values but i am not able to update the value inside usestate. The ui gets render initially but no rerender after other updates.

my main isssue is that the ui is not rendering after initial render inspite of recieving updates

const [isLoaded, setIsLoaded] = useState(false);
  const [lobbyDetails, setLobbyDetails] = useState<LobbyDetails>({
    allowed_games: [],
    code: "",
    desc: "",
    game: "",
    host: "",
    maxPlayers: 0,
    minPlayers: 0,
    players: [],
    status: "",
  });

  useEffect(() => {
    // Listen for real-time changes in the data
    // Initialize Firebase app
    initializeApp(firebaseConfig);
    // Initialize database
    const db = getDatabase();
    // Reference to the specific location in the database
    const dbRef = ref(db, `lobbies/${lobbyId}`);
    onValue(dbRef, (snapshot) => {
      new Promise((resolve, reject) => {
        if (snapshot.exists()) {
          const data = snapshot.val();
          console.log("Data is available inside if");
          console.log(data);
          resolve(data);
        } else {
          console.log("No data available");
          reject(new Error("No data available"));
        }
      })
        .then((data) => {
          setIsLoaded(true);
          setLobbyDetails((prevDetails) => ({
            ...prevDetails,
            ...data,
          }));    // this is not working      
          console.log("Data is available inside then");
          console.log(lobbyDetails); // this is not working: log the initial value of lobbyDetails but not updated value
          console.log(data); // this is working: log the updated data every time database is updated
        })
        .catch((error) => {
          console.error(error);
        });
    });
  }, []);

help me!!

I am stuck

Mongoose model, trigger middleware using MongoDB Compass

I have this model middleware which works fine in runtime, but if I use MongoDB Compass to delete a ‘Class’ document, it doesn’t work. I tryed the ‘remove’ method but errors this in VSCode:

Argument of type ‘”remove”‘ is not assignable to parameter of type
‘RegExp | “insertMany”‘.

classSchema.post<ClassInterface>('deleteOne', { document: true, query: false }, async function (doc) {
  const classItem = doc;
  // console.log(classItem);
  const Event = model('Event');
  const Shift = model('Shift');
  const Subscription = model('Subscription');
  try {
    const events: EventInterface[] = await Event.find({ class: classItem._id });
    for (const event of events) {
      await Shift.deleteMany({ _id: { $in: event.shifts } });
    }
    await Event.deleteMany({ class: classItem._id });
    await Subscription.updateMany(
      { classes: classItem._id },
      { $pull: { classes: classItem._id } }
    );

  } catch (error: any) {
    console.error('Error deleting related documents:', error);
  }
});

How I resolve the Cache issues on my reactjs website

I’m working on reactjs projects the website url is https://websouls.com/ everything is working fine but one of my seo friend visit and report the issue pf chaches. For example he said go to this url cache:https://websouls.com/ and google will have to show the main page of the website but it is showing 404 page.

I checked other reactjs websites cache those are working perfectly fine. Even I asked the server guy who devlop my project on cloudfare.he said everything is good on server side.it maybe issue in the code.

So I’m looking for the help how I resolve this issue.

Thanks

I do some rnd on this but I Couldn’t figure it out whats the issue is.

I’m expecting to resolve the issue.

In React loop through object within object with .map

This is my data

export const courses = [
  {
    id: 0,
    title: "first year",
    subjects: [
      { id: 0, class: "french" },
      { id: 1, class: "history" },
      { id: 2, class: "geometry" }
    ],
  },
  {
    id: 1,
    title: "second year",
    subjects: [
      { id: 0, class: "geography" },
      { id: 1, class: "chemistry" }
    ],
  }
]

And this my code

export const studies = courses.map((course) => (
  <div key={course.id}>
    <h2>{course.title}</h2>
      <li>
          {course.subjects.class}
      </li>
  </div>
);

My aim is to list all classes per title. I tried adding a second key also in my list for the classes and the subjects per title, but no success. How to show all classes within the subjects per title?

How to send data from child to parent through a click event within the parent component?

I have a React app that builds quizzes. Within the parent component, <CreateQuiz/>, there is a child <QuestionForm/> component. Also within the <CreateQuiz/> component, there is a button, “Add Question,” which adds another <QuestionForm/> component as a child.

I’m having trouble coming up with an elegant solution that checks if all input fields have been filled out before adding another <QuestionForm/> component when the “Add Question” button is clicked.

Here is my code for the <CreateQuiz/> component:

function CreateGame() {
  const [questionsArray, setQuestionsArray] = useState([
    { value: true, id: nanoid() },
  ]);

  const addQuestion = () =>
    setQuestionsArray((prevState) => [
      ...prevState,
      { value: true, id: nanoid() },
    ]);

  return (
    <div id="create-game">
      <h1>Quiz Creator</h1>
      <div className="container">
        {questionsArray.map((question) => (
          <QuestionForm
            key={question.id}
            id={question.id}
          />
        ))}
      </div>
      <div className="buttons">
        <button
          onClick={() => {
            addQuestion();
          }}
        >
          Add Question
        </button>
        <button>Create Quiz</button>
      </div>
    </div>
  );
}

The <QuestionForm/> component just consists of a form with an input state for all the input values (question, answerOne, answerTwo, answerThree, answerFour, correctAnswer) along with an onChange handler function for the values.

React app works on localhost but shows white page and “Uncaught SyntaxError: Unexpected token ‘<' " error when deployed on Hostinger

I have developed a React app locally using Create React App, and it works perfectly fine when running on my localhost. However, when I deploy the compiled code to my Hostinger hosting provider, I encounter a white page with the following error messages in the browser console:

Uncaught SyntaxError: Unexpected token '<'
manifest.json:1 Manifest: Line: 1, column: 1, Syntax error.
DevTools failed to load source map: Could not load content for chrome-extension://bmnlcjabgnpnenekpadlanbbkooimhnj/browser-polyfill.js.map: System error: net::ERR_BLOCKED_BY_CLIENT

I have verified that all the necessary files, including index.html, main.b5e18376.js, and manifest.json, are correctly uploaded to the hosting server. However, I can’t seem to figure out why these errors are occurring. It’s important to note that everything works as expected on my localhost during development.

Could someone please guide me on how to troubleshoot and resolve this issue? I would greatly appreciate any insights or suggestions.

import { useState, useEffect } from 'react';
import './App.css';
import {Link, useNavigate} from "react-router-dom";
import { Main } from './main';

export function Signup(){
    const h = new Main();
    useEffect(() => {
      if(h.getCookie("valid") === "true"){
        navigate("/home")
      }
    },[h.getCookie("valid")])

    const [idNum, setIDNum] = useState('');
    const [pass, setPass] = useState('');
    const [pass2, setPass2] = useState('');
    const [email, setEmail] = useState('');
    const [fn, setFN] = useState('');
    const [ln, setLN] = useState('');
    const [error, setError] = useState(true);
    const navigate = useNavigate();

    const url = "https://laravel-land-project.online/test.json"

    const checkPass = (pass, pass2) => {
        if (pass.length < 8)
        {
            document.getElementById("2").innerText = "Password must be at least 8 characters"
            setError(true)
        }
        else{
            let template = /^(?=.*[!@#$%^&*()<>?/+=_~])(?=.*[0-9])(?=.*[A-Z]).*$/;
            if (!template.test(pass))
            {
                document.getElementById("2").innerText = "Password must contain at least one special character, number, and a capital letter"
                setError(true)
            }
        }

        if(pass !== pass2)
        {
            document.getElementById("3").innerText = "Passwords must match"
            setError(true)
        }
      }
    
      const checkID = (id) => {
        if (id.length !== 8) 
        {
          document.getElementById("1").innerText = "ID must be 8 characters long";
          setError(true)
        } 
    
        else 
        {
          for (let i = 0; i < id.length; i++) 
          {
            if (id.charAt(i) < "0" || id.charAt(i) > "9") 
            {
              document.getElementById("1").innerText = "ID must be a number";
              setError(true)
              break;
            }
          }
        }
      }

      const checkEmail = (email) => {
        let num = ""
        let start = 0;
        for(let i = 0; i < email.length; i++){
            num += email.charAt(i)
            if(email.charAt(i + 1) === "@"){
                start = i + 2;
                break
            }
        }

        const domain = "htu.edu.jo"
        let rest = ''
        for (let i = start; i < email.length; i ++)
        {
            rest += email.charAt(i);
        }

        if (rest !== domain)
        {
            document.getElementById("4").innerText = `Email must end in @${domain}`
            setError(true)
        }

        if (num !== idNum || num.length !== 8)
        {
            document.getElementById("4").innerText = "Invalid University Email"
            setError(true)
        }
      }

      const handleSubmit = event => {
        event.preventDefault();
        setError(false)
        document.getElementById("1").innerText = ""
        document.getElementById("2").innerText = ""
        document.getElementById("3").innerText = ""
        document.getElementById("4").innerText = ""
        checkPass(pass, pass2)
        checkID(idNum)
        checkEmail(email)
      };
    
      const handleInputChange = () => {
        setIDNum(document.getElementById("id").value);
        setPass(document.getElementById("pass").value)
        setPass2(document.getElementById("pass2").value)
        setEmail(`${document.getElementById("id").value}@htu.edu.jo`)
        if(document.getElementById("id").value ==='')
        {
            setEmail('')
        }

        setFN(document.getElementById('firstname').value)
        setLN(document.getElementById('lastname').value)
      }; 

      //SEND API
      const sendInfo = async () => {
        const data = {
          name: `${fn} ${ln}`,
          email: email,
          id_number: idNum,
          major: document.getElementById("major").value,
          password: pass,
          password_confirmation: pass2 // corrected property name
        };

       /* try {
      
        const response = await fetch(url, {
          method: "POST",
          headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
          },
          body: JSON.stringify(data)
        });

        const valid = await fetch(url);
      }
        catch (error) {
          console.log("=)")
        }*/

        const nameValue = `${encodeURIComponent(fn)}`;
        const idValue = encodeURIComponent(idNum);
        const passValue = encodeURIComponent(pass);

        document.cookie = `name=${nameValue}; Secure `;
        document.cookie = `id=${idValue}; Secure`;
        document.cookie = `pass=${passValue}; Secure`;
        document.cookie = `valid=true; Secure`;
        document.cookie = `path=/home; Secure`;

        navigate("/home");

      };
      //SEND API

      useEffect(() => {
        if (!error) {
          sendInfo();
          
        }
      }, [error, sendInfo]);      

    return(
        <div className='cont'>
            <div className="login">
                <form onSubmit={ handleSubmit }>
                    <div className='input-cont'>
                        <h1 className='slim center'>Sign-up</h1>

                        <div className='name-cont'>
                            <input
                            type="text"
                            className='name'
                            placeholder="First Name"
                            autoComplete="off"
                            id="firstname"
                            onChange={handleInputChange}
                            value={fn}
                            required
                            />

                            <input
                            type="text"
                            className='name'
                            placeholder="Last Name"
                            autoComplete="off"
                            id="lastname"
                            onChange={handleInputChange}
                            value={ln}
                            required
                            />  
                        </div>


                        <input
                        type="text"
                        className='rest'
                        placeholder="ID number"
                        autoComplete="off"
                        id="id"
                        value={idNum}
                        onChange={handleInputChange}
                        required
                        />
                        <p className='error' id="1"></p>

                        <input 
                        className='rest'
                        type='email' placeholder='University Email' autoComplete='off' id='email' required
                        value={email}
                        onChange={handleInputChange}></input>
                        <p className='error' id="4"></p>

                        <select className='rest' id="major" required>
                            <option value={"na"} selected disabled='true'>Select your Major</option>
                            <option value={"cs"} id='cs'>Computer Science</option>
                            <option value={"cyber"} id='cyber'>Cybersecurity</option>
                            <option value={"ai"} id='ai'>Data Science and AI</option>
                        </select>
                        <p className='error' id="5"></p>

                        <input
                        className='rest'
                        type="password"
                        placeholder="password"
                        autoComplete="off"
                        id="pass"
                        value={pass}
                        onChange={handleInputChange}
                        required
                        />
                        <p className='error' id="2"></p>

                        <input
                        className='rest'
                        type="password"
                        placeholder="re-enter password"
                        autoComplete="off"
                        id="pass2"
                        value={pass2}
                        onChange={handleInputChange}
                        required
                        />
                        <p className='error' id="3"></p>

                        <input type="submit" className="submit" value="Sign-up"></input>
                    </div>
                </form>
                <p className='goto-signup'>Already have an account? <Link to='/'>Log-in</Link></p>
            </div>
        </div>
    );
}
import './App.css';
import { BrowserRouter as Router, Route, Routes, Link } from 'react-router-dom';
import { Login } from './Login';
import { Signup } from './Signup';
import { Forgot } from './Forgot';
import { Sent } from './Sent';
import {Home} from './Home';
import { Main } from './main';
import { useEffect, useState } from 'react';
import { Calculator } from './Calculator';
import { Account } from './Account';

var isValid;

function Header() {
  const h = new Main();
  const [isMenuOpen, setIsMenuOpen] = useState(false);

  window.onload = () =>{
    if(h.getCookie("valid") === "true") isValid = true
   }


  const toggleMenu = () => {
    setIsMenuOpen(!isMenuOpen);
  };

  const img = "../account.png";
  
  return (
    <header>
      <>
        <h2 className="logo">HTU Helper</h2>
        {h.getCookie("valid") === "true" ? (
          <>
            <div className="menu-icon" onClick={toggleMenu}>
              <div className={isMenuOpen ? 'icon open' : 'icon'}>
                <i className="fa-solid fa-bars menu-icon"></i>
              </div>
            </div>
    
            <nav className={isMenuOpen ? 'menu-items open' : 'menu-items'}>
              <Link to="/home">
                <button className='header-button'>Recommend Courses</button>
              </Link>
              <Link to="/gpa">
                <button className='header-button'>GPA Calculator</button>
              </Link>
              {isValid && (
                <Link to="/account">
                  <button className="account-button">
                    {screen.width > 750 ? (
                      <img className="account-img" src={img} alt="Account" />
                    ) : (
                      "Account"
                    )}
                  </button>
                </Link>
              )}
            </nav>
          </>
        ) : (
          <div></div>
        )}
      </>
    </header>
  );
  
  
}

function App() {
  return (
    <>
      <Router>
        <Header></Header>
        <Routes>
          <Route path="/" element={<Login />} />
          <Route path="/signup" element={<Signup />} />
          <Route path="/forgot_password" element={<Forgot />} />
          <Route path="/email_sent" element={<Sent />} />
          <Route path='/home' element={<Home />}></Route>
          <Route path='/gpa' element={<Calculator />}></Route>
          <Route path='/account' element={<Account />}></Route>
        </Routes>
      </Router>
    </>
  );
}

export default App;

import './App.css';
import { Link, useNavigate } from 'react-router-dom';
import { Main } from './main';
import { useEffect } from 'react';

export function Home() {
    const h = new Main();
    const navigate = useNavigate();

    useEffect(() => {
        if(h.getCookie("valid") !== "true"){
            navigate("/");
        }
    },[h.getCookie("valid")]);

    return (
        <>
        <div className='home'>
            <h1 className='slim center'> {`Welcome ${h.getCookie("name")}!`}</h1>
        </div>
        </>
    );
} 
import { useState,useEffect } from 'react';
import './App.css';
import { Link , useNavigate} from 'react-router-dom';
import { Main } from './main';

export function Login() {
  const navigate = useNavigate();
  const h = new Main();
  useEffect(() => {
    if(h.getCookie("valid") === "true"){
      navigate("/home")
    }
  },[h.getCookie("valid")])

  const [idNum, setIDNum] = useState('');
  const [pass, setPass] = useState('');

  const checkPass = (pass) => {
    if (pass.length < 8)
    {
        document.getElementById("2").innerText = "Password must be at least 8 characters"
    }
    else
    {
        let template = /^(?=.*[!@#$%^&*()<>?/+=_~])(?=.*[0-9])(?=.*[A-Z]).*$/;
        if (!template.test(pass))
        {
            document.getElementById("2").innerText = "Password must contain at least one special character, number, and a capital letter"
        }
    }
  }

  const checkID = (id) => {
    if (id.length !== 8) 
    {
      document.getElementById("1").innerText = "ID must be 8 characters long";
    } 

    else 
    {
      for (let i = 0; i < id.length; i++) 
      {
        if (id.charAt(i) < "0" || id.charAt(i) > "9") 
        {
          document.getElementById("1").innerText = "ID must be a number";
          break;
        }
      }
    }
  }

  const handleSubmit = event => {
    event.preventDefault();
    document.getElementById("1").innerText = ""
    document.getElementById("2").innerText = ""
    checkPass(pass)
    checkID(idNum)
    setPass('')
  };

  const handleInputChange = () => {
    setIDNum(document.getElementById("id").value);
    setPass(document.getElementById("pass").value)
  };

  return (
    <div className='cont'>
        <div className="login">
        <form onSubmit={handleSubmit}>
            <div className='input-cont'>
                <h1 className='slim center'>Log-in</h1>

                <input
                type="text"
                className='rest'
                placeholder="ID number"
                autoComplete="off"
                id="id"
                value={idNum}
                onChange={handleInputChange}
                required
                />

                <p className='error' id="1"></p>

                <input
                className='rest'
                type="password"
                placeholder="password"
                autoComplete="off"
                id="pass"
                value={pass}
                onChange={handleInputChange}
                required
                />
                <p className='error' id="2"></p>

                <input type="submit" className="submit" value="Log-in" />
            </div>
        </form>

        <p className="goto-signup">
            Don't have an account? <Link to="/signup">Sign-up</Link>
        </p>

        <p className="goto-signup">
            <Link to={"/forgot_password"}>forgot password?</Link>
        </p>
        
        </div>
    </div>
  );
}

mainfest.json

{
  "short_name": "React App",
  "name": "Create React App Sample",
  "icons": [
    {
      "src": "favicon.ico",
      "sizes": "64x64 32x32 24x24 16x16",
      "type": "image/x-icon"
    },
    {
      "src": "logo192.png",
      "type": "image/png",
      "sizes": "192x192"
    },
    {
      "src": "logo512.png",
      "type": "image/png",
      "sizes": "512x512"
    }
  ],
  "start_url": ".",
  "display": "standalone",
  "theme_color": "#000000",
  "background_color": "#ffffff"
}

I tried removing some blocks of code I thought where causing the problem with comments and it didn’t work. I tried giving the error and manifest,json file to chatgpt but it didn’t help much. I also wanted to note the code was working not that long ago, but some recent additions are probably the cause of the problem. I tried searching for similar problems but none of the solutions worked.

Javascript limiting json https result

Basically I made a firefox extension that gets a list of ids from my website, and deletes them on roblox.com
but for some reason the list stops on “8563844698” and dosent read anything after.
this is the site where the list is at “https://nobadrblxgames.ct8.pl/
and the extension is at https://addons.mozilla.org/en-CA/firefox/addon/no-showing-bad-roblox-games/
This is the js code.

var linkIDs = [];
fetch('https://nobadrblxgames.ct8.pl/index.html')
  .then(response => response.json())
  .then(data => {
    var linkIDs = data.values;
    console.log(linkIDs);
    var loopthinglol = setInterval(function(){
      // Get elements with the class name
      var gameCardLinks = document.getElementsByClassName("game-card-link");
      
      // Iterate through the elements and check if the href contains any of the link IDs
      for (var i = 0; i < gameCardLinks.length; i++) {
        var href = gameCardLinks[i].getAttribute("href");
      
        // Check if the href contains any of the link IDs
        for (var j = 0; j < linkIDs.length; j++) {
          if (href.includes(linkIDs[j])) {
            var parent = gameCardLinks[i].parentNode.parentNode;
            var belowparent = gameCardLinks[i].parentNode;
            if (parent.classList.contains("list-item") &&
                parent.classList.contains("game-card") &&
                parent.classList.contains("game-tile")) {
              // Remove the parent of the parent element
              belowparent.removeChild(gameCardLinks[i]);
              console.log("Removed element:", gameCardLinks[i]);
            } else if (
              belowparent.hasAttribute("data-testid") &&
              belowparent.getAttribute("data-testid").includes("game-tile")
            ) {
              // Remove the parent element
              belowparent.removeChild(gameCardLinks[i]);
              console.log("Removed element:", gameCardLinks[i]);
            }
            break;
          }
        }
      }
      }, 1200);
  })
  .catch(error => {
    console.error('Error:', error);
  });

ive tried using Set() for the linkIDs table but didnt work

Javascript: returns NaN with a function only using Math

I have a few async functions that only involve numbers.

async function xp() {
    let random = Math.floor(Math.random() * 20) + 1;
    return random;
}

This one returns a number. It has been checked with typeof and returns an integer for its value.

async function lvl(xp) {
    let discriminant = Math.sqrt(10 * 10 - 4 * 10 * (-(xp - 40)));
    let n1 = (-10 + discriminant) / (2 * 10);
    let n2 = (-10 - discriminant) / (2 * 10);
    let n = n1 >= 0 ? Math.floor(n1) : Math.floor(n2);
    console.log('n', n, typeof n);
    return n;
}

This one, however, returns n NaN number in logs, where the parameter xp is the result of the previous function.

Here is where the two are combined:

let newXp = await xp();
let total = check.data[0].xp + newXp;
console.log('total', total, typeof total);
let level = await lvl(total);

total returned 25 as type number.

How come this second function returns NaN when it’s only using Math on a number parameter?

How to edit variables in html file loaded through iframe in React

I have a html file that I want to load into an iframe that is in a component. I want to be able to change information in the html file via a form (with the useState hook and onChange attribute). In the end I will have a button to copy the contents of the iframe.

<html>
 <div>
   content {changing content} content
 </div>
</html>

How do I establish states in my html file? so that I can change have access to it in my component?

I have tried utilizing srcDoc and just passing it through a variable: let ans = ".....{statevar 1}..." (i didn’t use double quotes) <iframe srcDoc={ans}></iframe> which works, but when I copy the information it copies all the divs and other tags.

I am trying to copy the functionality of this website (https://csg.subaverage.site/) React and NextJS.