Cypress: How to log a dropdown item while searching a value in it

I have the following code which suppose the find a dropdown option:

Cypress.Commands.add('searchInDropDown', (searchedElement, containText, dropDownElement, eqValue = 0) => {
    // Use the recurse function to navigate through the dropdown menu
    recurse(
        // The action to perform on each iteration
        () => cy.contains(searchedElement, containText).should(() => { }),
        // The condition to continue recursion
        ($option) => $option.length > 0,
        // Options for the recurse function
        {
            limit: 100,
            log: false,
            timeout: 15000,
            delay: 1000,

            // The post function to execute after each successful iteration
            post() {
                // Simulate pressing the down arrow key on the dropdown menu
                cy.get(dropDownElement).eq(eqValue).type('{downarrow}', { force: true })
            }
        }
        // Force-click the selected option after the recursion is done
    ).click({ force: true })
})

For some reason it does not find it although I am sure it does contain it.

How can I log the current option value while searching for my value?

I tried this but got: Error
The function passed to cypress-recurse did not return a chainable instance. Did you forget the “return” command?

recurse(
        // The action to perform on each iteration
        ($option) => {
            if ($option) {
                cy.log(`Comparing with: ${$option.text()}`);
                cy.contains(searchedElement, containText).should(() => { });
            }
        },...

how to send an iq using satanza.js in react?

I’m trying to send this stanza:

<iq to="bmp-develop.phoenix.mahsan.net" type="get" id="lkbxdjn">
  <query xmlns="urn:xmpp:staff:0" type="all" />
</iq>

I used the sendIQ method but it sends an empty iq stanza:

<iq to="bmp-develop.phoenix.mahsan.net" type="get" id="lkbxdjn"/>

What should i do? I tried this code:

client.sendIQ({
    to: "bmp-develop.phoenix.mahsan.net",
    type: "get",
    id: "lkbxdjn",
    children: [`<query xmlns="urn:xmpp:staff:0" type="all" />`]
  })
  .then((res) => console.log(res))
  .catch((er) => console.log(er));

Use custom hook every time an item in added in context

In React I have a context that stores a list of files being uploaded. I can add files to it, update the upload status and remove files. The Context doesn’t have any logic, it just keeps the data.

I have a custom hook that when used handles the upload logic of a single file, it uses other custom hooks inside it. This custom hook updates the context with the progress.

We have a popup component that handles the upload, the user can select the file to upload and it uses the custom hook for each file.

Now we want to be able to continue uploading and show a toast when the upload finishes. But when the user navigates to another page the popup component along with the custom hook are destroyed so it won’t update the context and we don’t know when the upload finishes.

Is it possible to add a file to context and the context itself use the custom hook for each file in the context?

cannot click or write into textarea

This is my javascript

function edit(btn) {
div = document.getElementById(`div${btn.dataset.id}`)
post = document.getElementById(`post${btn.dataset.id}`)
post.remove()
let text_area = document.createElement('texarea')
text_area.textContent = post.textContent
text_area.setAttribute('rows','4')
text_area.setAttribute('name','contents')
text_area.setAttribute('columns','5')
div.append(text_area)
console.log(div)

}

I can see the contents of the textarea but cannot edit it. My html and css are simple so I think the problem is with javascript

make framer motion fade in & out based on scroll position

im just trying to get some text to fade in and out based on the scroll position

i am using framer motion

here is my code:


    const ref = useRef(null)
    const { scrollYProgress } = useScroll({
        target: ref,
        offset: ["start end", "end end"],
    })
    const opacity = useTransform(
        scrollYProgress,
        [0, 0.5, 1],
        [0, 1, 0],
    )

// ...

        <div ref={ref} className="flex flex-col items-center justify-center border border-blue-600 text-7xl h-screen">
            <motion.div
                style={{
                    opacity: opacity,
                }}
            >
                hello
            </motion.div>
        </div>

i want it so when the scroll position is centered on the div (scrollYProgress == 0.5) then the opacity is 100%, and scrolling up or down from that point fades it out progressively based on scrollYProgress

the text is only fading out when scrolling top to bottom, not fading in & out as desired

Set width of div to match the longest child (not yet appended)

I have a div and I append various values to it.
The div is centered and the children are aligned to the left.
When I add any children that are longer than the ones existing the div bops and expands.
I want to avoid this behavior by setting the width to fit the largest child in advance.

Any ideas?

function appendChildToDiv(stringToAppend) {
  const originalDiv = document.getElementById(`original`);
  originalDiv.innerHTML += `<div id='rest'>${stringToAppend}</div>`;
}
<div style='text-align: center;'>
  <div style='display: inline-block; text-align: left;' id='original'>
    <br> this is the first child
    <br> this is the second child
  </div>
</div>

<button onclick="appendChildToDiv('I am the longest child of them all');">
  Append long child
</button>

Failed authentication using JWT and Express.js

I am currently working on the authentication part of a web app. I use a MongoDB instance that runs in a docker container. The server-side web app uses Node.js and Express.js. Here I show how a user logs in:

app.post("/api/auth/signin", async (req, res) => {
  const username = req.body.username;
  const password = req.body.password;

  const userRequested = await db.collection("users").findOne({username:username});

  if (userRequested == null) {
    res.status(401).json({
      message: "Requested user does not exist",
    });
    res.json(username);
  } else if (username == null || password == null) {
    res.status(401).json({
      message: "Null username or password are not allowed",
    });
  } else {
    if (userRequested.password === password) {

      jwt.sign({ user: userRequested }, "secret", (err, token) => {
        res.redirect("/api/budget/whoami");
      });
    } else {
      res.status(401).send({
        message: "Wrong credentials",
      });
    }
  }
});

As you can see, when the user inserts the correct credentials, I redirect to /api/budget/whoami.

The API handles the request as follows:

app.get("/api/budget/whoami", (req, res, next) => {
    //res.json(req.headers["authorization"]);
    const bearerHeader = req.headers["authorization"];

    if (typeof bearerHeader !== "undefined") {
      const bearerToken = bearerHeader.split(" ")[1];
      req.token = bearerToken;
      next();
    } else {
      res.sendStatus(403);
      res.json(req.headers["authorization"])
    }
  },
  (req, res) => {
    jwt.verify(req.token, "secretkey", (err, authData) => {
      if (err) {
        res.sendStatus(403);
      } else {
        res.status(201);
        res.json({ authData });
      }
    });
  }
);

I used a simple form to try this out:

<html>
    <head>
        <title>Ajax</title>
        <script src="assets/js/app.js" defer></script>
        <link rel="stylesheet" href="assets/css/style.css"/>
    </head>
    <body>
        <form id="loginForm" action="/api/auth/signin" method="post">
            <label for="username">Username:</label>
            <input type="text" name="username" id="username" />
            <label for="password">Password:</label>
            <input type="password" name="password" id="password" />
            <input type="submit" value="login" />
        </form>
    </body>
</html>

However, even if I use the correct credentials, the response after the redirection is 403 Forbidden. For the moment, I want the redirection page to send a JSON document with the user information. I do not understand the error, I would kindly appreciate an explanation in simple terms.

Thank you in advance for your patience.

assign value to the object without specifying key in Javascript [duplicate]

In this React Todo List app tutorial https://www.youtube.com/watch?v=Rh3tobg7hEo on minute 26:30, there is a function called toggleTodo which takes id and the e.target.checked as an argument and it updates the state of “todos” (one React useStage object) by map and returning { …todo, completed} object.

const [todos, setTodos] = useState()

function toggleTodo(id, completed) {
 setTodos(currentTodos => {
  return currentTodos.map(todo => {
    if (todo.id === id) {
      return { ...todo, completed }
    }
    return todo
  })
})}

  return (
<>
  <h1 className="header">Todo List</h1>
  <TodoList todos={todos} toggleTodo={toggleTodo} deleteTodo={deleteTodo} />
</>

)

and on the TodoList.jsx:

export function TodoItem({ completed, id, title, toggleTodo, deleteTodo }) {

return (
<li>
  <label>
    <input
      type="checkbox"
      checked={completed}
      onChange={e => toggleTodo(id, e.target.checked)}
    />
    {title}
  </label>
  <button onClick={() => deleteTodo(id)} className="btn btn-danger">
    Delete
  </button>
</li> )}

the full code can be found here: https://github.com/WebDevSimplified/react-todo-list

my question is why the update function is not returning { …todo, completed: completed} ? isn’t the e.target.checked return only true or false, then when we set the object property we need to specify the key, not just passing true or false, this should be invalid { …todo, completed} isn’t it? how come the completed variable which is a boolean value being added into the object without specifying a key? Am I missing something?

How to update the UI when updating the component using another sibling component in aurelia

In navbar class I’m trying to call TodoList class addTodoToList method to add todos but the todos are appending in the items array of Todo Class but not showing on UI in form of list. If i harcode the items in todo class they appear in list. I’m unable to understand the issue.

Navbar Class

import {autoinject, bindable} from 'aurelia-framework';
import {Router} from 'aurelia-router';
import { TodoList } from 'components/TodoList/todo-list';

@autoinject
export class navbar {
    // Binding it with the newItem of the action-area class to access it
    @bindable public newItem: string;
    // items: string[];

    constructor(private router: Router, private todos: TodoList) {
        // this.items = [];
    }

    // Basic logout functionality
    logout(): void {
        console.log('logout clicked');
        this.router.navigate("");
    }

    // Adds todo to the todo-list
    addTodo(): void {
        const todoText = this.newItem; 
        if(todoText === undefined || todoText === '') {
            alert("Please enter the valid Todo");
        } else {
            // this.items.push(todoText);
            this.todos.addTodoToList(todoText);
            this.newItem = '';
        }
    }


    deleteTodo() {}

    updateTodo() {}
}

todo-list.ts Class

import {autoinject, BindingEngine} from 'aurelia-framework';

@autoinject
export class TodoList {
    items: string[];

    constructor() {
        this.items = [];
    }

    addTodoToList(todoText: string): void {
        this.items.push(todoText);
        console.log(this.items)
    }
}

todo-list.html

<template>
    <ul>
        <li repeat.for="item of items">
           ${item}
        </li>
    </ul>
</template>

Three.js MeshPhongMaterial is no longer “shiny” after a texture is applied (codepen)

If you look at the following codepen, you’ll see a white, shiny “cup” which is a .glb that been loaded in using Three’s GLTFLoader:

https://codepen.io/snakeo/pen/XWOoGPL

screenshot

However, when I apply a texture on a portion of the mug the shiny cup turns into a dull and spotty cup:

dull

You can apply the texture on the Codepen by uncommenting line 102:

// Create MeshPhongMaterial with the texture
const phongMaterial = new THREE.MeshPhongMaterial({
   color: 0xFFFFFF,       // White color for the ceramic look
   shininess: 30,         // Adjust shininess for the ceramic effect
   specular: 0x222222,    // Specular color
   // map: texture           // Apply the texture
});

The image only appears on the “face” of the cup.

I’m not sure why this transformation occurs. I’m kind of new to this and hoping for some guidance.

Thank you.

I’ve tried changing texture.wrapS, texture.wrapT and texture.repeat with strange results, none of which cause the cup to be white and shiny again.

How to loop through an object’s keys and access information from each seperately [duplicate]

Each product key is nested with more objects. I can’t seem to get an idea of how to get information from each product seperately.

The code below shows what i’m trying to do. I know that it doesn’t work because .productList[i] returns a string. I’m trying to make it so that it returns a valid object that lets me log the value of pricePerUnit.

function getProductBuyPrice(){

  const data = JSON.parse(UrlFetchApp.fetch("https://api.hypixel.net/v2/skyblock/bazaar").getContentText());

  productList = Object.keys(data.products)

    for(let i in data.products)
    {
      console.log(data.products.productList[i].buy_summary.pricePerUnit)
    }
}

getProductBuyPrice()

JSON format of the data

INK_SACK:3 and CORRUPT_BAIT are just two products, theres 1000+

nested result from http request become undefined [closed]

I tried both fetch and axios for http request. it was fine when i inspect and go to network tab, the response that i got from server was fine. But when i console the response, part of it’s value become undefined instead of the value that i got from server.

this is my function:

export const getAllRolesData = async () => {
  try {
    const accessToken = await getAccessToken()
    const responseGetAllRolesData = await fetch(
      `${SERVER_URI}/roles/get/all/permissions`,
       {
         method: "GET",
         headers: {
           "Content-Type": "application/json",
           Authorization: `Bearer ${accessToken}`,
         },
       }
     )
    const rolesData = await responseGetAllRolesData.json()

    if (!rolesData?.success) {
      throw new Error(rolesData?.message)
    }

    console.log("FROM API: ", { rolesData })

    return rolesData.data
  } catch (error) {
    console.error(error)
    return null
  }
}

on network tab i check the response like this:

...others
  {
    "id": 5,
    "name": "client_admin",
    "alias": "Client Admin",
    "permission": [
      {
        "roles_name": "client_admin",
        "features_module_name": "account",
        "features_alias": "Upload and remove business photo",
        "features_features": "["update:clients"]",
        "permissionid": 15,
        "rolesid": 5
      },
      {
        "roles_name": "client_admin",
        "features_module_name": "account",
        "features_alias": "Edit account details",
        "features_features": "["read:clients","edit:clients"]",
        "permissionid": 16,
        "rolesid": 5
      },
      {
        "roles_name": "client_admin",
        "features_module_name": "account",
        "features_alias": "Edit team member role",
        "features_features": "["update:users"]",
        "permissionid": 17,
        "rolesid": 5
      },
      {
        "roles_name": "client_admin",
        "features_module_name": "account",
        "features_alias": "Add, edit, remove team members",
        "features_features": "["create:users","update:users","delete:users","read:users"]",
        "permissionid": 18,
        "rolesid": 5
      }
    ]
  },
...others

But when i console the response from responseGetAllRolesData.json() i get this:

...others
{
    "id": 5,
    "name": "client_admin",
    "alias": "Client Admin",
    "permission": [
        undefined,
        undefined,
        undefined,
        undefined
    ]
},
...others

i was expecting get console same with network response

...others
  {
    "id": 5,
    "name": "client_admin",
    "alias": "Client Admin",
    "permission": [
      {
        "roles_name": "client_admin",
        "features_module_name": "account",
        "features_alias": "Upload and remove business photo",
        "features_features": "["update:clients"]",
        "permissionid": 15,
        "rolesid": 5
      },
      {
        "roles_name": "client_admin",
        "features_module_name": "account",
        "features_alias": "Edit account details",
        "features_features": "["read:clients","edit:clients"]",
        "permissionid": 16,
        "rolesid": 5
      },
      {
        "roles_name": "client_admin",
        "features_module_name": "account",
        "features_alias": "Edit team member role",
        "features_features": "["update:users"]",
        "permissionid": 17,
        "rolesid": 5
      },
      {
        "roles_name": "client_admin",
        "features_module_name": "account",
        "features_alias": "Add, edit, remove team members",
        "features_features": "["create:users","update:users","delete:users","read:users"]",
        "permissionid": 18,
        "rolesid": 5
      }
    ]
  },
...others

Is console is object?

esteemed developers! I have a query regarding JavaScript. In the context of JavaScript programming, I understand that ‘console’ is often utilized for debugging and displaying information. Is the ‘console’ considered an object in JavaScript? Furthermore, as ‘log’ is a method frequently used within ‘console’ for outputting messages, does ‘log’ have to be contained within the ‘console’ object? I’m seeking clarification to better understand the structure and usage of these elements within the JavaScript environment

Add one milliseconds to the tick

I have a tick data as 638315425210000000 and 638338147200000000 need to add/subtract one milliseconds from it ,and for the same I’m using the below specified code lines

let ticksInMilliseconds = 10000
//to add milliseconds to tick
const startTick = 638315425210000000
const millisecondsAdded = startTick +  ticksInMilliseconds 
//to reduce one millisecond
const endTick = 638338147200000000
const millisecondReduced = endTick + ticksInMilliseconds

for millisecondsAdded i get tick value as (638315425210010000) and for millisecondReduced get tick value as 638338147199990000

when converted to date online to check if the milliseconds value are added/reduced the millisecondReduced gave correct value ,but the millisecondsAdded it still shows the same time with no milliseconds added 2023-09-29​T00:02:01.000Z would like to understand why add is not adding millisecond to the tick and what should be the solution for the same

for conversion online used https://tickstodatetime.azurewebsites.net/

How can I set up a conditions-based auto-scrolling scheme?

i have these two auto-scrolling components:

ScrollToTop

import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';

export default function ScrollToTop() {
  const { pathname } = useLocation();

  useEffect(() => {
    document.documentElement.scrollTo({
      top: 0,
      left: 0,
      behavior: 'instant', // Optional
    });
  }, [pathname]);

  return null;
}

ScrollToAnchor

import { useEffect, useRef } from 'react';
import { useLocation } from 'react-router-dom';

function ScrollToAnchor() {
  const location = useLocation();
  const lastHash = useRef('');

  // listen to location change using useEffect with location as dependency
  // https://jasonwatmore.com/react-router-v6-listen-to-location-route-change-without-history-listen
  useEffect(() => {
    if (location.hash) {
      lastHash.current = location.hash.slice(1); // safe hash for further use after navigation
    }

    if (
      lastHash.current &&
      document.getElementById(lastHash.current)
    ) {
      setTimeout(() => {
        document
          .getElementById(lastHash.current)
          ?.scrollIntoView({ behavior: 'smooth', block: 'start' });
        lastHash.current = '';
      }, 100);
    }
  }, [location]);

  return null;
}

export default ScrollToAnchor;

they are being used inside my index.js as follows:

createRoot(document.getElementById('root')).render(
    <Provider store={store}>
        <BrowserRouter>
            <ScrollToTop />
            <ScrollToAnchor />
            <App />
        </BrowserRouter>
    </Provider>
);

the results have been rather unpredictable… Is there a way to set up proper conditional auto-scrolling scheme, instead of relying on order between components?