How to get thrown errors in service task implemented with JavaScript SDK in my code?

I have a process definition which whenever my web app client sends a specific request to my server, I start an instance of it. In this process, I have a service task that I have implemented it using javascript SDK. In this service task under some conditions, I throw a BPMN error like this:

export const checkTimePeriod = () => {
 client.subscribe("checkTimePeriod", async function ({ task, taskService }) {
  const requestTime = task.variables.get("requestTime");

  if (requestTime < 20) {
     // complete the task
     await taskService.complete(task);
  } else {
    const errorMessage = "Not in allowed time period";
    await taskService.handleBpmnError(task, errorMessage);
  }
});
};

Now since this is a callback and runs whenever my process reaches this state, how can I get this error in my own code in the upper function? Thanks.

Function can’t get Object from Class

I have a forEach method that has a function(displayBook) where it displays details of a book from an Array created from a Constructor class.

myLibrary.forEach(Book => {
    displayBook(Book)
})

function displayBook (item) {
    let div = document.createElement("div")
    let listName = document.createElement("li")
    let listPages = document.createElement("li")
    let listRead = document.createElement("li")
    let removeButton = document.createElement("button")
    
    document.body.appendChild(div)
    div.className = "bookCard"
    listName.textContent = item.name
    listPages.textContent = item.pages
    listRead.textContent = item.read
    div.appendChild(listName)
    div.appendChild(listPages)
    div.appendChild(listRead)

    div.appendChild(removeButton)
    removeButton.className = "removeButton"
    removeButton.textContent = "Remove Book"
}

I have another function(addBookToLibrary) that asks for new data and add it into the array. Then calls the function(displayBook) to display the new data. This function creates another div as written but it does not get thew item.name, item.pages, and item.read of the new data. It also says

Uncaught TypeError: item is undefined
function addBookToLibrary(item) {
        let bookName = prompt("Enter book name.")
        let pageNumber = prompt("Enter number of pages.")
        let readStatus = prompt("Have you read it?")
        const newBook = new Book(bookName, pageNumber, readStatus)
        myLibrary.push(newBook)
        displayBook(item)
    }

Accessing an javascript object by its index [duplicate]

I try to access this object. I want the value of property “city” from index [0] and save it in a variable. But I just found solutions for other constructions of an object.

var distance_to_each_city = [{
    'distance': [123],
    'city': 'Mannheim'
  },
  {
    'distance': [654],
    'city': 'Berlin'
  },
  {
    'distance': [342],
    'city': 'München'
  },
  {
    'distance': [444],
    'city': 'Hamburg'
  },
  {
    'distance': [442],
    'city': 'Köln'
  }
]

How to sort embed fields in order (Discord.js)

const { writeFileSync, readFileSync } = require('fs');

let json = JSON.parse(readFileSync('./json.json', 'utf-8'));
client.on('message', (message) => {
  if (message.content.startsWith(`${prefix}test`)) {
    if (json[message.guild.id]?.slot >= 17)
      return message.channel.send(`**Lobby 1 IS FULL!, use 1checkin2`);
    let s =
      message.member.roles.cache.find((r) => r.name === 'Tier1') ||
      message.member.roles.cache.find((r) => r.name === 'Tier2');

    let msg = '933343245725999134';
    let channel = message.guild.channels.cache.get('932431084132646942');
    channel.messages.fetch(msg).then((msg) => {
      let embed = msg.embeds[0];
      var arg = message.content.split(' ').slice(1).join(' '); //
      if (!arg) return message.reply('mention first');
      if (!json[message.guild.id]) {
        json[message.guild.id] = { slot: 1 };
      }

      embed.addField(
        `> `SLOT ${json[message.guild.id].slot}:``,
        `${arg}` + `${s}`,
      );
      json[message.guild.id].slot++;
      writeFileSync('./json.json', JSON.stringify(json, null, 2));
      msg.edit(embed);
    });
  }
});

I need to sort them:

so Tier 1 be on top
and Tier 2 be in the bottom
and SLOT number changes with it

how it should look:

I tried using embed.fields.sort but I couldn’t do it

how to retrieve the last unique object in an array

Hey guys is there a way i can retrieve the last unique object in an array
in the code below the id at the first and second index are the same is there a way i can retrieve the last occurrence of the id with the corresponding object

0: {id: 'tra.528555295', name: 'heart'}
1: {id: 'tra.528555295', name: 'heart-outline'}
2: {id: 'tra.528555301', name: 'heart'}
3: {id: 'tra.528555301', name: 'heart-outline'}

Passsing props from App.js to Stack.Screen React Native

I’m again asking a question regarding ReactNative: I have the following App.js:

export default function App() {

  function Tabs() {
    return <TabBar />;
  }

  const styles = StyleSheet.create({
    backButton: {
      color: global.GUI.ORANGE,
    },
  });

  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen
          name="Tabs"
          component={Tabs}
          ..
        />
        <Stack.Screen
          name="Impostazioni"
          component={Settings}
          ...
        />
        <Stack.Screen
          name="Registrati"
          component={Signup}
         ...
        />
        <Stack.Screen
          name="Login"
          component={Login}
          ...
        />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

I want to pass to each component some values declared in App.js,but doing something like:

            <Stack.Screen
              name="Impostazioni"
              component={Settings}
              currentUser={"name":"test"}
            />

Return undefined in:

import React from 'react';
import {View,Text} from 'react-native';

const Settings = (props) => {
  --> console.log(props.currentUser) // here is undefined
  return (
    <View >
     <Text>This is Settings!</Text>
    </View>
  );
};

export default Settings

So, how can I correctly pass props to App.js to all other components?

Thanks

How can I generate line number from css or javascript based on height of container

I have a situation where I have to make something that looks like a code editor and to acheive this I have to use HTML, CSS and Js without any libraries.

I have achieved pretty much everything except the line numbers and I am not sure how to do it.

So far I have achieved this:
enter image description here

and this is what actually is my target:
enter image description here

supposing that I have this html structure:

<html>
    <head>
    </head>
    
    <body>
        <div class="lines"></div>
        <div class="code"></div>
    </body>
</html>

enter image description here

how do I populate lines based on the height of content in code using CSS or JavaScript?

Pure JavaScript – Hide Div on Clicking outside

I want when i click outside the My DIV with the ID Container_ID , all the Container gets hidden through display: none;. The code that i present in JavaScript works to a certain point, because when i click inside any part of the Container_ID it returns the same behavior, the My DIV hides. And it wasn’t supposed when i’m interacting with elements Controls_CLASS + ul,li + Checkbox_CLASS inside the Container_ID itself. They should be excluded from hiding the entire Container_ID when i click on them, because they are inside.

How can I improve this?

JavaScript (font: https://codepen.io/marizawi/pen/YgaaMp)

window.addEventListener('mouseup',function(event){
    var cont = document.getElementById('Container_ID');
    if(event.target != cont && event.target.parentNode != cont){ cont.style.display = 'none';}
});

My DIV

<div class="Container_CLASS" id="Container_ID">
    <div class="Controls_CLASS"><a href="#">Select All</a>|<a href="#">Reset</a></div>
    <ul>
        <li><input type="checkbox" name="cars[]" class="Checkbox_CLASS" value="BMW" />BMW</li>
        <li><input type="checkbox" name="cars[]" class="Checkbox_CLASS" value="Mercedes" />Mercedes</li>
        <li><input type="checkbox" name="cars[]" class="Checkbox_CLASS" value="Volvo" />Volvo</li>
    </ul>
</div>

My DIV – CSS

div.Container_CLASS
{
    width: 50%;
    height: 350px;
    margin-top: 4px;
    margin-left: 4px;
    display: none;
    position: absolute;
    overflow-y: scroll;
}

Uncaught FirebaseError: Firebase: No Firebase App ‘[DEFAULT]’ has been created – call Firebase App.initializeApp() (app/no-app). HTML and Javascript

I have seen many websites (which includes StackOverflow) about the same error with their solutions but none of them have worked for me.

I know that the error means that I’ve run a function using firebase before it was initialized.

Here are the relevant parts of my code:

window.addPerson = addPerson;

        const queryString = window.location.search;
        const urlParams = new URLSearchParams(queryString);
        const userVar = urlParams.get('user')

        const userVarSplitted = userVar.split('#')
        const userVarFormatted = userVarSplitted[0] + ":" + userVarSplitted[1]

        // Import the functions you need from the SDKs you need
        import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.4/firebase-app.js";
        import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.6.4/firebase-analytics.js";
        import { getDatabase, ref, set } from "https://www.gstatic.com/firebasejs/9.1.0/firebase-database.js";
        // TODO: Add SDKs for Firebase products that you want to use
        // https://firebase.google.com/docs/web/setup#available-libraries

        // Your web app's Firebase configuration
        // For Firebase JS SDK v7.20.0 and later, measurementId is optional
        const firebaseConfig = {MY_CONFIG};

        // Initialize Firebase
        const app = initializeApp(firebaseConfig);
        const analytics = getAnalytics(app);
        const db = getDatabase();

        function addPerson() {
            set(ref(db, "verified/" + userVarFormatted), {
                name: userVarSplitted[0],
                discriminator: userVarSplitted[1]
            });

            console.log("added")
        }

PS: The javascript type is set to module

Do you know what’s happening?
Thanks

ReactJS: Argument of type ‘(bullets: never[]) => string[]’ is not assignable to parameter of type ‘SetStateAction’

I am fetching data from API and populating the input texts from the fretched email. I’m using bullet and setBullet to maintain the state. The problem is that I must define an initial item into the use state like this:

const [bullet, setBullet] = useState(['Temp']);

But defining it like this it obviously adds “Temp” as the first input and then all emails follow. But if I define the state like this:

const [bullet, setBullet] = useState([]);

I get errors in onChangeHandler and map function in useEffect.

const onChangeHandler = (index: number, value: string) => {
    setBullet((bullets) =>
      bullets.map((bullet, i) => (i === index ? value : bullet))
    );
  };

  useEffect(() => {
    fetch(
      "https://reqres.in/api/users?page=2")
        .then((res) => res.json())
        .then((json) => {
          json.data.map((data: any) => {
            setBullet((bullets) => [...bullets, data.email]);
            return console.log(data.email);
          })
        })
  }, [])

Error comes in setState function:

Argument of type '(bullets: never[]) => string[]' is not assignable to parameter of type 'SetStateAction<never[]>'.
  Type '(bullets: never[]) => string[]' is not assignable to type '(prevState: never[]) => never[]'.
    Type 'string[]' is not assignable to type 'never[]'.
      Type 'string' is not assignable to type 'never'

To summarise this is what I’m getting. I want to remove the ‘Temp’ bullet from it.

enter image description here

Any help will be much appreciated.

Thank You

Trying to show div(A) hover element on hover of div(B) using html ,css and vanilla js

what I’ve done till now is:
Show the div(A) on hover of div(B) that I have actually done and the real problem I’m getting is when I try to show the nav element of div(A) when it’s shown by hovering on div(B).

So the cycle is like: div(B)>div(A)>nav elements.

I’m attaching only relevant code as it might get to long to attach whole HTML file.

the HTML code is:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Target</title>
    <link rel="stylesheet" href="./style.css"> 
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
   <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=Assistant:wght@200&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.4/css/all.css" integrity="sha384-DyZ88mC6Up2uqS4h/KRgHuoeGwBcD4Ng9SiP4dIRy0EXTlnuz47vAwmeGwVChigm" crossorigin="anonymous">

</head>
<body>
    <header>
        <div class="header-first">
            <div class="header-forvisibility">
                <div class="header-second">
                    <div class="logo">
                        <img src="./images/target-logo.png" alt="Target-australia">
                    </div>
                    <div class="search">
                        <span class="search-icon">
                            <i class="fas fa-search"></i>
                            
                        </span>
                        <input type="text" placeholder="Search products & brands" name="search">
                        <span class="mic-icon">
                            <i class="fas fa-microphone"></i>
                        </span>
                    </div>
                    <div class="setting-icons">
                        <div class="user">
                            <img src="./images/user.svg" alt="user">
                        </div>
                        <div class="heart">
                            <img src="./images/heart.svg" alt="heart">
                        </div>
                        <div class="cart">
                            <img src="./images/shopping-cart.svg" alt="cart">
                        </div>
                    </div>
                </div>
            </div>
            <div class="header-third">
                <div class="header-third-inner">
                    <ul class="nav-ul">
                        <li class="nav-li">Deals & Exclusives
                            
                            <div class="mega-box deals-mega-box">
                             <hr>
                                <div class="content">
                                   
                                    <div class="deals-and-exclusive">
                                        <div class="row-1">
                                            Shop All Deals & Exclusives
                                        </div>
                                        <hr>
                                        <div class="row-2">
                                            <div class="col-1">
                                                <ul class="latest">
                                                    <li class="latest-li">Latest</li>
                                                    <li class="latest-li">Deals</li>
                                                    <li class="latest-li">Online Only</li>
                                                    <li class="latest-li">Clearance</li>

                                                </ul>
                                            </div>
                                            <div class="col-2">
                                                <div class="image-1">
                                                    <img src="./images/nav-col-2-image1.webp" alt="">
                                                </div>
                                                <div class="image-2">
                                                    <img src="./images/nav-col-2-image2.webp" alt="">
                                                </div>

                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </li>
                     </ul>

                     <div class="animation-line start">   
                    </div>
                </div>
            </div>

 </div>
        
    </header>
    <main>
    <div class="update-notification">
        <h3><span class="free-delivery">Free delivery</span> orders over <span class="dollar">$45</span></h3>

    </div>

I’m trying to mock this website navbar, after scrolling a little bit down you can hover and get the div(A) and then you can hover div(A) for nav elements but I’m not able to hover div(A). It just disappears when I move my mouse over div(A) elements.

The reference website is:
https://www.target.com.au/

Mine screenshot:

  1. First view:

enter image description here

  1. When I scroll little bit down it will disappear the div(A):
    enter image description here

  2. Now if I try to hover div(A) it will show div(A) and if I try to hover div(A) it just disappears (instead, should show div(A) nav elements just like in the reference website link):
    enter image description here

How to turn a function into a string without activation/use of any modules in javascript

Apparently this might look at a duplicate.. but let me explain the problem.
For the sake of the question ALL I can assume is that my code will be run, I do not know anything about the modules(if they’re fake or something) and can only trust the things that get set in instances that only my code will control(or originally set that they cannot be configured)

What I want to do is to as my heading says, to convert a function to a string.. however all my attempts at conversion depend on a module that can be overwritten by the client

Function.prototype.toString=()=>"pwned" //work of the client
//failed attempts to convert to string below
console.log(`${Object.keys}`) //"pwned"
console.log(Object.keys+'') //"pwned"
console.log(Object.keys.toLocaleString()) //"pwned"

Starting out with the only assumption I’m making(that my code is being run), I tried this below however it returns undefined(I thought returning nothing would somehow make it the default string)

//infinityLoop is a function I write(all this is inside another self calling function) and the name suggests what it does
//the concept in this example is to run the code and if it smells anything suspicious, infinite loop
try{((href)=>{
var symbol=Symbol.toPrimitive, c=1
var testObj={[symbol]:function(){return c++}}
if(testObj-0!==1 || c!==2){throw "bruh"}
function str(item){
  var measure=null, unit={}, count=0
  function verifier(hint){
    const condition=hint!=="default" || this!==item || verifier.caller!==str || count!==0
    if(condition){infinityLoop()}  else{ measure=unit; count++ }
  }
  item[symbol]=verifier; const string=item+''
  if(measure!==unit || count !==1){throw "bruh"}
  delete item[symbol]; return string
}
str(Object.keys) //"undefined"
//I get to control the conversion but I still can't convert it ;-;
})()}catch{infinityLoop()}

Is it possible to convert a function to string without overwritable modules or is this a ridiculous impossible question?

Javascript function returns Class

What does it mean to return a class in a function, like this:

setItems: action((state, newItems) => {
    state.items = newItems.map(data => Class != null ? new Class(data) : data)
})

I use React with easy-peasy state management library

How to print/save pdf in react native?

I have a screen where all the information related to user and their tasks will be displayed.. It’s like a report. At the end I have a button for the user clicking on which will allow them to save a pdf version of the same information. The information will be different every time.. So the number of rows will be different. How can this be achieved? I tried using react-native-html-to-pdf but I could create pdf of only static html.. Couldn’t figure out how to render dynamic html?
The ui will be slightly different for the pdf compared to the screen but the information will be same.