Speed test xmlhttprequest

Good afternoon. Please tell me how can I return the ‘event.
loaded’ which then dispatch it to the state

const startSpeedTestAsync = () => async (dispatch: Dispatch) => {
  const url = config.SPEED_TEST;


dispatch(setLoadTest(true));

const startTime = new Date().getTime();


dispatch(startSpeedTest({ startTime, isShowInfo: false }));



 const endRequest = (data: unknown) => {
    const endTime = new Date().getTime();
    dispatch(setEndTime(endTime));
    dispatch(calcSpeed(data));
    dispatch(stopSpeedTest({ isLoadTest: false, isShowInfo: true }));
  };



const sendHttpRequest = (metod: string, currenUrl: string) => {
    const promise: Promise<unknown> = new Promise((resolve) => {
      const xhr = new XMLHttpRequest();

  xhr.timeout = 5000;

  xhr.onprogress = function (event) {
    console.log('loaded: ', event.loaded);
    return event.loaded;
  };
  xhr.onreadystatechange = function () {
    // Only run if the request is complete
    if (xhr.readyState !== 4) return;
    resolve(xhr.onprogress);

    // resolve(xhr.onprogress);
  };
  xhr.open(metod, currenUrl);
  xhr.send();
});
return promise;

};

  sendHttpRequest('GET', url)
    .then((response: any) => console.log(response))
    .catch(endRequest);
};

I can not understand how to properly process the request that everything turned out. I’m trying to implement a request for xmlhttprequest
and return the size of the downloaded file to then calculate the speed of the Internet connection. The problem is that I don’t know how to return this size.

please i a am having an issue, i am trying to remove some div tags based on login role in php and javascript

it is working but once i reload the page it shows the div tag i removed in less than a sec, i should have used display:none but any user can go to inspect element and change the the display to block

here is my code

<?php
//if ($row['login_type'] == 'Advertiser'){
?>
        <script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
  <script>
     $(document).ready(function() {
     $(window).on("load", function() {
    
    $("#Div1").remove();
    $("#Div2").remove();
    $("#Div3").remove();
  }) 
 });
</script>
<?php }?>

How to prevent content(Tasks) to disappear after REFRESHING

I am trying to make a simple To-Do like application. I want the “Tasks” which I add to remain even after closing the window or at least after refreshing. I tried to achieve that using MongoDB but I couldn’t.
I think a simpler way to achieve this is by using arrays but I am not able to understand how to do that.
Please suggest me some way to achieve the above results….

let div = document.getElementById('tasks');
let add = document.getElementById('add');
let newTask = document.getElementById('newTask');

let c = 0;

add.addEventListener("click", function () {
    let newt = newTask.value;
    newTask.value = null;
    let cbox = document.createElement("input");
    let br = document.createElement("br");
    cbox.type = "checkbox";
    cbox.id = "check";
    let d = document.createElement("div");
    div.append(d);
    d.id = "nd";
    d.append(cbox);
    d.append(newt);
    c += 1;
    if (c === 12) {
        add.disabled = true;
        newTask.value = "Stack Overflow";
    }
});
/* body {
    background-color: #42f5f5
} */

.card {
    margin: 0 auto;
    float: none;
    /* margin-bottom: 10px; */
    /* border: none; */
    /* background-color: rgb(248, 179, 88); */
}

.container {
    margin-top: 2.5rem;
}

#title {
    width: 200px;
    border: none;
    font-size: larger;
    font-weight: bold;
}

#newTask {
    width: 200px;
}

#add {
    margin-top: 1rem;
}

#newTask {
    margin-top: 1rem;
}

#plus {
    font-family: Arial, Helvetica, sans-serif;
    font-size: 15px;
}

#nd {
    font-size: 20px;
    margin-top: 5px;
    margin-bottom: 10px;
}

#check {
    margin-left: 20px;
    height: 15px;
    width: 15px;
    margin-right: 10px;
}
<!doctype html>
<html lang="en">

    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
            integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
        <link href="ToDo.css" rel="stylesheet">
        <title>To-Do</title>
    </head>

    <body>

        <div class="container">
            <div class="card" style="width: 35rem;height: 42rem;">
                <div class="card-body">
                    <p style="font-size: 2rem;font-weight: bold;">
                        <input type="text" class="form-control" id="title" placeholder="Title">
                    </p>
                    <p id="main">
                    <div id="tasks">

                    </div>
                    <form class="form-inline">
                        <div class="form-group mx-sm-3 mb-2">
                            <input type="text" class="form-control" id="newTask" autocomplete="off"
                                placeholder="Enter new task">
                        </div>
                        <button type="button" class="btn btn-primary mb-2" id="add">Add Task</button>
                    </form>
                    </p>
                </div>
            </div>
        </div>

        <script src="ToDo.js"></script>
        <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
            integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
            crossorigin="anonymous"></script>
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"
            integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
            crossorigin="anonymous"></script>
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js"
            integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
            crossorigin="anonymous"></script>
    </body>

</html>

How do I close a prompt upon clicking cancel in JS?

I cannot for the life of me figure out how to close the prompt altogether upon pressing cancel in my code for a guessing game. I’ve tried several things, but each time either the code ignores what I’m trying to do, or ends in an error. Here’s the code in question:

let numGuess = prompt (`Guess the number I am thinking of (between 1 and 10):`);
let num = (4);

let numTries = 1

console.log(numGuess);

numGuess = parseInt(numGuess)

if (prompt == null) {

alert (`Press F5 to play again.`) 


}
if (numGuess === num) {

  alert (`Correct! You guessed the number in 1 try! Press F5 to play again.`);

}

else while ((numGuess !== num) && (numTries <3))

{

  numTries = numTries++

  alert (`Incorrect guess. Try again.`)

}

length property in built-in Object, Number

Why does the built-in Object, Number, have a length property?

var n = Number;
n;
EPSILON: 2.220446049250313e-16
MAX_SAFE_INTEGER: 9007199254740991
MAX_VALUE: 1.7976931348623157e+308
MIN_SAFE_INTEGER: -9007199254740991
MIN_VALUE: 5e-324
NEGATIVE_INFINITY: -Infinity
NaN: NaN
POSITIVE_INFINITY: Infinity
isFinite: ƒ isFinite()
isInteger: ƒ isInteger()
isNaN: ƒ isNaN()
isSafeInteger: ƒ isSafeInteger()
length: 1 // For what??

Error: Cannot POST /includes/signup.inc.php

I’m using Node.js to help build a web app and am trying to create a login form + signup form but when submitting the form i get the following error: Cannot POST /includes/signup.inc.php . I’m new to php and MySQLi and thus are following this tutorial: https://youtu.be/gCo6JqGMi30 and have a db running with phpmyadmin (not too sure whether it could be an issue with accessing that as i never came accross an option to set usernames or passwords for the db). The issue might also be to do with the routing on routes.js. Here’s my code for the affected areas:
dbh.inc.php:

<?php

$serverName="localhost";
$dBUsername="root";
$dBPassword="";
$dBName="revisionflashcards";

$conn = mysqli_connect($serverName, $dBUsername, $dBPassword, $dBName);

if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

signup.inc.php:

<?php

if (isset($_POST["submit"])) {
    echo "It works!";
}
else {
    header("location: ../views/index.ejs");
}

createacc.php:

<!DOCTYPE html>
<head>
    <script src="https://kit.fontawesome.com/855632da8a.js" crossorigin="anonymous"></script>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Poppins&display=swap" rel="stylesheet">
</head>
<style>
    .center {
      margin: auto;
      width: 50%;
      padding: 10px;
    }
    .button {
      border: none;
      color: white;
      padding: 10px 40px;
      text-align: center;
      text-decoration: none;
      display: inline-block;
      font-size: 16px;
      margin: 4px 2px;
      transition-duration: 0.4s;
      cursor: pointer;
    }
    
    .button1 {
      background-color: white;
      color: black;
      border: 2px solid #4da9ff;
    }
    
    .button1:hover {
      border-radius: 10px;  
      background-color: #4da9ff;
      color: white;
    }

</style>
<section class="signup-form">
    <h1>Create Account</h1>
    <form action="../../includes/signup.inc.php" method="post" style="margin: auto; width: 250px;">
        <i class="fa-solid fa-user"></i><input type="text" name="uid" size="25" placeholder="Create A Username"/><br>
        <i class="fa-solid fa-lock"></i><input type="password" name="pwd" size="25" placeholder="Create A Password"/><br>
        <i class="fa-solid fa-lock"></i><input type="password" name="pwdrepeat" size="25" placeholder="Repeat Password"/><br>
        <i class="fa-solid fa-envelope"></i><input type="text" name="email" size="25" placeholder="Your Email"/><br>
        <i class="fa-solid fa-tag"></i><input type="text" name="name" size="25" placeholder="Full Name"/><br>
        <button class="button button1" type="submit" name="submit">Sign Up</button>
    </form>
</section>

routes.js:

var express = require("express");

var router = express.Router();


router.get("/", function(req, res){
    console.log("A1 Cabs!? A1 Cabs!? Testing Testing 123!")
    res.render("index");
});


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

router.get("/login", function(req, res){
    res.render("acc/login");
});

router.get("/createacc", function(req, res){
    res.render("acc/createacc");
});

router.get("/projectpage", function(req, res){
    res.render("projecthub");
});

module.exports = router;

Thank you any help would be appreciated. 🙂

Increase qty by 1 if item already exist in cart – Reactjs/NextJS

I have found many questions similar to the subject, however, I couldn’t understand the logic, as most of these are asked/explained in the PHP/ MySQL community.

I’m building an eCommerce store, where I need to handle cart items. The problem is already mentioned in the subject. Below is a short snippet of my code.

const [cartItems, setCartItems] = useState([]) // initial state of cartItems array
const handleCartUpdate = (id,title, price, qty) => {
  // first checking if  cart is empty or not
  const cartLength = cartItems.legnth >=1 ? true : false
  // Check if item exist with the id as given in parameters
  if(cartLength) {
    const checkItemExist = cartItems.find(item => item.id == id)
    // Now, if item exist, update the propert 'qty' , My approach is as under:
    if (checkItemExist) {
      cartItems.map(product => {
        if(product.id == id) {
          return {product, qty: qty+1
        }
      }
      return product
      setCartItems(...cartItems, product)
    }
  } else {
    setCartItems(...cartItems, {...})
  }
}

After that, I am unable to understand how to update the cartItems

How can I write node.js to profile memory usage properly?

I wanted to test memory usage for objects in node.js. My approach was simple: I first use process.memoryUsage().heapUsed / 1024 / 1024 to get the baseline memory. And I have an array of sizes, i.e. the number of entries in objects const WIDTHS = [100, 500, 1000, 5000, 10000] and I plan to loop through it and create objects of that size and compare the current memory usage with the baseline memory.

function memoryUsed() {
    const mbUsed = process.memoryUsage().heapUsed / 1024 / 1024

    return mbUsed
}

function createObject(size) {
  const obj = {};
  for (let i = 0; i < size; i++) {
    obj[getRandomKey()] = i;
  }

  return obj;
}


const SIZES = [100, 500, 1000, 5000, 10000, 50000, 100000]

const memoryUsage = {}

function fn() {
  SIZES.forEach(size => {
  const before = memoryUsed()
  const obj = makeObject(size)
  const after = memoryUsed()
  const diff = after - before
  memoryUsage[width] = diff
  })
}

console.log(memoryUsage)

but the results didn’t look correct:

{
  '100': 0.58087158203125,
  '500': 0.0586700439453125,
  '1000': 0.15680694580078125,
  '5000': 0.7640304565429688,
  '10000': 0.30365753173828125,
  '50000': 7.4157257080078125,
  '100000': 0.8076553344726562,
}

It doesn’t make sense. Also, since the object memoryUsage that records the memory usage itself takes up more memory as it grows so I think it adds some overhead.

What are some of the more robust and proper ways to benchmark memory usage in node.js?

file JS untracked on React JS

I got this error when creating functional component i got this error:
enter image description here

the error said cannot find dile Buku.js .srccomponentsBukuBuku.Js’. but the JS file what i imported is exist and i’m sure not write wrong directory
enter image description here

How will i take product with same category into a string or an array?

How will i take product with same category into a string or an array?


<ul>
  <li class="product_cat-category-1"></li>
  <li class="product_cat-category-3"></li>
  <li class="product_cat-category-2"></li>
  <li class="product_cat-category-5"></li>
  <li class="product_cat-category-1"></li>
  <li class="product_cat-category-2"></li>
  <li class="product_cat-category-3"></li>
  <li class="product_cat-category-5"></li>
  <li class="product_cat-category-4"></li>
  <li class="product_cat-category-1"></li>
  <li class="product_cat-category-2"></li>
  <li class="product_cat-category-3"></li>
  <li class="product_cat-category-4"></li>
</ul>

what I want exactly is, to filter them and append them into a new div to create a filterable animation using gsap.
this is actually a wordpress woocommerce product page.

last time i created a popup using gsap, and in that i used something called split() function

triggers.each(function(){
    let listClassName = $(this).attr('class').split(' ');
    let revealClassName = String(listClassName[listClassName.indexOf(listClassName.find(element => element === 'dasrgsap__reveal-trigger')) + 1]);
    const sectionReveal = $('.dasrgsap__reveal-content.' + revealClassName);
    const colReveal = $('.dasrgsap__reveal-content.' + revealClassName + ' .et_pb_column');

});


the trigger was (“dasrgsap__reveal-trigger sandra”) and the popup content container was (“dasrgsap__reveal-container sandra”). both were given two separate classs, which made eaiser to split and access them.

but in this case, woocommerce products list items are given too many classes, so the only class i can play with to get a specific category is the “product_cat-‘product-category'”,

I’m want to get a string or array of the same product category,
i’m want to split “product_cat-” and “category-1” and get an array of that category but i’m not able to do it.

is this even possible?

Method to identify max and min values (or swing high / low) from a series

I’m trying to find swings / pivots in a series of data (value over time), and it seems it’s a much harder task than what it initially seemed…

I have only been able to find local max and min values (peaks). After literally seven different attempts (my own code and also adapting code from others) have failed… I don’t seem to understand how to identify a SWING (higher high or lower low).

This is is what I have:

Sample data:

const values = [{"time":1650211200,"value":40471.8},{"time":1650214800,"value":40257.5},{"time":1650218400,"value":40130},{"time":1650222000,"value":40419.9},{"time":1650225600,"value":40420},{"time":1650229200,"value":40252.4},{"time":1650232800,"value":40299.9},{"time":1650236400,"value":39999},{"time":1650240000,"value":39773.3},{"time":1650243600,"value":39800},{"time":1650247200,"value":39800},{"time":1650250800,"value":39838.8},{"time":1650254400,"value":39815.8},{"time":1650258000,"value":38970.6},{"time":1650261600,"value":39063.8},{"time":1650265200,"value":39055.6},{"time":1650268800,"value":39048.3},{"time":1650272400,"value":38986},{"time":1650276000,"value":39105.7},{"time":1650279600,"value":39099.9},{"time":1650283200,"value":39459.6},{"time":1650286800,"value":39562.4},{"time":1650290400,"value":39520.9},{"time":1650294000,"value":39355.3},{"time":1650297600,"value":39609},{"time":1650301200,"value":40378},{"time":1650304800,"value":41030.6},{"time":1650308400,"value":40700},{"time":1650312000,"value":40866.5},{"time":1650315600,"value":41067.9},{"time":1650319200,"value":40972},{"time":1650322800,"value":40950.8},{"time":1650326400,"value":41229.7},{"time":1650330000,"value":40918.9},{"time":1650333600,"value":40759.3},{"time":1650337200,"value":40773.2},{"time":1650340800,"value":40848},{"time":1650344400,"value":40850.4},{"time":1650348000,"value":40803.4},{"time":1650351600,"value":40736.7},{"time":1650355200,"value":40853.9},{"time":1650358800,"value":40759.4},{"time":1650362400,"value":40821.2},{"time":1650366000,"value":40974.8},{"time":1650369600,"value":41079.3},{"time":1650373200,"value":41460.2},{"time":1650376800,"value":41678.5},{"time":1650380400,"value":41730},{"time":1650384000,"value":41533.6},{"time":1650387600,"value":41367.5}]

Code that will detect peaks:

type Point = {
    time: string,
    value: number
}

const peaks: Point[] = [];
enum directionEnum {
    Ascending = 'up',
    Descending = 'down'
}

let direction: directionEnum = directionEnum.Ascending;
let prevVal = values[0];


for (let i=1,len=values.length; i<len; i++) {       
   
    const curVal =  values[i];

    if (prevVal.value < curVal.value) {  // (still) ascending?
        direction = directionEnum.Ascending;
    
    } else if (prevVal.value > curVal.value) { // (still) descending?

        if (direction != directionEnum.Descending) { // starts descending?

            peaks.push(prevVal);

            direction = directionEnum.Descending;
        }
    }

    prevVal = curVal;
}

Graphical example:

Results in a Chart

All the red points are the peaks (highs and lows) identified by my code. Marked in green are the ones I really need to identify, the “pivots” or “swing high and low”.

How should I do this?

Thanks in advance!

How to replace ‘undefined’ with an text message in JavaScript

I made a statement in the options. However, some options that I don’t show in the text statement will appear undefined

Instead of displaying the word undefined, I want to replace it with a text message.

Here’s my code below:

function idenmalaria() {
  var a, b, c, d, text;

  a = document.getElementById("rbc_size").value;
  b = document.getElementById("rbc_dis").value;
  c = document.getElementById("dot").value;
  d = document.getElementById("distribusi").value;
   
  if (a == 1 && b == 1 && c == 1 && d == 1) {
    text = "Plasmodium falciparum";
  } else if (a == 1 && b == 2 && c == 3 && d == 2) {
    text = "Plasmodium malariae";
  } else if (a == 2 && b == 1 && c == 2 && d == 2) {
    text = "Plasmodium vivax";
  } else if (a == 2 && b == 2 && c == 2 && d == 2) {
    text = "Plasmodium ovale";
  }

  document.getElementById("result").value = text;

}

HTML code :

<select id="rbc_size">
    <option value="1">RBC normal</option>
    <option value="2">RBC big</option>
</select>
<select id="rbc_dis">
    <option value="1">RBC distorted</option>
    <option value="2">RBC undistorted</option>
</select>
<select id="dot">
    <option value="1">Maurer dots</option>
    <option value="2">Schüffner dots</option>
    <option value="3">None</option>
</select>
<select id="distribusi">
    <option value="1">Homogeneous</option>
    <option value="2">Heterogeneous</option>
</select>

<button onclick="idenmalaria()" type="submit">Parasit</button>
<input type="text" id="result" />

Any help would be appreciated. Thank you.

What is the difference between Crypto and CryptoJS AES encryption? The results are different. (javascript

The encryption results of the two libraries are different.
Can someone give me some advice?

//Crypto
const enCrypt = (plainText, key, iv) => {
    plainText = Buffer.from(plainText);
    let cipher = Crypto.createCipheriv("AES-128-CBC", key, iv);
    let encrypted = cipher.update(plainText, "", "");
    return Buffer.concat([encrypted, cipher.final()]).toString("base64");
}

//Crypto-js
const encryptAES = (pText, init_key, init_iv) => {
    const key = CryptoJS.enc.Utf8.parse(init_key);
    const iv = CryptoJS.enc.Utf8.parse(init_iv);
    
    const cipherData = CryptoJS.AES.encrypt(pText, key, {
      iv: iv,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7,
    });
    return cipherData.ciphertext;
  }

//crypto-js result
ba0a16dc341853969069249a74649a865403d8887816479f3b4d907eb6f827d96364a6960009a548edae9997037cc5718e8a3655bd7181d017983cba8d8b6e798905a7bd90741569f72bfc8677e8f3e97c0bfeafef1a22aa1c3e3e0711a53cdb54f6ec088b54ed77d08914f33f86f4fdd7dd8afd95894b64d33ff5f50c226e179e35b8a5018615624b992ef6b2b8ab9a8fa08bb6052445b5baa27737fac0896930e260f3c26d129b0bfa66bc381d3e0859f0bf37713af7541ff25651119894ff

//crypto result
ugoW3DQYU5aQaSSadGSahlQD2Ih4FkefO02Qfrb4J9ljZKaWAAmlSO2umZcDfMVxjoo2Vb1xgdAXmDy6jYtueYkFp72QdBVp9yv8hnfo8+l8C/6v7xoiqhw+PgcRpTzbVPbsCItU7XfQiRTzP4b0/dfdiv2ViUtk0z/19QwibheeNbilAYYVYkuZLvayuKuaj6CLtgUkRbW6onc3+sCJaTDiYPPCbRKbC/pmvDgdPghZ8L83cTr3VB/yVlERmJT/

toggle button not functioning

I’m creating a to-do list app for my portfolio and I’d like to add a dark-mode feature for my body/background. however, my toggle button looks fine but the switch doesn’t seem to function and I can’t seem to figure out why anyone sees anything wrong or that may be interfering?

function dark() { // setting up dark-mode 
  var element = document.body;
  element.classList.toggle("dark-mode"); //dark-mode class
}
label {
  margin: 10px;
  cursor: pointer;
  width: 50px;
  height: 30px;
  display: block;
  border-radius: 50px;
  position: relative;
  color: white;
}

.switch {
  position: relative;
  display: inline-block;
  width: 110px;
  height: 10px;
  margin: 0 10px;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: aqua;
  transition: .4s;
  border-radius: 35px;
  ;
}

.switch input {
  display: none
}

.slider::before {
  position: absolute;
  content: "";
  height: 20px;
  width: 20px;
  left: 5px;
  bottom: 5px;
  background-color: white;
  transition: 0.4s;
  border-radius: 50px;
}

input:checked+.slider {
  background-color: blue;
}

input:checked+.slider::before {
  transform: translateX(0px);
}

input:checked+.slider::after {
  transform: translateX(8px);
}
<div class="toggle">
  <label for="switch">
        <input type="checkbox" onclick="dark()" checked>
        <span class="slider"></span>
        </label>
</div>

Create array from table rows with multiple cell data

I’m trying to create a simple array with jquery from a table with only rows, but a row can contain multiple time elements.

I could only find solutions for tables with single td values and no children…

This is my table:

<div id="customhours">
    <table>
      <tbody>
        <tr>
          <td>Tuesday</td>
          <td>
            <time>17:00 - 18:00</time>
          </td>
        </tr>
        <tr>
          <td>Friday</td>
          <td>
            <time>16:00 - 17:00</time>
            <time>17:00 - 18:00</time>
          </td>
        </tr>
      </tbody>
    </table>
</div>

The array I’m looking for is:

[["Tuesday", "17:00 - 18:00"], ["Friday", ["16:00 - 17:00, 17:00 - 18:00"]]]

Any help would be appreciated.