Code analysis warning while parsing boolean query param (REST)

export function isLegacyResource(): boolean {
    const queryParams = new URLSearchParams(window.location.search);
    return isQspValueTruthy(queryParams.get('isLegacy'));
}
export function isQspValueTruthy(value: string | null): boolean {
    if (value === null) {
        return false;
    }
    return value === '1' || value.toLowerCase() === 'true';
}
const isLegacy = isLegacyResource();

Semmle raises this warning [SM01513] User-controlled bypass of security check.

This says that I might be comparing the user-input using user controlled data. I feel the query param reading using window.location.search is checked for truthy-ness and this is not contradicting to any security flaw.

Can someone please point out the issue and how I can mitigate this?

Alert not getting triggered JS

i have made a program of a mock Shopping cart and ive recently tried to implement something that should prevent adding more than one instance of the same item inside the cart but the alert i have set up doesn’t seem to trigger when i add the same item again into the cart.

Relevant Html

`

<div class="store-item">
                <span class="product-name">Cpu-1</span>
                <img class="cpu-image" src="Images/Cpu-1.jpg">
                <div class="product-details">
                    <span class="item-price">$229.99</span>
                    <button class="btn btn-primary item-button" role="button">ADD TO CART</button>
                </div>
            </div>
            <div class="store-item">
                <span class="product-name">Cpu-2</span>
                <img class="cpu-image" src="Images/Cpu-2.jpg">
                <div class="product-details">
                    <span class="item-price">$129.99</span>
                    <button class="btn btn-primary item-button" role="button">ADD TO CART</button>
                </div>
            </div>
        </div>
    </section>

    <section class="container text-content">
        <h2 class="section-head">CART</h2>
        <div class="cart-row">
            <span class="cart-item cart-header cart-column">PRODUCT</span>
            <span class="cart-price cart-header cart-column">COST</span>
            <span class="cart-quantity cart-head cart-column">AMOUNT</span>
        </div>
        <div class="cart-items">
            <div class="cart-row">
                <div class="cart-item cart-column">
                <img class="checkout-cpu" src="Images/R9-7950.jpg" width="100" height="100">
                <span class="checkout-item">Ryzen 9-7950X</span>
            </div>
            <span class="cart-column cart-price">$799.99</span>
            <div class="cart-quantity cart-column">
                <form>
                <input class="checkout-input" type="number" value="1" autocomplete="off">
                </form>
                <button class="btn btn-warning" role="button">REMOVE</button>
            </div>
        </div>
        </section>
        <section>
        <div class="cart-total">
            <strong class="cart-sum">SUM</strong>
            <span class="cart-sum-amount">$799.99</span>
        </div>
        <button class="btn btn-primary btn-checkout" role="button">Check Out</button>
        </div>
    </section>

`

Relevant JavaScript

`

var addToCartButtons = document.getElementsByClassName('item-button')
    for (var i = 0; i < addToCartButtons.length; i++) {
        var button = addToCartButtons[i]
        button.addEventListener('click', addToCartClicked)
    }
}

`

`

function addToCartClicked(event) {
    var button = event.target
    var shopItem  = button.parentElement.parentElement
    var cpuName = shopItem.getElementsByClassName('product-name')[0].innerHTML
    var cpuPrice = shopItem.getElementsByClassName('item-price')[0].innerHTML
    var cpuImg = shopItem.getElementsByClassName('cpu-image')[0].src
    addItemToCart(cpuName, cpuPrice, cpuImg)
}

function addItemToCart(cpuName, cpuPrice, cpuImg) {
    var cartRow = document.createElement('div')
    cartRow.classList.add('cart-row')
    var cartItems = document.getElementsByClassName('cart-items')[0]
    var cartItemNames = cartItems.getElementsByClassName('product-name')
    for (var i = 0; i < cartItemNames.length; i++) {
        if (cartItemNames[i].innertext == cpuName) {
            alert('item already in cart')
            return
        }
    }
    var cartRowContents = `
        <div class="cart-item cart-column">
            <img class="checkout-cpu" src="${cpuImg}" width="100" height="100">
            <span class="checkout-item">${cpuName}</span>
        </div>
        <span class="cart-column cart-price">${cpuPrice}</span>
        <div class="cart-quantity cart-column">
            <form>
            <input class="checkout-input" type="number" value="1" autocomplete="off">
            </form>
            <button class="btn btn-warning" role="button">REMOVE</button>
        </div>`
        cartRow.innerHTML = cartRowContents
    cartItems.append(cartRow)
}

`

In React, why can’t I get an object after typed into the browser console?

Supposedly, inside my App component I defined the following object:

let obj = {
      a: 2,
      b: 4,
      c: 6,
    };

If I type “obj” in browser console returns the following message:

Uncaught ReferenceError: obj is not defined
    at <anonymous>:1:1
(anonymous) @ VM297:1 

Source is debbuger:///VM297:1

Note: I have already tested window.obj = obj given in Why I can’t see my objects in chrome console in react?

with similar result:

Uncaught ReferenceError: obj is not defined
    at <anonymous>:1:1
(anonymous) @ VM335:1

What is the core of this subject in ReactJS? How can someone access a given object?

Get the months between two dates JavaScript

Problem

First off, I am going to clarify that this question is not a duplicate of Difference in months between two dates in javascript or javascript month difference

My question is specifically about getting the months in between two dates, not the number of months.

Expected Results

So If date1 is 11/01/2022 (mm/dd/yyyy) and date2 is 02/20/2023, it should output an array of months including the month of date1 and date2 like ["November", "December", "January", "February"]. I need to know how to return the actual months between two dates, not the number of months. Can somebody explain what would be the way to do that?

premature node.js timeout with firebase

I am running a node.js cloud function in firebase and testing locally using the firebase server (functions only)

firebase serve --only functions

I’m having a premature timeout issue that is only effecting me (as opposed to both a colleagues of mine, and also in production on gcloud) – but it’s extremely difficult to build/test on.

At some point it seems to decide the function is now over and timed out at 540s (even if its been just a few seconds)

⚠  functions: Your function timed out after ~540s. To configure this timeout, see
      https://firebase.google.com/docs/functions/manage-functions#set_timeout_and_memory_allocation.
⚠  Your function was killed because it raised an unhandled error.

Then it seems to kill the function and decide to pick up its toys and go home.

The problem is most apparent in loops that have a deliberate “delay” built in to avoid DoS’ing APIs. It’s almost as if when this goes quiet for a few seconds, firebase thinks its finished and terminates the call.

example error

You can see at some point firebase has declared the function over:

**i  functions: Finished "http.app" in 949.993542ms**

I’ve tried all the different ways you can “delay” a node app from cpu cycling to set timeouts… here’s my current function (but the same issue occurs no matter how I delay)

function waitforme(milisec) {
  return new Promise(resolve => {
    setTimeout(() => { resolve('');    }, milisec);
  })
}

Ive tested it on simple loops that have nothing else but the delay in them, and after a few seconds (regardless of how long the delay per loop is) it appears that the function is terminated.

It feels like the server is terminating its connection if it doesn’t hear anyone else on the line – but it’s doing it extremely quickly… despite being run with ample time.

.runWith({
    timeoutSeconds: 540,
    memory: "4GB",
  })

Hopefully someone can help!

Questions about how to move url in JavaScript

I’m using this button in HTML. Below is a description of the button, followed by a description of “functionclick().

<button type="submit" class="btn btn-primary" ONCLICK="functionclick()">확인</button>
<script type="text/javascript">
  function functionclick() {
    let id =  document.getElementById('exampleDropdownFormEmail1').value;
    let password = document.getElementById('exampleDropdownFormPassword1').value;

    if (id == "" || password == "") {
      alert("회원 정보를 입력하세요");
      history.back();
    } else{
      var path= "/tryLogin?id=" + id + "&password=" + password;
      const url = new URL(path);
      window.location.href = url;
    }
  }

</script>
Uncaught TypeError: Failed to construct 'URL': Invalid URL
    at functionclick (login:23:23)
    at HTMLButtonElement.onclick (login:83:81)
functionclick @ login:23
onclick @ login:83

I don’t know much about JavaScript grammar. So I have a lot of difficulties in doing simple things… I need your help.

The result I expected is to send a ‘GET’ request to the server while moving the page to url in “var path”.
But It doesn’t worked and popped up this error where the chrome debugger

Change link color of the current page in css and html

How does one style links for the current page differently from others? I would like to swap the colors of the text and background

HTML code

<div id="navbar-collapse" class="navbar-collapse collapse">
  <ul class="nav navbar-nav navbar-right">

    <li><a href="index.php">Home</a></li>

    <li><a href="about.php">About</a></li>

    <li class="dropdown">
      <a href="#" data-toggle="dropdown" class="dropdown-toggle">Products</a>
      <ul class="dropdown-menu">
        <li><a href="street-light-capsul-model.php">Street light capsule model</a></li>
        <li><a href="street-light-lens-model.php">Street light lens model</a></li>
        <li><a href="flood-light-with-white-reflector-fixture-model.php">Flood light width white reflector fixture model</a></li>
        <li><a href="street-light-lens-fixture-model.php">Street light lens fixture model</a></li>
        <li><a href="flood-lights.php">Flood Light</a></li>
        <li><a href="street-lights.php">Street Light</a></li>
        <li><a href="high-bay-lights.php">High Bay Lights</a></li>
      </ul>
    </li>
    <li><a href="contact.php">Contact</a></li>
  </ul>
</div>

Why does bubbling fire on the document sooner than on parent?

Why does bubbling fire on the document sooner than on parent?

Maybe I am registering events the wrong way?

child.addEventListener("click", () => {
  console.log("Child clicked");
});

parent.addEventListener("click", () => {
  console.log("Parent clicked");
});

document.addEventListener("click", () => {
  console.log("document clicked");
});


// Child clicked
// document clicked
// Parent clicked
<div id="parent" style="background: #ccc; padding: 50px">
  <button id="child">Child</button>
</div>

JQUERY: “this” not working on a each loop [duplicate]

I’m trying to detect every DOM text starting by “..” in the HTML body, then remove the “..” and replace the content. I started with that code:

$("body *:contains('..')").each(function() {
        let vari = $(this).html().slice(2);
        $(this).html(eval(vari));
})

But it only detects if “..” is present anywhere in a string, while I want to detect it at the beginning. So I ended up with this:

$("body *").each(function() {
    if(this.text().substr(0, 2) == "..") {
        let vari = $(this).html().slice(2);
        $(this).html(eval(vari));
    }
})

But it seems like this can’t be used inside a if condition. Is there a jQuery selector like contains but can check the two characters of the content of a DOM, or another way to make the condition? I tried to use the toString() method but I do so the DOM won’t be a DOM anymore and then can’t be modified. Do you guys have ideas on that?

Trying to retrieve element from object in React results in undefined

I’m trying to retrieve the value of “id” from a one-object-long array in React. (The data is coming from Firebase). I have tried every possible combination of code, but it always gives me back undefined (in Firefox). I think it’s a pretty basic question, but I would really really appreciate your help!

So I have this array called “Original Data”, and this is where I want to retrieve the “id” and store it in a variable. Then I tried to convert it into object by slicing to first element of arary (although I’m not sure if that’s needed altogether). And then I’m trying to retrieve the id by calling the Object.id value, but it returns undefined.
I tried doing it with data.id (thinking maybe it’s Firebase data structure), but it also doesn’t work.

MY CODE:
`

    console.log("OriginalData")
    console.log(OriginalData)

    const ConvertingToObject = {... OriginalData.slice(0)}

    const RetrievingID = ConvertingToObject.id
    console.log("Converting to Object")
    console.log(ConvertingToObject) 
    console.log("Retrieving ID")
    console.log(RetrievingID)

`

CONSOLE LOG:

`**OriginalData **

Array [ {…} ]

0: Object { data: {…}, id: “100” }

length: 1

: Array []

Converting to Object

Object { 0: {…} }

0: Object { data: {…}, id: “100” }

: Object { … }

**Retrieving ID **
undefined`

Storing data for storing and display multivalued data in Javascript

So, I am trying to make a form, where user enter there name and email, and after that select the skill and level, a user can enter as many skills and level, as he/she wants. But, I am facing difficulty in how to store that repetitive skills and level in Javascript array and display it.

Here is my HTML-

<section class="contact-form">

<div class="container">
   


  <input type="text" id="name" class="input" placeholder="Enter your name..."/>
  <input type="text" id="email" class="input" placeholder="Enter your email..."/>

  <br>
  <br>
  <label for="inputEmail4" class="form-label">Add Skills</label>
  
  <br>

  <select name="dog-names" id="skills-name" class="dropdown">
    <option value="Java">Java</option>
    <option value="HTML">HTML</option>
    <option value="Bootstrap">Bootstrap</option>
    <option value="JavaScript">JavaScript</option>
    <option value="Python">Python</option>
  </select>

  <select name="dog-names" id="levels" class="dropdown">
    <option value="level1">level1</option>
    <option value="level2">level2</option>
    <option value="level3">level3</option>
    <option value="level4">level4</option>
    <option value="level5">level5</option>
  </select>

  <input type="button" value="Add" id="btnClick" class="Addbtn" onclick="addMore()">    
  <span id="addError"></span>

  <br><br>
  <label for="inputEmail4" class="form-label">Selected Skills</label>
  <ul id="written-box"></ul>
  
  <input type="button" value="Submit" class = "submitBtn" onclick="submit()">
  <br>
  <span id="submitError"></span>

</div>

And now this is my JS code –

    // If any field is blank, then this error will pop-up
function submit(){
    document.getElementById('submitError').innerHTML = "";

    let name = document.getElementById('name').value;
    let email = document.getElementById('email').value;

    if(name == '' || email == ''){
        document.getElementById('submitError').innerHTML = "One or more field is blank! Fill all details";
    }

}

// Function for add skill section
function addMore(){
    document.getElementById('addError').innerHTML = "";

    let skill = document.querySelector('#skills-name').value;
    let level = document.querySelector('#levels').value;

    if(skill == '' || level == ''){
        document.getElementById('addError').innerHTML = "Please Select both Skill & level";
}
else{

    let box = document.getElementById('written-box');

    let li = document.createElement('li');
    li.textContent = skill + " - " + level;

    // Creating 'x' to remove the mistakenly selected skill
    let a = document.createElement('a');
    a.textContent = "delete";
    a.href = "javascript:void(0)";
    a.className = "remove";
    li.appendChild(a);

    let pos = box.firstElementChild;

    if(pos == null)
        box.appendChild(li);
    else
        box.insertBefore(li, pos);

    box.appendChild(li);
}

document.getElementById('skill').value = "";
document.getElementById('level').value = "";
}
let btn = document.querySelector('ul');
btn.addEventListener('click', function(e){
    let box = document.getElementById('written-box');
    let li = e.target.parentNode;
    box.removeChild(li);
});

For more clarity, I have done this-
Till now, I have done this

And want to display this 🙂
Want this

How can I loop through an array of object and get one property element out of the two objects listed inside the array?

I have my array of object bellow.

const Articles = [
    {
        id: 1,
        article1: 1,
        title1:'Trust',
        name1:'Pericles',
        date1:'Dec 2, 2022',
        text1: 'Lorem ipsum dolor sit consectetur. minima in quae dolores quis fugit officia, quia at quam ipsum iste suscipit, eum, veniam eaque voluptas?',
    },
    {
        id: 2,
        article2: 2,
        title2:'Love',
        name2:'Billey',
        date2:'Dec 2, 2022',
        text2: 'minima in quae dolores quis fugit officia, quia at quam ipsum iste suscipit, eum, veniam eaque voluptas?',
    }

]

I have a function and I am trying to select Articles.title1 through mapping

 function  arc(){
   Articles.map((element, index)=>{    
   console.log(element.title1) 
})

I get “Trust” for the title1 and that’s all I needed but, im getting underfined for the other.
Is there a way I can just have just title1? Thank you.

I have also tried for loop,

for(let i = 0; i < Articles.length; i++){
    console.log(Articles[i].title1)
}

and get the same result

Variable not getting defined

One of my event’s variables isn’t getting defined.

The title variable isn’t getting defined so I think I made a mistake.

var addToCartButtons = document.getElementsByClassName('item-button')

for (var i = 0; i < addToCartButtons.length; i++) {
  var button = addToCartButtons[i]
  
  button.addEventListener('click', addToCartClicked)
}

function addToCartClicked(event) {
  var button = event.target
  var shopItem = button.parentElement.parentElement
  var title = storeitem.getElementsByClassName('product-name')[0].innerHTML
  
  console.log('title')
}
<div class="store-item">
  <span class="product-name">CPU 1</span>
  <img class="cpu-image" src="Images/CPU-1.jpg">
  <div class="product-details">
    <span class="item-price">$229.99</span>
    <button class="btn btn-primary item-button" role="button">ADD TO CART</button>
  </div>
</div>

Im trying to upload a file to sanity client with client.assets.upload

I catch this error when ive try to upload to sanity client. Is it the lengthComputable or something else that is the problem and if so how do i fix it?

Caught Error

client.assets
        .upload('file', selectedFile, { contentType: selectedFile.type, filename: selectedFile.name })
        .then((data) => {
          console.log(data)
        })
        .catch((error) => {
          console.log("Upload failed: ", error)
        })

selected File is a vid btw. I am not sure what im doing wrong. Thanks for any help.

Ive tried to use await but the documentation does not say i have to.