Parse cookie and add to HTTP request as custom header

I have this Axios request:

public getData<ResponseEntity = any>(path: string, config?: AxiosRequestConfig) {
  return this.axiosInstance.get<ResponseEntity>(path, {
    headers: {
      'x-b3-traceid': traceId,
      'x-b3-spanid': searchId(),
    },
    ...config,
  });
}

I’d like to make a request where I first parse one of the cookies and send it as a custom header. The below parses the cookie. How do I add it as a header and not overwrite the existing headers that get added?

getCook(cookiename: string) {
    // Get name followed by anything except a semicolon
    var cookiestring = RegExp(cookiename + '=[^;]+').exec(document.cookie);
    // Return everything after the equal sign, or an empty string if the cookie name not found
    return decodeURIComponent(!!cookiestring ? cookiestring.toString().replace(/^[^=]+./, '') : '');
}

getCert(policy: string): Promise<string> {
    // default timeout overridden. set to 3 mins for this call as it can be slow to respond
    const cook = this.getCook('mycookie');
    return ApiService.getData(this.apiUrl + policy + this.certEndpoint).then(
      (response) => response.data
    );
  }

Calculate time it takes to reach a certain game score

we are currently forced for a school project to secure a browser based game. My group choosed the dino game. Our idea was to send the score the client reached and his needed time to the server where we would check if these two values are matching. But how would you calculate the time a Player would need for a certain score?! Is there a formula for that?

Why TextEncoder.encode() produces different result from File.arrayBuffer()?

Here’s the simple code:

document.querySelector('#upload').addEventListener('change', async (e) => {
  const initialFile = e.target.files[0];
  const arrayBuffer = await initialFile.arrayBuffer();

  const text = await initialFile.text();
  var enc = new TextEncoder();
  const arrayBufferFromText = enc.encode(text).buffer

  // WHY THESE TWO AREN'T THE SAME?
  console.log(arrayBuffer.byteLength)
  console.log(arrayBufferFromText.byteLength);
})
<input type="file" id="upload">

When uploading a binary file, e.g. an image, arrayBuffer will be different from arrayBufferFromText. That’s apparently happening somewhere in the text -> buffer conversion using TextEncoder.

Why is this happening and how to get arrayBufferFromText the same as arrayBuffer?

Why does bcrypt.hash takes the wrong value?

In the following function, I have two nested bcrypt functions. The first one checks the value with the current hash password and the second one should write the new hashed value to the database.

However, as soon as bcrypt.hash(pw_frontend is called, the pw_check value is hashed and written to the database. But I want the pw_frontend value to be written in. What is the reason that the value of pw_check is used despite that I pass pw_frontend as parameter?

app.put('/api/profil/update', userMiddleware.isLoggedIn, (req, res) => {
  con.query('SELECT * FROM benutzer WHERE id = ' + req.body.id, function (
    err,
    result,
  ) {
    if (err) throw err

    let pw_check = result[0].password
    let pw_frontend = req.body.old_password

    console.log(pw_check)
    console.log(pw_frontend)
    console.log(req.body.id)

    bcrypt.compare(pw_frontend, pw_check, function (err, result) {
      if (result) {
        console.log('CHECK 1 True')
        // Takes the wrong value, he takes the value from the backend
        bcrypt.hash(pw_frontend, 10, (err, hash) => {
          if (err) {
            return res.status(500).send({
              msg: err,
            })
          } else {
            console.log('HASHVALUE FROM FRONTEND: ')
            console.log(hash)
            // has hashed pw => add to database
            con.query(
              'UPDATE benutzer SET password = ? WHERE id = ' + req.body.id,
              [hash],
              (err, result) => {
                if (err) {
                  throw err
                  return res.status(400).send({
                    msg: err,
                  })
                }
                return res.status(201).send({
                  msg: 'Updated!',
                })
              },
            )
          }
        })
      } else {
        console.log('CHECK 2 False')
        return res.status(201).send({
          msg: 'Passwörter stimmen nicht überein!',
        })
      }
    })
  })
})

File disappears after upload

Requirement:

Add file and Upload.

I have added file on the fixtures folder.

file name = pdf1.pdf

Code:

cy.wait(10000)
    cy.fixture('pdf1.pdf').then(fileContent => {
    cy.get('#Shipment_PaperlessFile').attachFile ({

      fileContent: fileContent.toString(),
      fileName: 'pdf1.pdf',
      mimeType: 'text/pdf'

    })
  })

When I ran the code, the file is added.

image

But after this I have to click on the Create button for the file to get uploaded. But after I click on the submit button (Create), the the file that was added disappears.

set default color button in first rendering

I have 3 button like this, I want set default color when component render first time. Any idea?

enter image description here

<Button onClick={setChartDay}>Day</Button>
<Button onClick={setChartWeekly}>Week</Button>
<Button onClick={setChartMonth}>Month</Button>

My css

  '& button:active': {
      color: styles.color.white,
      backgroundColor: styles.color.darkBlue,
    },
    '& button:focus': {
      color: styles.color.white,
      backgroundColor: styles.color.darkBlue,
    },

React – Input value does not change when an user try to change it

I have an input with a value coming from a state from the redux store.

When an user try to manually update the value of this input, it doesn’t work. Impossible to change it.

The problem occurs when I add the debounce function, the input value doesn’t change anymore.
I mean, when an user enter in the input field and try to change it, it just doesn’t change at all.

If I remove the debounce function then it work just fine (it’s just a little bit slow when an user enter a value in the input but it work).

Any idea?

Input

<input
    id={spectacleLine.id}
    disabled={isNotEditable}
    onChange={handleUpdateQty}
    value={spectacleLine.qteReservee}
    placeholder="Qte"
    className={"form-control form-control-md form-control-solid text-center p-1"}
    type="text"
/>

onChange function

const handleUpdateQty = debounce((event: any) => {
    const idSpl: number = event.target.id;
    const qty: number = parseInt(event.target.value);

    // Check qty
    if (isNaN(qty) || qty < 0) {
        return toast.error("Quantity not valid");
    }

    agent.Spectacle.updateSpectacleLine({
        Id: idSpl,
        QteReservee: qty,
    })
        .then(() => dispatch(updateSpectacleLine({ id, idSpl, qty })))
        .catch((error) => console.log(error));
});

Debounce function

function debounce(cb: any, delay = 2000) {
    let timeout: ReturnType<typeof setTimeout>;

    return (...args: any) => {
        clearTimeout(timeout);
        timeout = setTimeout(() => {
            cb(...args);
        }, delay);
    };
}

Javascript filter return empty array

var data = [1, 2, 3, 5, 2, 1, 4];

// iterate over elements and filter
var res = data.filter(function (v) {
  
    return data.filter(function (v1) {   
    });
});

console.log(res);

In this code i try to use double filter to see what will return to var res. My expectation for var res is empty array and the second filter will also giving me a empty array(which meet my expectation)

but in reality var res return [1,2,3,5,2,1,4], slap my face hard.

In my understanding filter return true or false, if true will return array and element with the value else will return nothing (empty array).Second filter does what i think (return 7 empty array).

So why 7 empty array return back to first filter,first filter is giving me all the element of the array? [1,2,3,5,2,1,4].Because i am not returning true or false value to first filter instead second filter is returning 7 empty array to first filter.

storage.ref is not a function error (react, javascript, firebase v9)

I am trying to upload an image to storage in firebase v9, but I get a following error,

ImageUpload.js:72 Uncaught (in promise) TypeError: storage.ref is not a function at handleUpload (ImageUpload.js:72:1)

I have checked firebase documentation but cannot find a right solution.
Could anybody help?

Here is my code facing errors

const handleUpload = async (event) => {
        event.preventDefault()

        if(image === ''){
            const collectionRef = collection(db, "posts");
            const contents = {
                timestamp: serverTimestamp(),
                caption: caption,
                imageUrl: image,
                noLikes: noLikes,
                username: username
            } 
            await addDoc(collectionRef, contents);
        }
        else{
            const uploadTask = storage.ref(`images/${image.name}`).put(image);
            uploadTask.on(
                "state_changed",
                snapshot => {},
                error => {
                    console.log(error);
                },
                () => {
                    storage
                    .ref("images")
                    .child(image.name)
                    .getDownloadURL()
                    .then(url => {
                        const collectionRef = collection(db, "posts");
                        const contents = {
                            timestamp: serverTimestamp(),
                            caption: caption,
                            imageUrl: url,
                            noLikes: noLikes,
                            username: username
                        } 
                        addDoc(collectionRef, contents);
                    });
                }
            )
        }
        handleClose();
        setCaption("");
        setImage(null);
    };

I want to remove item from local storage key with the function

 function remove(current) {

            let text = "Are You Sure ?";


            if (confirm(text) == true) {
                current.parentElement.parentElement.remove();
                // document.getElementById("tablebody1").deleteRow(element.parentNode.rowIndex);
                text33 = JSON.parse(localStorage.getItem("storex"))

                 function rem(arr,index){
                     return arr.filter(function(ele){
                         return ele !=index
                     })
                 }
                
               localStorage.setItem('text32', JSON.stringify(result));
               
               localStorage.getItem("text32")
            

                
                
            }

//I am trying to delete the items from my localstorage I render the table data on the screen but my table data is coming into the localstorage i want to delete particular item for example:=

if i have localstorage just like that

 {namex: "ANUJ", lnamex: "ANUJ", emailx: "[email protected]"},…]
0: {namex: "ANUJ", lnamex: "ANUJ", emailx: "[email protected]"}
1: {namex: "ANUJ", lnamex: "ANUJ", emailx: "[email protected]"}
2: {namex: "ANUJ", lnamex: "ANUJ", emailx: "[email protected]"}
3: {namex: "ANUJ", lnamex: "ANUJ", emailx: "[email protected]"}
4: {namex: "ANUJ", lnamex: "ANUJ", emailx: "[email protected]"}
5: {namex: "ANUJ", lnamex: "ANUJ", emailx: "[email protected]"}
6: {namex: "rohit", lnamex: "ANUJ", emailx: "[email protected]"}
7: {namex: "shubhum", lnamex: "ANUJ", emailx: "[email protected]"}

let say i want to delete 6: item how can i do so or if i delet it whwn i refresh the page it come again

How to check if word is in english dictionary

Im creating a web app that the user enters a word from a given characters and the app needs to check if the word is in english or not.
So far i used library in python called enchant but there is a lot of words that it returns true and its not accurate enough.
There is any accurate API or library ??
thanks for your help 🙂

How dangerous is it to mutate a Vue prop by the child?

Vue allows to mutate props but it is not recommended. In the docs (https://vuejs.org/guide/components/props.html#one-way-data-flow) I found that

As a best practice, you should avoid such mutations [mutating nested props by the child] unless the parent and child are tightly coupled by design.

This sounds for me that it is not good practice to do so, but it is okay. However, in all forum posts I found, they say rather things like “don’t ever do this!” and that re-rendering of the parent component can even corrupt the data (i.e. Vue 2 – Mutating props vue-warn).

If it was up to me, I would just stick to the recommendation and not argue about this. However, the team I work in uses prop mutation extensively.

So far it works, but I’m afraid that in future there might occur problems. Is there the risk that in future versions Vue could really forbid this? Or that they apply subtle changes that would be compatible only for code that follows the recommendation?