How to write generic type for types extraction in Typescript

I am trying to extract types based on input type.

My code is:

type ArrayElement<T> = T extends Array<infer U> ? U : never;

interface Field {
    key: string;
    value: number | string;
    required?: boolean;
}

interface Props {
    test: number;
    fields: Field[];
}

type Rt<T extends Field> = Record<T['key'], T['value']>; 

const someFn = <T extends Field[]>(props: Props) => {
    const v = props.fields.reduce(
        (acc, vv) => ({
            ...acc,
            [vv.key]: vv.value,
        }),
        {},
    );

    return v as Rt<ArrayElement<T>>;
};

const p: Props = {
    test: 1,
    fields: [
        { key: 'name', value: 'John' },
        { key: 'age', value: 30 },
    ],
};

const r = someFn(p);

// eslint-disable-next-line prettier/prettier, no-console
console.log(r.name, r.age); // name should be string type, age should be number type

Problem is, that return type is not perfect. My question is which Typescript operators should I use for correct extraction from Field type. Name should be string type, age should be number type.

Right now both of my variables are union type string | number.

What is wrong with my code?

I tried to create custom type and this type is described in my question.

What is the best field for EEE,CMPE engineer? [closed]

I graduated from electrical and electronics engineering and now starting my computer science master degree, I want some advice to get the most out of those two degrees, to land the best job and field.

I investigated data scientist, data engineer, network engineer, cloud engineer,web development careers, but still i want to discuss it again with you guys

Delete input value after format it into group of 4 digits in javaScript

I have a card-number input wich when type numbers in it, it will be formatted as a group of “4 digits” and a “whitespace” after it instead of writing the numbers as 16 digits without any whitespace

The code I use

input.value = input.value.replace(/d{4}/g, "$& ");

Bug

After replacing the input.value in format that I want, I can not delete the value unless I click on a specific group of numbers, for example:

input.value is:
“1234 5678 9123 4567 “

Now when I press “Backspace key” on keyboard, it won’t delete the numbers, to do so, i need click on “4567” to be able to delete this group.

how can I fix this?

setState function is not setting the value in the variable

This is a project in nextjs.
i am trying to set the imgfileId and docfileId but it is not getting set , i am setting it after getting response from the server , i can console the value but not getting stored in variable , i have read several answers where it says it is async and doesn’t log because of it but in this case i am accessing the varible in another function and it is not even showing value there

const Upload = () => {
  const router = useRouter();

  // list of options for rendering different options
  const [imgfileID, setImgFileID] = useState("");
  const [docfileID, setDocFileID] = useState("");

  const [fileEvents, setFileEvents] = useState({
    fileEvent: "",
    imgEvent: "",
  });

  const fileHandler = service;

   const handleFileUpload = async (file) => {
    const selectedFile = file;

    if (selectedFile) {
      try {
        setIsUploadInProgress(true);
        const response = await fileHandler.uploadFile("Docs", selectedFile);
        // console.log("Doc File upload response", response);
        setDocFileID(response.$id);
        console.log("file id", docfileID);
        console.log("file id res",response.$id);
        setIsDocFilesUploaded(true);
        return response;
      } catch (error) {
        console.log("Error occurred while uploading file", error);
      } finally {
        setIsUploadInProgress(false);
      }
    } else {
      alert("No file selected");
    }
  };

  const handleCoverPageUpload = async (file) => {
    const selectedFile = file ;

    if (selectedFile) {
      try {
        setIsUploadInProgress(true);
        const response = await fileHandler.uploadFile("Image", selectedFile);
        // console.log("Image File upload response", response);
        console.log("img id", imgfileID);  
        console.log("file id res",response.$id);

        setImgFileID(response.$id);
        setIsImgFilesUploaded(true);
        return response;
      } catch (error) {
        console.log("Error occurred while uploading file", error);
      } finally {
        setIsUploadInProgress(false);
      }
    } else {
      console.log("No file selected");
    }
  };


Handling Unpredictable MediaError AUDIO_RENDERER_ERROR with HTML Audio Element

When attempting to play the audio using the HTML audio element, it sometimes fails to play, resulting in a MediaError with the message ‘AUDIO_RENDERER_ERROR’ and error code 3. When trying to play multiple times, the audio starts to play randomly.

Steps to reproduce the problem

  • Initialize an audio context.
  • Fetch the list of MP3 audio files.
  • Decode MP3 files to obtain audio buffers.
  • Combine decoded audio buffers into a single buffer.
  • Convert the combined buffer into WAV format.
  • Generate a blob from the WAV audio data.
  • Create a URL for the joined audio data.

Observations:

  • The issue is being reproduced specifically in android devices.
  • The issue does not occur in Firefox, Safari, issue occurs specifically in Chromium based browsers (Chrome, Edge).

Mailchimp signup form automation using cypress

I have a Mailchimp signup form embedded to my website and I’m trying to automate the form submissions with the help of cypress.
Currently I’m trying a basic test with filling the input fields using type() method and then submitting the form using click() on submit button element. It’s filling up the input fields and also submitting the form. See the attachment here https://ibb.co/rZvWsCy

But, after click on submit it redirects to different page and there it’s displays the errors for required input fields even after getting filled into the form by using type(). See the attachment https://ibb.co/2qc26DN

It seems like the input field values are not getting read by the mailchimp AJAX that calls after submitting the form.

Do anyone have experienced this before? Is there any workaround or another way to work with mailchimp forms?

Here, I’m attaching the code that I’d tried:

describe('Mailchimp Form Submission', () => {
it('passes', () => {
    cy.visit('https://example.com/subscribe')

    cy.get('#mce-EMAIL').type('[email protected]').then(
        $input => {
            cy.log('Value attribute after typing:', $input.val())
        }
    )
    cy.get('#mce-FNAME').type('Test')
    cy.get('#mce-LNAME').type('Test')

    cy.get('input[type=submit]').contains('Subscribe', { matchCase: false }).click()
    
  })
})

Any help is appreciated. Thanks!

Uncaught ReferenceError: $ is not defined funciones.js:3 [closed]

estoy haciendo un proyecto con PHP, MySQL y AJAX. Tengo el problema que no me esta reconociendo el jquery. Utilizo el jquery-3.6.0.js
enter image description here

Intento listar a los Usuarios de la siguiente manera:
fuciones.js:

document.addEventListener("DOMContentLoaded", function(){
    tblUsuarios = $('#tbUsuarios').DataTable({
        ajax: {
            url: base_url + "Usuarios/listar",
            dataSrc: ''
        },
        columns: [
            {'data' : 'Id_usuario'},
            {'data' : 'Login_us'},
            {'data' : 'Nombres_us'},
            {'data' : 'Cargo_us'},
            {'data' : 'Rol_us'},
            {'data' : 'Caja_caj'},
            {'data' : 'Estado'},
            {'data' : 'Acciones'}
        ]
    } );
})

Esta es la tabla en el index.php:

<table class="table table-light" id="tbUsuarios">
    <thead class="thead-dark">
        <tr>
            <th>Id</th>
            <th>Usuario</th>
            <th>Nombre</th>
            <th>Cargo</th>
            <th>Rol</th>
            <th>Caja</th>
            <th>Estado</th>
            <th>Acciones</th>
        </tr>
    </thead>
</table>

Y de esta manera, llamo a los scripts:

        <script src="<?php echo base_url; ?>Assets/js/jquery-3.6.0.js" crossorigin="anonymous"></script>
        <script src="<?php echo base_url; ?>Assets/js/bootstrap.bundle.min.js"></script>
        <script src="<?php echo base_url; ?>Assets/js/scripts.js"></script>
        <script src="<?php echo base_url; ?>Assets/js/Chart.min.js"></script>
        <script src="<?php echo base_url; ?>Assets/DataTables/datatables.min.js"></script>
        <script src="<?php echo base_url; ?>Assets/js/sweetalert2.all.min.js"></script>
        <script>
            const base_url = "<?php echo base_url; ?>";
            </script>
        <script src="<?php echo base_url; ?>Assets/js/funciones.js"></script>

Importing variables from one JS file to another

Okay, so here’s the issue:
I was trying to export the arr from script.js to script1.js, but I get this

Uncaught SyntaxError: Cannot use import statement outside a module (at script1.js:1:1)

The js files are in a folder which is in the same directory as the html files. It’s a form that takes input in index.html and stores in script.js, but then, it stores the inputs in an array and exports it, which is imported in script1.js.

Could someone please help me out with this?

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Timetable Scheduler</title>
    <link rel="shortcut icon" href="https://www.freeiconspng.com/thumbs/calendar-image-png/calendar-image-png-3.png" type="image/x-icon">
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
    <style>
        body {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            min-height: 100vh;
            background-color: #212529;
    background-image: url("https://www.transparenttextures.com/patterns/dark-wood.png");
        }
        form {
            margin: 50px;
        }
    </style>
    <script type="module" src="script/script.js"></script>
</head>
<body class="bg-dark text-light">
    <h1>Timetable Scheduler</h1>
    <form id="form" action="./Scheduler" class="d-flex justify-content-center align-items-center flex-column" method="post">
        <div class="row">
            <div class="col-md-6 col-sm-12 col-lg-3 d-flex flex-column justify-content-end pt-4">
                <label for="" class="form-label">Enter number of classes in a day (including leisure hours) </label>
                <input value="" type="number" class="form-control" name="totalHours" id="totalHours" required>
            </div>
            <div class="col-md-6 col-sm-12 col-lg-3 d-flex flex-column justify-content-end pt-4">
                <label for="" class="form-label">Enter duration of each hour (in minutes) </label>
                <input value="" type="number" class="form-control" name="classDuration" id="classDuration" required>
            </div>
            <div class="col-md-6 col-sm-12 col-lg-3 d-flex flex-column justify-content-end pt-4">
                <label for="" class="form-label">Enter classes start time </label>
                <input value="" type="time" class="form-control" name="startTime" id="startTime" required>
            </div>
            <div class="col-md-6 col-sm-12 col-lg-3 d-flex flex-column justify-content-end pt-4">
                <label for="" class="form-label">Enter classes ending time </label>
                <input value="" type="time" class="form-control" name="endTime" id="endTime" required>
            </div>
        </div>
        <input type="hidden" name="arr" id="arr" value="">
        <div class="row col-lg-3 d-flex justify-content-center">
            <input type="submit" value="build timetable" class="btn btn-outline-light mt-5">
        </div>
    </form>
</body>
</html>

script.js

var arr = [];
var totalHoursVal = document.getElementById("totalHours").value;
arr.push(totalHoursVal);
var classDurationVal = document.getElementById("classDuration").value;
arr.push(classDurationVal);
var startTimeVal = document.getElementById("startTime").value;
arr.push(startTimeVal);
var endTimeVal = document.getElementById("endTime").value;
arr.push(endTimeVal);
console.log(arr)

export function stuff() {
    return arr
};

build-timetable.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Build Timetable</title>
    <link rel="shortcut icon" href="https://www.freeiconspng.com/thumbs/calendar-image-png/calendar-image-png-3.png" type="image/x-icon">
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
    <style>
        *::-webkit-scrollbar {
            display: none;
        }
        body {
            min-height: 100vh;
            max-width: 100vw;
            display: flex;
            flex-direction: column;
            background-color: #212529;
            background-image: url("https://www.transparenttextures.com/patterns/dark-wood.png");
        }
        table {
            border-collapse: collapse;
            width: 100%;
            margin-top: 20px;
        }
        th, td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: center;
        }
        #timetableContainer {
            width: fit-content;
        }
    </style>
    <script type="text/javascript" src="script/script1.js"></script>
</head>
<body class="bg-dark text-light d-flex flex-column align-items-center justify-content-center">
    <h1 style="text-align: center; margin-top: 10px;">Timetable Builder</h1>
    <form action="./Classes" method="post" class="mt-5 d-flex justify-content-center align-items-center flex-column">
        <div class="row">
            <div class="col-md-6 col-sm-12 col-lg-4 d-flex flex-column justify-content-end ps-5 pe-5 pb-5">
                <label for="className" class="form-label">Enter class name</label>
                <input type="text" class="form-control" id="className" required>
            </div>
            <div class="col-md-6 col-sm-12 col-lg-4 d-flex flex-column justify-content-end ps-5 pe-5 pb-5">
                <label for="classroomNum" class="form-label">Enter classroom number</label>
                <input type="text" class="form-control" id="classroomNum" required>
            </div>
            <div class="col-md-6 col-sm-12 col-lg-4 d-flex flex-column justify-content-end ps-5 pe-5 pb-5">
                <label for="classCoord" class="form-label">Enter Class Coordinator Name</label>
                <input type="text" class="form-control" id="classCoord" required>
            </div>
        </div>
        <div id="classes" onload="classes()"></div>
        <div class="container-fluid mt-4 mb-5">
            <div class="row">
                <div class="col-lg-6 col-md-6 col-sm-12">
                    <button type="reset" class="btn btn-outline-danger w-100 mb-3">clear all</button>
                </div>
                <div class="col-lg-6 col-md-6 col-sm-12">
                    <button type="submit" class="btn btn-light w-100">save all and continue</button>
                </div>
            </div>
        </div>
    </form>
</body>
</html>

script1.js

import stuff from './script1.js';

var hours = stuff()[0];
console.log(hours);


var days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]

window.onload = function classes() {
    var classesForm = document.getElementById("classes");
    
    for(var k = 0; k < days.length; k++) {
        var day = document.createElement("h3");
        day.classList.add("mt-5")
        day.classList.add("container-fluid")
        day.innerHTML = days[k];
        classesForm.appendChild(day);
        var div = document.createElement("div");
        for (var i = 0; i < hours; i++) {
            if (i % 3 == 0) {
                div = document.createElement("div");
                div.classList.add("row");
                div.classList.add("container-fluid");
                div.classList.add("w-100");
                div.style.padding = '0';
                div.style.margin = '0';
            }
            var divChild = document.createElement("div");
            divChild.classList.add("col-lg-4");
            divChild.classList.add("col-md-4");
            divChild.classList.add("col-sm-10");

            var label = document.createElement("label");
            label.textContent = "Enter hour " + (i + 1) + " subject:";

            var input = document.createElement("input");
            input.type = "text";
            input.required = true;
            input.name = `${k}-${i}`
            input.classList.add("form-control");
            input.classList.add("mt-2");
            input.classList.add("mb-4");
            
            divChild.appendChild(label);
            divChild.appendChild(input);
            div.appendChild(divChild);

            if ((i + 1) % 3 == 0 || i == hours - 1) {
                classesForm.appendChild(div);
            }
        }
    }
}

Post request not being found, but get and delete are found with Express JS and Vue

I’m following this tutorial to get a basic app setup and everything is working great for me expect the post request and I’m out of ideas.

Tutorial: https://www.youtube.com/watch?v=HkIGAqAP1GY

This is pretty recreatable since there’s the tutorial but I’m hoping I’ve just been looking at it too long and that’s why I can’t see what’s wrong.

Running refreshData() and deleteNote() run perfectly, and the format is the same, so I’m not sure what I’m doing wrong.

Here’s the call in the Network tab

here's the call in the Network tab

Express JS Api

var Express = require("express");
var Mongoclient = require("mongodb").MongoClient;
var cors = require("cors");
var multer= require("multer");


var app = Express();
app.use(cors());

var CONNECTION_STRING=<removing for privacy>;

var DATABASENAME="gifttracker";
var database;

app.listen(5038, () => {
    console.log("app listen");
    Mongoclient.connect(CONNECTION_STRING).then((client) => {
        database = client.db(DATABASENAME);
        console.log('Mongo DB Donnection Successful');
    }).catch((err) => {
        console.log('Error connecting to MongoDB: ', err)
    });
})

app.get('/api/gifttracker/GetNotes', async (req, res) => {
    let collection = await database.collection("todo");
    let results = await collection.find({}).toArray();
    res.send(results).status(200);
});

app.post('/api/gifttracker/AddNotes',multer().none(), async (req, res) => {
    console.log("addnote api", req); //this does NOT get printed
    let collection = await database.collection("todo");
    collection.count({}, function(error, num){
        collection.insertOne({
            id:(num+1).toString(),
            desc:req.body.newNotes
        })
        res.json("Added successfully");
    })
})

app.delete('/api/gifttracker/DeleteNotes', async (req, res) => {
    let collection = await database.collection("todo");
    collection.deleteOne({
        id:req.query.id
    });
    res.json("Deleted Successfully");
})

Vue App UI

<template>
  <div class="hello">
    <h1>To Do</h1>
    <input id="newNote"/>
    <button @click="addNote()">Add</button>
    <p v-for="note in notes" :key="note.id">
      {{ note.desc }}
      <button @click="deleteNote(note.id)">Delete</button>
    </p>  
  </div>
</template>

<script>
import axios from 'axios';
const API_URL="http://localhost:5038/";
export default {
  name: 'HelloWorld',
  props: {
    msg: String
  },
  data() {
    return {
      notes: []
    }
  },
  methods: {
    async refreshData() {
      axios.get(API_URL+'api/gifttracker/GetNotes').then((res) => {
        this.notes = res.data;
      })
    },
    async addNote() {
      var note = document.getElementById("newNote").value;
      console.log("add note", note); //this gets printed
      const formData = new FormData();
      formData.append("newNotes", note);
      console.log("form data", formData); // so does this
      axios.post(API_URL+"api/gifttracker/AddNotes", formData).then((res) => {
        this.refreshData();
        alert(res.data);
      }).catch((err)=> {
        console.log("err",err);
      })
    },
    async deleteNote(id) {
  console.log("delete note", id);
  axios.delete(API_URL+"api/gifttracker/DeleteNotes?id="+id).then((res) => {
    this.refreshData();
    alert(res.data);
  })
},
  },
  mounted() {
    this.refreshData();
  }
}
</script>

How to block pop-up, banner ads and video ads in iframe in Next.js?

I am embedding a video player that has popup banner ads. When looking for ways to block them, I first found sandbox attribute but the site embed site didn’t allow me to use sandbox attribute. Then I came across another solution, which worked perfectly fine with HTML and JS but when I tried doing the same in Next, it didn’t work.

This was the solution that worked. Here is the code:

//JS
window.onload = function() {
  var button = document.getElementsByName("sandbox")[0]
  var iframe = document.getElementsByName("framez")[0] button.addEventListener('click', sndbx, false);

  function sndbx() {
    var nibba = document.getElementById("framez").src;
    if (iframe.sandbox == 'allow-forms allow-pointer-lock allow-same-origin allow-scripts allow-top-    navigation') {
      document.getElementById("framez").removeAttribute("sandbox");
    }
    frames['framez'].location.href = nibba;
    iframe.sandbox = 'allow-forms allow-pointer-lock allow-same-origin allow-scripts allow-top-    navigation';
  }
}
<button name="sandbox">
  SandBox
</button>
<iframe name="framez" id="framez" src="YOUR_SOURCE" allowfullscreen="true">
</iframe>

And this is how I changed to make it work for Next.js:

"use client";
import React,
{
  useRef
}
from 'react';

const IframeComponent = () = >{
  const iframeRef = useRef(null);

  const handleClick = () = >{
    const iframe = iframeRef.current;
    const iframeSrc = iframe.src;

    if (iframe.sandbox === 'allow-forms allow-pointer-lock allow-same-origin allow-scripts allow-top-navigation') {
      iframe.removeAttribute('sandbox');
    }

    iframe.contentWindow.location.href = iframeSrc;
    iframe.sandbox = 'allow-forms allow-pointer-lock allow-same-origin allow-scripts allow-top-navigation';
  };

  return ( < div > <iframe ref = {
    iframeRef
  }
  id = "framez"name = "framez"src = "SOURCE GOES HERE"width = "100%"height = "500px"allowFullScreen allow = "encrypted-media" > </iframe>
      <button onClick={handleClick}>Change Iframe Source</button > </div>
  );
};

export default IframeComponent;

But it doesn’t seem to work, how do I fix it?

Font-size changes in tables

I have a few buttons that make it so the user can change font size. However, when the font size is changed to the biggest size (1.75em) a table on my site gets all messed up. The entire table floats almost all the way to the right side of the screen when 1.75em is used. Is there a way to make it so the table stays in the middle of the screen or that the text inside of the table doesn’t change font size? (The snippet doesn’t work because of localStorage)

const buttons = document.querySelector('.buttons');
const buttonIds = ['fnt-1em', 'fnt-1.25em', 'fnt-1.75em'];

window.onload = function() {
  const fontSize = localStorage.getItem('fontSize');
  if (fontSize) {
    document.getElementById('text').style.fontSize = fontSize;
    addClickedClassToButton(fontSize);
  } else {
    changeFontSize('1em'); 
  }
}

function changeFontSize(size) {
  localStorage.setItem('fontSize', size);
  document.getElementById('text').style.fontSize = size;
  addClickedClassToButton(size);
}

function addClickedClassToButton(size) {
   const current = document.querySelector('.clicked');
   if(current) {
    current.classList.remove('clicked');
   }
   document.getElementById(`fnt-${size}`).classList.add('clicked');
}
@import url('https://fonts.googleapis.com/css?family=Poppins:200,300,400,500,600,700,800,900&display=swap');

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Poppins', sans-serif;
}

:root {
  --primary-color: #fff;
  --secondary-color: #4978ff;
  --text-color: #000;
  --boxHover-color: #000;
  --placeholder-color: #000;
  --hover-a: rgba(255, 255, 255, 1);
  --table-color: #d3d3d3;
}
.dark-theme {
  --primary-color: #1e1e1e;
  --secondary-color: #4978ff;
  --text-color: #fff;
  --boxHover-color: #fff;
  --placeholder-color: rgba(255, 255, 255, 0.5);
  --hover-a: #000;
  --table-color: #323232;
}

.wrapper {
  max-width: min(900px, 100% - 3rem);
  text-align: center;
}

table {
  width: 100%;
  border-collapse: collapse;
  background: var(--table-color);
  padding: 1rem;
}

caption,
th,
td {
  padding: 1em;
  font-size: 1em;
}

caption {
  background: var(--secondary-color);
  color: #fff;
  font-size: 1.5rem;
  font-weight: 700;
}

th {
  background: hsl(0 0% 0% / 0.5);
}

tr:nth-of-type(2n) {
  background: hsl(0 0% 0% / 0.1);
}

h3 {
  font-size: 40px;
  font-weight: 200;
  margin-bottom: 10px;
  color: var(--text-color);
}

.sec h4 {
  font-size: 30px;
  font-weight: 200;
  margin-bottom: 10px;
  color: var(--text-color);
}

.sec ol li {
  margin-left: 150px;
  max-width: 550px;
}
<section class="sec" id="job">
         <div class="content">
           <div class="buttons">
            <span class="btn" id="fnt-1em" onclick="changeFontSize('1em')">A</span>
            <span class="btn" id="fnt-1.25em" onclick="changeFontSize('1.25em')">A</span>
            <span class="btn" id="fnt-1.75em" onclick="changeFontSize('1.75em')">A</span>
           </div>
           <div class="text" id="text">
             <h3 class="jobTitle">Banen in cybersecurity</h3>
             <p class="job">In de cybersecuritysector zijn er talrijke carrièremogelijkheden, variërend van technische functies tot managementrollen. Enkele van de belangrijkste carrièrepaden in cybersecurity zijn:</p>
             <div class="wrapper">
              <table>
                <caption class="caption">
                  Carrièrepaden in cyberbeveiliging
                </caption>

                <tr>
                  <th class="career">Carrièrepaden</th>
                  <th class="purpose">Doel</th>
                  <th class="function">Functietitels</th>
                </tr>

                <tr>
                  <td class="engineering" data-cell="careerpath">Engineering</td>
                  <td class="engineeringPurpose" data-cell="purpose">Creatie, implementatie en onderhoud van beveiligingssystemen voor digitale infrastructuur.</td>
                  <td data-cell="job titles">
                    <ul>
                      <li class="se">Beveiligingsingenieur</li>
                      <li class="ase">Ingenieur applicatiebeveiliging</li>
                      <li class="cse">Cloud-beveiligingsingenieur</li>
                      <li class="nse">Netwerkbeveiligingsingenieur</li>
                    </ul>
                  </td>
                </tr>

                <tr>
                  <td class="test" data-cell="careerpath">Testing</td>
                  <td class="testPurpose" data-cell="purpose">Systeem-, applicatie- en netwerkevaluatie voor potentiële zwakke plekken in de beveiliging.</td>
                  <td data-cell="job titles">
                    <ul>
                      <li class="pt">Penetratietester</li>
                      <li class="va">Kwetsbaarheidsbeoordelaar</li>
                      <li class="sa">Beveiligingsauditor</li>
                    </ul>
                  </td>
                </tr>

                <tr>
                  <td class="analyse" data-cell="careerpath">Analyse</td>
                  <td class="analysePurpose" data-cell="purpose">Onderzoek van gegevens, systemen en patronen om cyberbedreigingen te begrijpen en te beperken.</td>
                  <td data-cell="job titles">
                    <ul>
                      <li class="ca">Cybersecurity-analist</li>
                      <li class="ta">Bedreigingsanalist</li>
                      <li class="abc">Analist Beveiligingscentrum</li>
                      <li class="ia">Inbraakanalist</li>
                    </ul>
                  </td>
                </tr>

                <tr>
                  <td class="response" data-cell="careerpath">Respons</td>
                  <td class="responsePurpose" data-cell="purpose">First responders bij inbreuken op de beveiliging om schade te beperken, bedreigingen uit te roeien en bedrijfsactiviteiten te herstellen.</td>
                  <td data-cell="job titles">
                    <ul>
                      <li class="ir">Incident responder</li>
                      <li class="imc">Incidentmanager cyberbeveiliging</li>
                      <li class="fan">Forensisch analist</li>
                    </ul>
                  </td>
                </tr>

                <tr>
                  <td class="auditing" data-cell="careerpath">Auditing</td>
                  <td class="auditingPurpose" data-cell="purpose">IT-systemen en operationele evaluaties voor naleving van regelgeving en best practices.</td>
                  <td data-cell="job titles">
                    <ul>
                      <li class="csa">Cyberbeveiligingsauditor</li>
                      <li class="ica">IT-compliance auditor</li>
                      <li class="sca">Beoordelaar veiligheidscontrole</li>
                    </ul>
                  </td>
                </tr>

              </table>
            </div>
         </div>
       </section> 

Authentification fallback while re-login when a session expires using React, Nodejs and Mariadb database

this is my first issue I am posting here so please bear with me 😀
I am creating a social app, where currently I am implementing fallback when my database is off. In my Login.jsx component I am fetching my data do the backend like this:

fetch(getApiUrl('/auth/login'), {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(values),
  credentials: 'include',
  })
  .then(res => {
    const jsn = res.json();
    if (res.ok) {
      handleAuthLogin(navigate, revalidate)(jsn);
    } else if (jsn.message) {
     toast.error(<div className='text-lg'>{jsn.message}</div>);
    }
  })
  .catch((err) => {
    console.error(err);
    if (err.message === 'Failed to fetch') {
      navigate('/service-unavailable');
    } else if (err.message === 'Invalid token' || err.message === 'Unauthorized') {
      navigate('/login');
    } else {
      toast.error(<div className='text-lg'>Failed to connect to the server. Please check your connection.</div>);
    }
  });

Then in my backend, I am using JWT to hash the password. Here is just a code snippet from my index.js file:

/**
 * Middleware for handling authentication routes.
 * All routes starting with '/auth' will be handled by the authRouter.
 */
app.use(checkToken);
app.use('/auth', authRouter);
app.use(userRouter);

// Set up the /users endpoint
app.get('/users', async (req, res) => {
    const { name } = req.query.name;

    // Query the database using Prisma
    const users = await prisma.user.findMany({
        where: {
            name: {
                contains: name,
            },
        },
    });

    // Send the result back to the client
    res.json(users);
});

and the checkToken component:

const checkToken = (req, res, next) => {
    const token = req.headers['authorization'];
    console.log('token: ', token);

    if (!token) {
        return res.status(403).send({ message: 'No token provided.' });
    }

    try {
        const decoded = decodeJwt(token);
        req.userId = decoded.id;
        next();
    } catch (error) {
        return res.status(401).send({ message: 'Unauthorized! Session expired.' });
    }
};

as well as the form verification:

const formVerification = (req, res, action) => {
  // Extract the data from the request body
  const data = req.body;
  console.log(data);

  // Validate the data against the schema
  schema
    .validate(data)
    .catch(err => {
      // If validation fails, send a 422 status code and the validation error messages
      res.status(422).json({ status: 422, message: err.errors });
    })
    .then(valid => {
      if (valid) {
        const cred = {
          usr: data.username,
          pwd: data.password
        };

        if (action === "login") {
          // Login handle
          handleLogin(cred, req, res);
        } else if (action === "signup") {
          // Signup handle
          handleSignup(cred, req, res);
        } else {
          throw new Error("Invalid action");
        }
      } else {
        res.status(400).json({ status: 400, message: "Invalid request" });
      }
    });
}

handleLogin component with encoding jwt:

const hashPwd = (pwd) => {
    return createHash("md5").update(pwd).digest("hex");
};

const encodeJwt = ({ id, name }) => {
    return sign({ id, name }, secret, { expiresIn: "1h" });
};

const decodeJwt = (jwt) => {
    try {
        return verify(jwt, secret);
    } catch (e) {
        throw new Error('Failed to decode JWT: ' + e.message);
    }
};
const handleLogin = ({ usr, pwd }, req, res) => {
    console.log('usr: ', usr, 'pwd: ', pwd);
    getUser(usr, (err, user) => {
        if (err) {
            console.error(err);
            return res.status(500).json({ status: 500, message: "Database is offline" });
        }
        console.log('user: ', user);
        if (!user) {
            return res.status(404).json({ status: 404, message: "User not found" });
        } else if (user.credentials.hash !== hashPwd(pwd)) {
            return res.status(401).json({ status: 401, message: "Invalid password" });
        } else {
            return res.status(200).json({ status: 200, jwt: encodeJwt(user), user: { id: user.id, name: user.name } });
        }
    }, true);
};

You may realize now that this is hard to pinpoint where exactly is the error and the code is a little large, so I’ll just link my repo for the whole code: https://github.com/Patri22k/social-app.

Finally, what is the error? On the mount I have an error user.js:29 GET http://localhost:5000/user/@me 401 (Unauthorized). Oh, btw this is user.js file:

// No token stored in local store
const NO_TOKEN_ERR = "no_token";

const UserContext = createContext(null);
const UserProvider = ({ children }) => {
    const [user, setUser] = useState(null);
    const [fetching, setFetching] = useState(false);
    const [error, setError] = useState(null);
    
    // Obtain new data
    const revalidate = () => {
        // Obtain local JWT val
        const jwt = localStorage.getItem("jwt");
        if (!jwt) {
            setError(NO_TOKEN_ERR);
            return;
        }
        const init = {
            method: "GET",
            headers: {
                'Authorization': `Bearer ${jwt}`
            }
        }
        // Fetch that thing
        fetch(getApiUrl("/user/@me"), init) // line 29
            .then(res => res.json())
            .then(({ user }) => setUser(user))
            .catch((e) => setError(e.message))
            .finally(() => setFetching(false))
    }
    // rest of the code
}

and after I pass any value to the form, the token is undefined and I got an error POST http://localhost:5000/auth/login 403 (Forbidden). But on the mount there is a hashed token.
What I want to achieve?
I’d like to have a fallback when my database is off, it will redirect to the /service-unavailable url. That’s it. When it’s on, it should work as any social app with form validation.

Firebase State changing problems, Page does not change its aspect when user is logged in

Basically when the user is logged in I want the homepage to have written my account instead of login/register. I tried my chatpgt since I’m a beginner but it is not working. I would really appreciate a help. I have no idea how to solve it.

<script src="https://www.gstatic.com/firebasejs/10.10.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/10.10.0/firebase-auth.js"></script>
<script>
import { initializeApp } from "https://www.gstatic.com/firebasejs/10.10.0/firebase-app.js";
import { getAnalytics } from "https://www.gstatic.com/firebasejs/10.10.0/firebase-analytics.js";
import { getAuth, onAuthStateChanged} from "https://www.gstatic.com/firebasejs/10.10.0/firebase-auth.js";
  // Your web app's Firebase configuration
  const firebaseConfig = {
    I have removed my keys here
  };
  
  // Initialize Firebase
  const app = firebase.initializeApp(firebaseConfig);
  const auth = firebase.auth();

  // Listen for auth state changes
    onAuthStateChanged(auth, user => {
    if (user) {
      // User is signed in, show "My Account" link
      document.querySelector('.navigation').innerHTML = `
        <a href="chat" class="nav-link">Chat</a>
        <a href="account" class="nav-link">My Account</a>
      `;
    } else {
      // No user is signed in, show "Login / Register" link
      document.querySelector('.navigation').innerHTML = `
        <a href="chat" class="nav-link">Chat</a>
        <a href="auth" class="nav-link">Login / Register</a>
      `;
    }
  });
</script>

Here is the nav bar in the html:

<header>
        <div class="header-container">
            <div class="logo-container">
                <h1 class="site-title">Athena</h1>
            </div>
            <nav class="navigation">
                <a href="chat" class="nav-link">Chat</a>
                <a href="auth" class="nav-link">Login / Register</a>
            </nav>
        </div>
    </header>

Does anyone makes minecraft scripts/hacks? I think it’s simple

I would need a Script/Hack(idk) that collect chests whithout i neet to target it, it would be like “kill aura for the chest”, there is a thing called envoy in minecraft that spawn some chests in random locations, I’m looking for someone that could make this script/hack, where I could just fly over the chest and collect it.

I thought to use nuker with just chests selected but the anti-cheats catch it instantly.