Webassembly runs much slowly than pure JavaScript function

im newly in webassembly. i just try it by writing a fuction to filter the array of objects base on some criterias and return an array of id. i run this function in and measure execution time. Surprisingly, Webassembly run slowly 10 times than JS.

My filter JS functon:

function filter(array: Obj[], criteria: Filter, additionalArr: number[]){
//Filter....
}

C++ file like this:

#include<emscripten/bind.h>
#include<emscripten/val.h>

struct Filter {
  vector<int> f1;
  vector<int> f2;
  vector<string> f3;

  Filter(): f1({}), f2({}), f3({}) {}

  Filter(vector<int> f1, vector<int> f2, vector<string> f3) : 
   f1(f1), f2(f2), f3(f3) {}
};

struct Obj {
  int p1;
  int p2;
  string p3;

  Obj (): p1(0), p2(0), p3("") {}

  Obj (int p1, int p2, string p3) : 
   p1(p1), p2(p2), f3(p3) {}
}

Obj processObj(emscripten::val jsObj){
  Obj wasmObj = new Obj();
  wasmObj.p1 = jsObj["p1"].as<int>();
  wasmObj.p2 = jsObj["p2"].as<int>();
  wasmObj.p3 = jsObj["p3"].as<string>();
  
  return wasmObj;
}

Filter processFilter(emscripten::val jsFilter){
 //Similar to processObj
}

bool filterOneObj(Obj obj, Filter criterias, vector<int> additionalArr) {
 //Filter one obj base on criterias and additionalArr
}

emscripten::val wasmFilter(emscripten::val objJS, emscripten::val criteriaJS, emscripten:: val additionalArrJS) {
   vector<int> result;
   Filter wasmFilter = processFilter(criteriaJS);
   for(size_t i = 0; i < objJS["length"].as<size_t>(); i++) {
      if(filterOneObj()) result.push_back(objJS[i]["p1"].as<int>());
   }
   return val::array(result);
}

EMSCRIPTEN_BINDINGS(module) {
  class_<Filter>("WasmFilter")
    .constructor<vector<int>,
                vector<int>,
                vector<string>>
   .property("f1", &Filter::f1)
   .property("f2", &Filter::f2)
   .property("f3", &Filter::f3)

  class_<Obj>("WasmObj")...//similar to Filter

  emscripten::register_vector<int>("IntList");

  emscripten::register_vector<Obj>("ObjList");

  emscripten::function("wasmFilter", &wasmFilter);
}

Compile C++ to wasm using this command:

emcc -lembind -Iinclude -s WASM= -s EXPORT_ES6=1 -s MODULARIZE=1 -s ENVIRONMENT=web filter.cpp -o filter.js

I run this function with large array (100.000) and the result is JS execution time about 1s and call wasmFilter from JS about 10s.
I don’t know which part in c++ file make wasm run much slowly. Is it because of using embind???

I read many articles that show Webassembly is faster than Js.
I also know that in some cases Webassembly is not effecient. But in my case, Webassembly runs much slowly.
Why? And is there any efective way to passing object and array between JS and C++??

Javascript encryption and decryption problem

<script>
let room_id = 0;
let username = "{{ username }}";
let friend_username = "{{ friend_username }}"; // Automatically join chat with this friend
const key = 'secret key 123'; // Define the key globally
const socket = io(); // Initialize the socket

// Function to handle sending messages
function send() {
    let message = document.getElementById("message").value;
    document.getElementById("message").value = ''; // Clear the input after sending
    const encryptedMessage = CryptoJS.AES.encrypt(message, key).toString();
    console.log("Sending encrypted:", encryptedMessage); // Debugging log
    socket.emit("send", username, encryptedMessage, room_id);
}

document.addEventListener("DOMContentLoaded", () => {
    if (friend_username) {
        join_room();
    }
});

function join_room() {
    socket.emit("join", username, friend_username, (res) => {
        if (typeof res !== "number") {
            alert(res); // Show error if joining failed
            return;
        }
        room_id = res; // Set the room ID
        document.getElementById("input_box").style.display = 'block'; // Show message input box
    });
}

function leave() {
    socket.emit("leave", username, room_id);
    window.location.href = "/friend_list";
}

socket.on("incoming", (encryptedMsg) => {
    console.log("Received encrypted:", encryptedMsg);
    let messageBox = document.getElementById("message_box");
    let messageElement = document.createElement("p");
    var bytes = CryptoJS.AES.decrypt(encryptedMsg, key);
    var decryptedMsg =  bytes.toString(CryptoJS.enc.Utf8);
    messageElement.textContent = decryptedMsg.toString();
    console.log("Received decrypted:", encryptedMsg);
    messageBox.appendChild(messageElement);
    messageBox.scrollTop = messageBox.scrollHeight; // Scroll to the bottom
});

this is my JS code which handles chat box and messages between users. What I’m trying to do here is after sending the messages, I encrypt using AES Encryption Algo, but I can’t decrypt the message. Here is the output I got from the console:Picture for console output

Huge thanks for the help!!

Remove scroll-bar when SVG exceeds containing element

Problem
Solution

I want to remove the scrollbar from SVG scaling. I Want my SVG path to flow over and under my text lines, and I want the SVG to be big enough to cover the width of my text properly that’s why I am using scale property. And if I am using overflow then my SVG gets out of place.

SVG STYLE ::

.svg-container{
    margin-top: 45rem;
    z-index: -999;
    /* overflow-y:hidden; */
    }
svg{
    overflow: hidden;
    width: 100%;
    scale: 2;
    margin-left: 240px;
    background-size: cover;
}

SVG CODE ::

<div class="svg-container">
            <svg width="800" height="800" viewBox="0 0 800 800">
                <path id="curvePath" d="M -50,120 Q 90,-60 190,110 Q 310,260 390,110  Q 480,-90 700,130" fill="transparent" stroke="yellow" stroke-width="20px"/>
                <text width="500" dy="5px">
                    <textPath href="#curvePath">
                        Lorem ipsum, dolor sit amet consectetur adipisicing elit. Saepe cum sit ipsam placeat consequatur nulla deleniti, tempore sapiente velit! Nam repellendus vel delectus exercitationem dolor tempore illum, sapiente vero porro.
                        <animate id="anim1" attributeName="startOffset"
               from="0" to="600"
               begin="0s;anim2.end" dur="5s"
               repeatCount="1"
             />
             <animate id="anim2" attributeName="startOffset"
                from="600" to ="0"
                begin="anim1.end" dur="5s"
                repeatCount="1"
             />
                    </textPath>
                </text>
            </svg>
        </div>
        <div class="hero-title-container">
            <div class="hero-title-first">I<i class="hero-title-first-n">n</i>novation</div>
            <div class="hero-title-second">& expertise</div>
        </div>

How to deal with time intervals availabilities in different timezones with Javascript?

I’m trying to create an application where a teacher can enter his time availabilities. He can input them in the following way:

TimeZone: Please select a timezone

Monday:
9-17
AND
18-20

Tuesday:
2-3
And
10-15

etc…

What I want to do is that when a student wants to book a teacher at a specific day and time, he can see the time in his current timezone. So for exemple, the teacher may have entered his time in the America/Toronto Timezone, but if the student is in Japan, he will see all the times in his current timezone, so with a +11 difference.

The issue I’m currently having is that I’m not sure how to render the times when a time interval overlaps two days… Let’s say the teacher is available from 9-17 on a monday in toronto. This means that in Japan, the time Interval will become 20 to 23:59 on monday but also 00:00 to 04:00 on a tuesday.

How do I deal with this situation with Javascript? I’m currently storing the times in the teacher timezone with the name of the timezone and the index of the day of the week. I feel like the conversion should only be done after the data is fetched but I’m not sure how…

An application that already does the same thing is calendly.com if you need a visual exemple of my situation.

I tried the following method:

  • Fetch the data from the database where Day Index of the selected day = Day index in my database
  • Create an array of time slots using the time intervals
  • Each time slots become associated to a date after being stored in an array
  • Convert each time slots in the student timezone.

The issue is if I only fetch data for the current day index, I can miss timeslots from the day before and day after.

Cannot read properties of null (reading ‘id’) in React js

I am building simpel movie project and i use react router with Link component but when i need to route to “actor/:id” i get this error “Cannot read properties of null (reading ‘id’)”

MovieDetails.jsx

const { id} = useParams();
useEffect(() => {
  if (id) {
    fetch(`https://api.themoviedb.org/3/movie/${id}?api_key=${apiKey}`)
      .then((res) => res.json())
      .then((data) => {
        setMovieDetails(data);
        fetchProvider();
        getCredits();
        getTrailer();
      })
      .catch((error) => console.log(error));
  }
}, [id]);
 <Link to={`/person/${actor.id}`}>
                  <div className="flex-none w-64 h-[500px] bg-[#1F51FF] rounded-2xl shadow-md overflow-hidden text-white ml-5">
                    <img src={getActorImage(actor)} alt={actor.name} />
                    <div className="p-4">
                      <h5 className="text-lg font-bold">{actor.name}</h5>
                      <h1>{actor.character}</h1>
                    </div>
                  </div>
                </Link>

Actors.jsx have also id useParams

App.jsx where all routes goes

export default function App() {
  return (
    <>
      <Router>
        <Routes>
          <Route path="/" element={<Menu />} />
          <Route path="/movie/:id" element={<MovieDetails />} />
          <Route path="/person/:id" element={<Actors />} />
          <Route path="/genre/:id/:name" element={<Genre />} />
          <Route path="/tv/:id" element={<TvDetails/>} />
          <Route path="/credits/:id" element={<Credits />} />
        </Routes>
      </Router>
    </>
  )
}

Updating innerHTML

So, I’m just learning JS and trying to write a basic game using HTML/JS. I can’t figure out how to update the score text.

I have a variable, “score”, and a

tag with the class “scoretext”. I made a button, and I want to have it add 1 to the score when it is pressed. I have an onclick that says “score += 1” but I am unsure to to get the scoretext to update with the new score when the button is pressed.

How to use map function in react JS? I cannot run the loop using map function for looping a component code. How can I run it? [duplicate]

App.js specific code:

<Container>
        <Row>
          {blog.map((v, i) => (
            <ProductItems key={i} blog={v}/>
          ))}
        </Row>
      </Container>

function ProductItems() {
  return (
    <Col lg="3" md="6">
      <Card >
        <Card.Img variant="top" src="placeholder.js/100px180" />
        <Card.Body>
          <Card.Title>Card Title</Card.Title>
          <Card.Text>
            Some quick example text to build on the card title and make up the bulk of the card's content.
          </Card.Text>
          <Button variant="primary">Go somewhere</Button>
        </Card.Body>
      </Card>
    </Col>
  );
}

blog.jsx code:

export let blog = [
    {
      "blog": [
        {
          "userId": 1,
          "id": 1,
          "title": "are or do repels provide blacked out to accept the option criticizes",
          "body": "because and acceptsnaccepts the result of refusal convenient and when which is allnof our things, but they are the thing that will happen to the architect"
        },
        {
          "userId": 1,
          "id": 2,
          "title": "who is to be",
          "body": "is of things at the time of lifenthey are nothing to follow let the pain of the blessed rebuke those pains and not run away from the caresses of the pleasure, nor any trouble"
        },
        {
          "userId": 1,
          "id": 3,
          "title": "who is to be",
          "body": "is of things at the time of lifenthey are nothing to follow let the pain of the blessed rebuke those pains and not run away from the caresses of the pleasure, nor any trouble"
        },
        {
          "userId": 1,
          "id": 4,
          "title": "who is to be",
          "body": "is of things at the time of lifenthey are nothing to follow let the pain of the blessed rebuke those pains and not run away from the caresses of the pleasure, nor any trouble"
        },
        {
          "userId": 1,
          "id": 5,
          "title": "who is to be",
          "body": "is of things at the time of lifenthey are nothing to follow let the pain of the blessed rebuke those pains and not run away from the caresses of the pleasure, nor any trouble"
        },
        {
          "userId": 1,
          "id": 6,
          "title": "who is to be",
          "body": "is of things at the time of lifenthey are nothing to follow let the pain of the blessed rebuke those pains and not run away from the caresses of the pleasure, nor any trouble"
        }
      ]
    }
  ]

{Description: The blog.jsx contains json code and the objects I am trying to looping through map fuction. The App.js file contains the ProductItems component and function and the map function.}

I tried to repeat the ProductItems code because it has the card code. And were expecting this result that did not happened.

How to use a variable in regex while checking for anything thats not a number or the variable [duplicate]

I have this JavaScript code:

let separator = '.';
let fee = '10.00';
let regex = new RegExp(/^[^a-zA-Z]*.[^a-zA-Z]*$/);

console.log( regex.test( fee ) );

I want this to return false if the fee contains anything that isn’t a number and/or doesn’t contain the . separator.

  1. How can I make the regex use the string from the separator variable, rather than hardcoding it directly in the regex like I have currently
  2. How can I alter this regex to check for anything thats not a number and the separator, e.g. !@£$%^, currently it only does a-zA-Z

Please help me correct the create account php code integrated with mysql database – help please

Unable to register new user on the register.php page

website: http://nasax.xyz

Please help me fix the code for this files, it is a website created on php, mysql, javascript, html, css, bootstrap, and flexbox.

Registering a new user is not working correctly, please help me fix this issue

I would also love to add the function to send the password to the users email address automatically

error message: “A system error occurred. Please try again later.”

I’ve posted here all the code of each file:

register_user.php file code:

<?php
error_reporting(-1); 
ini_set('display_errors', 'On');
ini_set('display_startup_errors', 'On');

session_start();
require_once 'db.php';

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $errors = []; // Initialize errors array

    // Input Sanitization and Validation
    $email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Invalid email format.";
    }

    $username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING); 
    if (!filter_var($username, FILTER_SANITIZE_STRING)) { 
        $errors[] = "Invalid username format.";
    }

    $password = $_POST['password'];

    // Password Strength Validation
    if (strlen($password) < 8) {
        $errors[] = "Password must be at least 8 characters long.";
    }
    // ... (Rest of your password validation checks)

    function emailExists($email) {
        global $pdo; // Access the $pdo database connection object
    
        try {
            $sql = "SELECT id FROM users WHERE email = :email";
            $stmt = $pdo->prepare($sql);
            $stmt->execute(['email' => $email]);
    
            // Return true if a user with the email is found, false otherwise
            return $stmt->fetchColumn() > 0;
    
        } catch (PDOException $e) {
            error_log("emailExists Error: " . $e->getMessage());
            return false; // Handle database errors gracefully
        }
    }

    function usernameExists($username) {
        global $pdo;
    
        try {
            $sql = "SELECT id FROM users WHERE username = :username";
            $stmt = $pdo->prepare($sql);
            $stmt->execute(['username' => $username]);
    
            return $stmt->fetchColumn() > 0;
    
        } catch (PDOException $e) {
            error_log("usernameExists Error: " . $e->getMessage());
            return false;
        }
    }

    // Check for Existing Email and Username
    if (emailExists($email)) {
        $errors[] = "Email already registered.";
    }
    if (usernameExists($username)) {
        $errors[] = "Username already exists. Please choose a different one.";
    }

    // Registration Logic (If no errors)
    if (empty($errors)) {
        $hashedPassword = password_hash($password, PASSWORD_DEFAULT);

        try {
            $sql = "INSERT INTO users (email, password, username, created_at) VALUES (?, ?, ?, NOW())";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$email, $hashedPassword, $username]); 

            // Success Handling
            $_SESSION['success'] = "User registered successfully. Please log in.";
            header('Location: login.php'); 
            exit();

        } catch (PDOException $e) {
            error_log("Error during user insertion: " . $e->getMessage());
            $errors[] = "A system error occurred. Please try again later."; // User-friendly message
        }
    }

    // If errors exist, store in session and redirect
    if (!empty($errors)) {
        $_SESSION['error'] = $errors; 
        header('Location: register.php');
        exit();
    }
}

register.php code:

this is register.php file code

<?php 

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();

if (isset($_SESSION['error'])): ?>
    <ul class="errors">
        <?php foreach ($_SESSION['error'] as $error): ?>
            <li><?php echo $error; ?></li>
        <?php endforeach; ?>
    </ul>
    <?php unset($_SESSION['error']); ?> 
<?php endif; ?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Register - NASA-X Info Portal</title>
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.4/css/all.css">
    <!-- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous"> -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <link rel="stylesheet" href="css/styles.css"> <!-- Make sure this path is correct -->
<style>

        .btn-primary {
            background-color: #007bff; /* Bootstrap primary button color */
        }

        .parent-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
}
    </style>
</head>
<body class="d-flex flex-column h-100">

<!-- NAVBAR SECTION -->

<nav class="navbar navbar-expand-lg navbar-dark bg-dark sticky-top">
    <div class="container">
        <a class="navbar-brand" href="index.php">
            <img src="images/nasa.png" alt="NASA Logo" style="height: 30px;">
            <img src="images/spacex.png" alt="SpaceX Logo" style="height: 30px;">
            <img src="images/nasax_logo.png" alt="NASA-X Logo" style="height: 30px;">
        </a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarNav">
            <ul class="navbar-nav ml-auto">
                <li class="nav-item">
                    <a class="nav-link" href="index.php"><i class="fas fa-home"></i> Home</a>
                </li>
                
                <?php if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true): ?>
                <!-- User Dashboard Link -->
                <li class="nav-item">
                    <a class="nav-link" href="dashboard.php"><i class="fas fa-user-circle"></i> Dashboard</a>
                </li>
                    <li class="nav-item">
                        <a class="nav-link" href="logout.php"><i class="fas fa-sign-out-alt"></i> Logout</a>
                    </li>
                <?php else: ?>
                    <li class="nav-item">
                        <a class="nav-link" href="login.php"><i class="fas fa-sign-in-alt"></i> Login</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="register.php"><i class="fas fa-user-plus"></i> Register</a>
                    </li>
                <?php endif; ?>
                <li class="nav-item">
                    <a class="nav-link" href="contact.php"><i class="fas fa-envelope"></i> Contact</a>
                </li>
            </ul>
        </div>
    </div>
</nav>

<!-- END OF NAVBAR SECTION -->


<!-- Page Content -->
<div id="page-content" class="register parent-container">
    <form class="register-form" action="register_user.php" method="post">
        <h2 class="mt-5 text-center">Register</h2>
        <div class="form-group">
            <label>Username</label>
            <input type="text" id="username" name="username" required class="form-control">
        </div>
        <div class="form-group">
            <label>Email</label>
            <input type="email" id="email" name="email" required class="form-control">
        </div>
        <div class="form-group">
            <label>Password</label>
            <input type="password" id="password" name="password" required class="form-control">
        </div>
        <div class="text-center">
            <button type="submit" class="btn btn-primary">Register</button>
        </div>
    </form>
</div>



<!-- Bootstrap JS, Popper.js, and jQuery -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<!-- <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-BBtl+eGJRgqQAUMxJ7pMwbEyER4l1g+O15P+16Ep7Q9Q+zqX6gSbd85u4mG4QzX+" crossorigin="anonymous"></script> -->
<!-- <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script> -->
 <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script> 
</body>
</html>

and here is working login_user.php file code:

<?php
ini_set('display_errors', 1); 
ini_set('display_startup_errors', 1);
error_reporting(E_ALL); 

session_start(); 
require_once('db.php');

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
    $password = $_POST['password'];

    $stmt = $pdo->prepare("SELECT id, email, password_hash FROM users WHERE email = ?");
    $stmt->execute([$email]);

    if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        if (password_verify($password, $row['password_hash'])) {
            // Successful login
            $_SESSION['user_email'] = $row['email']; 
            $_SESSION['loggedin'] = true;
            // Set other relevant session variables if needed
            header("Location: dashboard.php"); // Or another appropriate page
            exit();
        } else {
            // Incorrect password
            $_SESSION['login_error'] = "Incorrect email or password.";
            header('Location: login.php'); 
            exit();
        }
    } else { 
        // Email not found
        $_SESSION['login_error'] = "Incorrect email or password."; // Same message for security
        header('Location: login.php'); 
        exit();
    }
} else {
    // Not a POST request
    header('Location: login.php');
    exit();
}
?>

login.php code:

<?php 
// 1. Database Connection with Error Handling
require_once 'db.php';
// ...

// 2. Session Start
session_start();

/*
// 3. Authentication 
if (isset($_SESSION['user_email'])) {
    header("Location: dashboard.php"); 
    exit; 
}
*/

// Check for 'login_required' error (only if NOT already logged in)
if (!$userLoggedIn && isset($_GET['error']) && $_GET['error'] === 'login_required') {
    echo '<div class="alert alert-warning">You must be logged in to access this page.</div>';
}


// ... (Rest of your login form)

// Display other login errors (if existing)
if (isset($_SESSION['login_error'])) {
    echo '<div class="alert alert-danger" role="alert">' . 
         htmlspecialchars($_SESSION['login_error']) . 
         '</div>'; 
    unset($_SESSION['login_error']);
}

?>




<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Login - NASA-X Info Portal</title>
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.4/css/all.css">
    <!-- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous"> -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <link rel="stylesheet" href="css/styles.css"> <!-- Make sure this path is correct -->
<style>

        .btn-primary {
            background-color: #007bff; /* Bootstrap primary button color */
        }

        .parent-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
}
    </style>
</head>
<body class="d-flex flex-column h-100">

<!-- Navbar -->
<!-- Navigation Bar -->

<nav class="navbar navbar-expand-lg navbar-dark bg-dark sticky-top">
    <div class="container">
        <a class="navbar-brand" href="index.php">
            <img src="images/nasa.png" alt="NASA Logo" style="height: 30px;">
            <img src="images/spacex.png" alt="SpaceX Logo" style="height: 30px;">
            <img src="images/nasax_logo.png" alt="NASA-X Logo" style="height: 30px;">
        </a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarNav">
            <ul class="navbar-nav ml-auto">
                <li class="nav-item">
                    <a class="nav-link" href="index.php"><i class="fas fa-home"></i> Home</a>
                </li>
                <!-- User Dashboard Link -->
                <li class="nav-item">
                    <a class="nav-link" href="dashboard.php"><i class="fas fa-user-circle"></i> Dashboard</a>
                </li>
                <?php if ($userLoggedIn): ?>
                    <li class="nav-item">
                        <a class="nav-link" href="logout.php"><i class="fas fa-sign-out-alt"></i> Logout</a>
                    </li>
                <?php else: ?>
                    <li class="nav-item">
                        <a class="nav-link" href="login.php"><i class="fas fa-sign-in-alt"></i> Login</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="register.php"><i class="fas fa-user-plus"></i> Register</a>
                    </li>
                <?php endif; ?>
                <li class="nav-item">
                    <a class="nav-link" href="contact.php"><i class="fas fa-envelope"></i> Contact</a>
                </li>
            </ul>
        </div>
    </div>
</nav>


<!-- Page Content -->
<div id="page-content" class="login parent-container">
    <form class="login-form" action="login_user.php" method="post">
        <h2 class="mt-5 text-center">Login</h2>
        <?php if (isset($error)): ?>
        <div class="alert alert-danger" role="alert">
            <?= htmlspecialchars($error) ?>
        </div>
        <?php endif; ?>
        <div class="form-group">
            <label>Email</label>
            <input type="email" name="email" class="form-control <?= isset($email_err) && !empty($email_err) ? 'is-invalid' : ''; ?>" required>
            <span class="invalid-feedback"><?= $email_err ?? ''; ?></span>
        </div>
        <div class="form-group">
            <label>Password</label>
            <input type="password" name="password" class="form-control <?= isset($password_err) && !empty($password_err) ? 'is-invalid' : ''; ?>" required>
            <span class="invalid-feedback"><?= $password_err ?? ''; ?></span>
        </div>
        <div class="text-center">
            <button type="submit" class="btn btn-primary">Login</button>
        </div>
    </form>
</div>




<!-- Bootstrap JS, Popper.js, and jQuery -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<!-- <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-BBtl+eGJRgqQAUMxJ7pMwbEyER4l1g+O15P+16Ep7Q9Q+zqX6gSbd85u4mG4QzX+" crossorigin="anonymous"></script> -->
<!-- <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script> -->
 <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script> 
</body>
</html>

Daisy UI chat-bubble

Im having a Chat-start & chat-end issue where the chat-bubble all from the senderId and recieverId both messages appear on chat-start only from daisy UI

I tried to make the authenticated user which is “fromMe” in the code to have a chat-end “chatClassName”
and the “profilePic” to be the one of the AuthUser….So this code is only making the authUser and the selectedUser both chat on the Chat-start…..I dont know what to do please help`

yourimport { useAuthContext } from "../../context/AuthContext";
import useConversation from "../../zustand/useConversation";

const Message = ({ message }) => {
    const { authUser } = useAuthContext();
    const { selectedConversation } = useConversation();
    const fromMe = message.senderId === authUser._id;
    const chatClassName = fromMe ? "chat-end" : "chat-start";
    const profilePic = fromMe ? authUser.profilePic : selectedConversation?.profilePic;
    const bubbleBgColor = fromMe ? "bg-blue-500" : "";


    return (
        <div className={`chat  ${chatClassName}`}>
            <div className='chat-image avatar'>
                <div className='w-10 rounded-full'>
                    <img alt='Tailwind CSS chat bubble component' src={profilePic} />
                </div>
            </div>
            <div className={`chat-bubble text-white ${bubbleBgColor} `}>{message.message}</div>
            <div className='chat-footer opacity-50 text-xs flex gap-1 items-center'>12:30</div>
        </div>
    );
};
export default Message; text

Redirecting to different routes according to user type

This is my express code, I’m handling authentication by passport.js and passport-local-mongoose, I’ve been having trouble redirecting different user type to their dashboard

var express = require("express");
var router = express.Router();
const userModel = require("./users");
const passport = require("passport");
const localStrategy = require("passport-local").Strategy;
const session = require("express-session");

passport.use(new localStrategy(userModel.authenticate()));
/* GET home page. */

router.get("/", function (req, res, next) {
  res.render("intro");
});

router.get("/aboutus", (req, res) => {
  res.render("aboutus");
});

router.get("/auth", (req, res) => {
  res.render("login");
});

const checkUserType = (req, res, next) => {
  const userType = req.user;
  console.log(userType);
  if (req.isAuthenticated() && userType === "doctor") {
    const obj1 = {
      successRedirect: "/doctorProfile",
      failureRedirect: "/auth",
      failureMessage: true,
    };
    return obj1;
  } else {
    const obj2 = {
      successRedirect: "/patientProfile",
      failureRedirect: "/auth",
      failureMessage: true,
    };
    return obj2;
  }
};

router.get("/doctorProfile", isLoggedIn, (req, res) => {
  res.render("doctor");
});

router.get("/patientProfile", isLoggedIn, (req, res) => {
  res.render("patientProfile");
});

router.post("/register", (req, res) => {
  var userData = new userModel({
    name: req.body.name,
    username: req.body.username,
    email: req.body.email,
    user_type: req.body.user_type,
  });
  userModel.register(userData, req.body.password).then(() => {
    console.log("You have registered");
    res.redirect("/auth");
  });
});

function isLoggedIn(req, res, next) {
  if (req.isAuthenticated()) {
    return next();
  }
  res.redirect("/auth");
}

router.post(
  "/signin",
  passport.authenticate("local", checkUserType),
  (req, res) => {}
);

module.exports = router;

I’m passing the checkUserType middleware to passport.authenticate. The error I am facing is when I try to console.log(req.user.user_type) it prints undefined. I don’t know what to do?

javascript change option in function call

I have on my discord bot with discord.js v14 this npm installed: discord-tts.
If i run that function all is fine but i like to change the language from “en” to “de-DE”.

Here is the function from the file:

function getVoiceStream(text, {lang = 'en', slow = false, host = 'https://translate.google.com', timeout = 10000, splitPunct} = {}) {
    const stream = new Stream.PassThrough();
    downloadFromInfoCallback(stream, text, {lang, slow, host, timeout, splitPunct });
    return stream;
}

And thats my call:

const stream=discordTTS.getVoiceStream(newState.member.displayName.split('[')[1].split(']')[1] + ' gekommen');

I expect to: Set the parameter lang: to “de-DE”.
I tried follow command:

const stream=discordTTS.getVoiceStream(newState.member.displayName.split('[')[1].split(']')[1] + ' gegangen', lang="de-DE");

Why is timer yielding same integer regardless of time?

I am writing a simple web app where a random time interval is generated and then the user clicks the button when they guess that much time has passed and then the app shows the margin of error. For some reason it is not calculating the elapses time at all, it’s just showing the user as correct every time. I think it’s a logic flow or math issue.

I tried using Microsoft AI copilot to debug the logic, it did not properly understand the logic.

Below is my code;


<html>
    <head> 
        <style>
            button {
               background-color:maroon;
               border-radius: 25px;
               border: none;
               padding: 20px;
               color: white;
               text-align: center;
               font-size: 50px;
            }
            body {
                font-size: 50px;
            }
        </style>       
        <script type="text/javascript">
           function guessElapsed() {                
            var limitinmiliseconds = 300; // 5 hours;
            console.log("start");
            var previoustime = localStorage.getItem("previoustime");
            const nowseconds = Math.floor(Date.now() / 1000);
            var nowminutes = nowseconds / 60 ;
            var nowhours = nowminutes / 60 ;   
            var duration = nowhours;
            var aim = localStorage.getItem("aim");                             
                if (previoustime && aim) {
                    var elapsed = duration - previoustime ;
                    var marginoferrorminutes = aim - elapsed;
                    var marginoferrorminutes = Number(marginoferrorminutes).toFixed(0); 
                    var variancediv = document.getElementById("variance");
                    console.log("if");
                    variancediv.innerHTML = "Your margin of error is: " + marginoferrorminutes + " minutes.";                  
                    localStorage.removeItem("previoustime", nowhours);
                    var aim = Math.floor(Math.random() * limitinmiliseconds);
                    const nowseconds = Math.floor(Date.now() / 1000) ;
                    var nowminutes = nowseconds / 60 ;
                    var nowhours = nowminutes / 60 ;                    
                    localStorage.setItem("previoustime", nowhours);
                    localStorage.setItem("aim", aim);
                    var truncaim = Number(aim).toFixed(0); 
                    var buttontext = document.getElementById("button");
                    buttontext.innerHTML=" I think " + truncaim + " minutes have passed.";
                    
                }
                else {                    
                   var aim = Math.floor(Math.random() * limitinmiliseconds);
                   const nowseconds = Math.floor(Date.now() / 1000) ;
                   var nowminutes = nowseconds / 60 ;
                   var nowhours = nowminutes / 60 ;                    
                   localStorage.setItem("previoustime", nowhours);
                   localStorage.setItem("aim", aim);
                   var buttontext = document.getElementById("button");
                   console.log("else");
                   var truncaim = Number(aim).toFixed(0); 
                   buttontext.innerHTML=" I think " + truncaim + " minutes have passed.";
                    }               
            }
        </script>
        </head>
        <body>
        <div id="variance"></div>
        <button id="button" onclick="guessElapsed()">Start</button>
        <script type="text/javascript">
            var aim = localStorage.getItem("aim");
            var previoustime = localStorage.getItem("previoustime");
            if (aim) {
                var buttontext = document.getElementById("button");
                var truncaim = Number(aim).toFixed(0); 
                buttontext.innerHTML=" I think " + truncaim + " minutes have passed.";
            }
        </script>
    </body>
</html>


I tried changing how the integer is formatted leaving the part after the decimal point on or off. I am expecting the margin of error to be different from the aimed guess but it’s matching every time despite the time elapsed being different.

Form not getting submitted when i click on register button and the data is also not getting entered into the database

i have a registration form which validates input fields using javascript and gets submitted when all the conditions satisfies. I entered everything in the input fields which satisfy the conditions but when i click on register it is not getting submitted.

i thought there was a mistake in the database connection so i checked it without the php code but still it is not getting submitted. so i’m thinking there is a mistake in the javascript code. but still i have no idea how to make it correct and where have i made the mistake

function hover + function normal

I am currently trying out the code institute 5 day challenge, i have followed/ used the same codes from the course video and can’t seem to find where I am going wrong? multiple error messages after running tests with things like “did you set the font size within the body of preperation hover function etc…the same for the other functions.
please can you write out the correct codings in full, so I can undertand better?

error messages are:
Did you set the ingredients Font Awesome icon font size inside the body of the ingredientsNormal() function?
Did you set the ingredients Font Awesome icon font size inside the body of the ingredientsHover() function?
Did you set the preparation Font Awesome icon font size inside the body of the preparationHover() function?
Did you set the preparation Font Awesome icon font size inside the body of the preparationNormal() function?

My codings are:

<section id="ingredients" onmouseover="ingredientsHover()" onmouseout="ingredientsNormal()">

<section id="preparation" onmouseover="preparationHover()" onmouseout="preparationNormal()">

function ingredientsHover() { document.getElementById("ingredients").firstElementChild.firstElementChild.style.fontSize = "300%"; }

function ingredientsNormal(){ document.getElementById("ingredients").firstElementChild.firstElementChild.style.fontSize = "100%"; }

function preparationHover() { document.getElementById("preparation").firstElementChild.firstElementChild.style.fontSize = "300%"; }

function preparationNormal(){ document.getElementById("preparation").firstElementChild.firstElementChild.style.fontSize = "100%"; }

thanks

i wrote my codings, and hoping someone can write out the correct codings in full, so i can understand better.