Avoid infinite loop when using a JavaScript for loop to iterate over an array and call gtag events

I am working on tracking user engagement with an ecommerce store. One of the features is adding a shopping list of items to your cart. This event has a datalayer instance which gets overwritten when the page reload and populates the basket. Before that happens I am saving the datalayer to session storage. Then on page load, for each item added to the basket I want to log an add to cart event within Google Analytics 4. I intend to do this via a custom gtag event, but when this runs it goes into an infinite loop.

Example code below

var newCartItems = JSON.parse(sessionStorage.getItem("cartContents"));
var keyLength = Object.keys(newCartItems).length -1;
var myCustomCartProducts = newCartItems[keyLength].ecommerce.add.products;
 
for(i = 0 ; i < myCustomCartProducts.length; i++) {  
 
 gtag(
                "event", "add_to_cart_multi", {
                "value": myCustomCartProducts[i].price * myCustomCartProducts[i].quantity,
                "currency": "{{Ga4 dlv ecommerce.currencyCode}}",
                "page_type": "{{CJS - Page Type}}",
                "search_term": "{{1 Cookie - searchterm}}",
                "search_term_previous": "{{Cookie - searchtermprevious}}",
                "search_term_all_lc": "{{Cookie - searchterm - Lowercase}}",
                "search_term_previous_all_lc": "{{Cookie - searchtermprevious - Lowercase}}",
                "is_user_logged_in_out": "{{MK - DL - user.status}}",
                "product_line_quantity": myCustomCartProducts[i].quantity,
                "product_line_price": myCustomCartProducts[i].price,
               
                items: [
                {
                "item_name": myCustomCartProducts[i].name ,
                "item_id": myCustomCartProducts[i].id ,
                "price": myCustomCartProducts[i].price,
                 "item_brand": myCustomCartProducts[i].brand,
                "item_category": myCustomCartProducts[i].category ,
                "quantity": myCustomCartProducts[i].quantity    

                }]
                    }); 
     
    
  
  }

When I change gtag to console.log the for loop completes normally.I am struggling to work out what is extending the length of the array/breaking the loop.

How can I refresh component every N seconds until some condition?

I would like to refresh a component every 5 seconds, but when I hit a stop condition I stop the rerender.

The actual code is:

const [status,setStatus ] = useState(''); //0:failed, 1:waiting, 2:success

useEffect(() => {
    const interval = setInterval(() => {
        setTime(new Date());
        if(status!='2' && status!='0'){ //if succes or fail STOP CALLING THE API
            handleClickRefresh()
        }
    }, 5000);
    return () => clearInterval(interval);
}, []);

const handleClickRefresh = async () => {
    axios.get('...', {
        headers: {
            ...
    }
    }).then((res) =>{
        if(res.status==202){
            setStatus('1'); //waiting
        }else if(res.status==200){
            setStatus('2'); //success
        }
    }).catch(
        function (error) {
            setStatus('0'); //fail
        }
    );
}

The problem seems to be that I can’t read “status” correctly, because when the component refresh status comes back to be == '' it resets to starting value.

How can I solve the problem?

Putting a login Authentication using Azure features in React Application

I am currently working on a calendar application which needs a login/user authentication. I tried doing it using azure, but due to my lack of expertise in Azure I found myself lost in multiple tutorials. I need the solution of this one. Any help or leads would be really helpful.
Here is how my application looks like.

Index.js

ReactDOM.render(
  <React.StrictMode>
    <ContextWrapper>
      <App />
    </ContextWrapper>
  </React.StrictMode>,
  document.getElementById("root")
);

App.js

return (
      <Router>
        <Routes>
          <Route exact path="/" element = {
            <React.Fragment>
              <div className="overall">
                <CalendarHeader />
                <div className="main-content-area">
                  <Sidebar />
                  <Month month={currentMonth} />
                  <EventModal />
                </div>
              </div>
            </React.Fragment>
            }>
          </Route>
          <Route exact path="/addEvents" element={<UpdateEventsForms />}></Route>
          <Route exact path="/editdeletedata" element={<EditAndDelete />}></Route>
          <Route exact path="/adminPage" element={<AdminPage />}></Route>
        </Routes>
      </Router>
  );

Header.js

<div>
 <button className="button-calendar-today">Sign-In</button>
 <button className="button-calendar-today" onClick={() => navigate("/adminPage")}>Admin 
 Login</button>
</div> 

And how I want is like when the user is not logged-in then don’t want to display admin page instead I would like to show sign-in button. But when the user is logged-in I want to display the admin page not the sign-in button.
Moreover, when clicked on Admin login that will take the user to the Admin Page (<AdminPage />) which is user in my react-router above in App.js

Vue3, how to make a same component to appear in the DOM when the component’s state is updated?

Can you please show me the pattern vue3 how can I achieve next thing:
I have a button component to attache a file. And once the file is attached I need to show the next same component, the same as the previous – to be empty in order to attach the next file, and to keep this process infinite. I thought a recursive component pattern should be fitting here maybe (I just can’t understand the algorithm), or resursive component is not the best choise?
I’m having some start sketch code.

//global store file
const file = ref(null)
const allAttachedFiles = ref([])
const allAttachedFile = // do I need also to modify this function cause I'll have more than a single file by pushing each file to the allAttachedFiles array ?

//
const attachFile = async (id sequence = 1) => {
    if (!file.value) {
      return
    }

    const filePath = ticketId + String(sequence)

    await uploadDocument({ file: file.value, filePath })
    await attacheFile({
      fileName: file.value.name,
      filePath,
    })
  }
//

// button component
<template>
  <AppRequestFromFieldFile v-model="formsStore.file" />
</template>

<script setup>
import { useRequestsFormsStore } from '@/stores/...'

   const formsStore = useRequestsFormsStore()
</script>   

How do i call the function as a parameter

I m new to programming i have stored the two function getComputerChoice() and getPlayerChoice() in a variable so that i can place them in the function playround parameter. but the value of the two is undefined in the playround. what am i doing wrong.

const computerSelection = getComputerChoice();
const playerSelection = getPlayerChoice();

let playRound = (playerSelection, computerSelection) => {

    const playerWin = `You win, you choose ${playerSelection} and the computer picked ${computerSelection}`;
    const computerWin = `You loose, you choose ${playerSelection} and the computer picked ${computerSelection}`
    const draw = `Ohhhhhhh, a drawww , You choose ${playerSelection} and the computer picked ${computerSelection}`;

    if (playerSelection == computerSelection && computerSelection == playerSelection) {
        return draw; 
    } else if (playerSelection > computerSelection && computerSelection < playerSelection) {
        return computerWin; 
    } else if (playerSelection < computerSelection && computerSelection > playerSelection) {
        return playerWin; 
    } else {
        return 1;
    }
}

I am unable to find any solution

react- Assign jsx elements in sequence with input from array elements

I am trying to assign jsx elements sequentially in a component. this sequence should be based off of array elements of an input. let me elaborate on what i mean.

`let input = ['apple', 'ball', 'cat']`

Above is the input array and the sequence of how i want my jsx elements, jsx elements are below

```
let apple = (<div>Apple as first element</div>)
let ball = (<div>Ball as second element</div>)
let cat = (<div>Cat as third element</div>)

return (
    <>
      {input[0]}
      {input[1]}
      {input[2]}
   </>
)```

`

If i do the following shown above, jsx elements doesnot gets diplayed but if i do below code, jsx elements show fine.

```return (
    <>
      {apple}
      {ball}
      {cat}
   </>
)```

can someone let me know how to get the first scenario working.

How to resolve gulp issue with the file not found, even though file exists in my case

I’m figuring out how Gulp works, and following is a sample task,

function negativeGlobTest(){
    return src(["./src/**/*.js", "!./src/pop/*.js", "./src/pop/twopac.js"])
    .pipe(ugli())
    .pipe(rename({extname : ".min.js"}))
    .pipe(dest("./superOutput"))
}

and here is my output for the `ls -lR src

src:
total 1
-rw-r--r-- 1 terminator 197121 395 Apr  5 14:31 index.js 
drwxr-xr-x 1 terminator 197121   0 Apr  5 18:43 pop/     

src/pop:
total 2
-rw-r--r-- 1 terminator 197121 133 Apr  5 18:30 mao.js   
drwxr-xr-x 1 terminator 197121   0 Apr  5 14:30 pom/     
-rw-r--r-- 1 terminator 197121 154 Apr  5 18:34 twopac.js

src/pop/pom:
total 1
-rw-r--r-- 1 terminator 197121 29 Apr  5 18:27 index.js 

upon running the task I’m encountering the error

Error: File not found with singular glob: C:/my-github-repo/master/src/pop/twopac.js (if this was purposeful, use `allowEmpty` option)

clearly file exists, What am I doing wrong here ?

I think glob should first match all the files inside the src excluding all the files ending at js inside pop, and later allowing the twopac.js which is inside the pop.

HTML collection has elements but indices are null [duplicate]

I have a table and want to color the numbers based on their amount. Therefor I try to get the innerHTML (with the number) of the td’s with class=”account-balance” in javascript.

The problem is that indices of the HTML collection that I get back are null, which they are definitly not and the indices are existing.

function setBalanceColor() {
  console.log(dataTBody.getElementsByClassName("account-balance"));
  console.log(dataTBody.getElementsByClassName("account-balance")[1]);
  console.log(dataTBody.getElementsByClassName("account-balance")[1].innerHTML);
}

Outputs in console

And that is what’s inside the innerHTML of index [1]:

Content of innerHTML from index 1

Using .item(1) instead of [1] leads to the same result. Also different index-numbers. I have no clue what the reason could be. Someone who got an idea?

highlight x-axis on x value condition

High everybody!

I have a series with constant time step e.g:
2009/07/13,120
2009/07/14,120
2009/07/15,120
but sometimes some steps missed:
2009/07/16,120
2009/07/19,180

Can I highlight missed area?
Is it possible to expand missed area?

Change checkboxes look and color if selected [closed]

I would like to make my checkboxes look like aligned buttons and make so that the text and background color changes when selected. I’m currently using bootstrap 5 and came to this result until now :

Checkboxes

I would also like the ckeckboxes to fit inside the fieldset

<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"  />

<fieldset class="border rounded-4 p-5">
<legend class="float-none w-auto px-3" align="center">Documentary System</legend>
  <div class="form-inline" style="vertical-align:middle"> 
    <div class="input-group w-auto" style="display: inline-flex;">
      <div class="btn-group btn-group-toggle row" style="width:800px; margin:0 auto;">
        <div class="btn btn-secondary col-md-6" data-toggle="buttons">
          <label class="btn btn-secondary" for="grpdoc1">
            <input class="form-check-input" name="groups[]" type="checkbox" id="grpdoc1" value="grp_FCBG_Collaborator_RW" style="display: none;">Collaborator_RW
          </label>
        </div>
        <div class="btn btn-secondary col-md-6" data-toggle="buttons">
          <label class="btn btn-secondary" for="grpdoc2">
            <input class="form-check-input" name="groups[]" type="checkbox" id="grpdoc2" value="grp_FCBG_Events_RW" style="display: none;">Events_RW
          </label>
        </div>
        <div class="btn btn-secondary col-md-6" data-toggle="buttons">
          <label class="btn btn-secondary" for="grpdoc3">
            <input class="form-check-input" name="groups[]" type="checkbox" id="grpdoc3" value="grp_FCBG_Finance_RW" style="display: none;">Finance_RW
          </label>
        </div>
        <div class="btn btn-secondary col-md-6" data-toggle="buttons">
          <label class="btn btn-secondary" for="grpdoc4">
            <input class="form-check-input" name="groups[]" type="checkbox" id="grpdoc4" value="grp_FCBG_IT_RW" style="display: none;">IT_RW
          </label>
        </div>
        <div class="btn btn-secondary col-md-6" data-toggle="buttons">
          <label class="btn btn-secondary" for="grpdoc6">
            <input class="form-check-input" name="groups[]" type="checkbox" id="grpdoc6" value="grp_FCBG_Management_RW" style="display: none;">Management_RW
          </label>
        </div>
        <div class="btn btn-secondary col-md-6" data-toggle="buttons">
          <label class="btn btn-secondary" for="grpdoc7">
            <input class="form-check-input" name="groups[]" type="checkbox" id="grpdoc7" value="grp_FCBG_Platform_Collaborator_RW" style="display: none;">Platform_Collaborator_RW
          </label>
        </div>
        <div class="btn btn-secondary col-md-6" data-toggle="buttons">
          <label class="btn btn-secondary" for="grpdoc8">
            <input class="form-check-input" name="groups[]" type="checkbox" id="grpdoc8" value="grp_FCBG_Platform_Manager_RW" style="display: none;">Platform_Manager_RW
          </label>
        </div>
        <div class="btn btn-secondary col-md-6" data-toggle="buttons">
          <label class="btn btn-secondary" for="grpdoc9">
            <input class="form-check-input" name="groups[]" type="checkbox" id="grpdoc9" value="grp_FCBG_Quality_Manager_RW" style="display: none;">Quality_Manager_RW
          </label>
        </div>
        <div class="btn btn-secondary col-md-6" data-toggle="buttons">
          <label class="btn btn-secondary" for="grpdoc10">
            <input class="form-check-input" name="groups[]" type="checkbox" id="grpdoc10" value="grp_FCBG_RH_RW" style="display: none;">RH_RW
          </label>
        </div>
      </div>
    </div>
  </div>
</fieldset>

Negative numbers in Binary Search Function

I have created a binary search function operating in a divide and conquer fashion.
Comparing the middle index value of an array, for smaller or larger to the sought value.
If the middle index is higher than then sought value than we look for the middle index between that midpoint and the leftIndex (initialized as 0), and the opposite for the right side.

Very simple and everything works fine, my question is that when. a testcase is introduced with negative number, for example, [-1,0,3,5,9,12] and searching for 9, we get a timeout and it cannot compute.

My array is sorted, so I am curious to know why this would not work, considering the integer values are compareable, and that looking for the value of 9, the -1 at index 0 would not even be considered, in this particular example.

Please see my function here.

function binarySearch(arr, val){
    //lets first declare our left and right values 
    let leftIdx = 0;
    let rightIdx = arr.length - 1
  
    while(leftIdx <= rightIdx){
    //while left idx is smaller or equal to right
    //lets calculate the middle
    let middleIndex = Math.floor(leftIdx + rightIdx / 2);
    //lets extract the value from this middleIndex
    let middleVal = arr[middleIndex]
    
    if(val < middleVal){
      //if our sought value is smaller than the middle
      rightIdx = middleIndex - 1
    } else if(val > middleVal){
      //if our sought value is bigger than middle
      leftIdx = middleIndex + 1
    
    } else {
      return middleIndex
    }
  }
  return -1
}

nginx no carga css, js, etc

Tuve el siguiente problema, tengo un sistema alojado en un droplet de digital ocean, soy nueva en este servidor asi que cualquier ayuda me sirve. El mismo funcionaba sin problema hasta que venció el dominio y dejo de cargar. Por cuestion de tiempo, el mismo debio volver a ser registrado y delegado ya que no alcance a renovar. Antes de ser registrado nuevamente se ingresaba mediante la ip publica y cargaba sin problema, por ejemplo http://125.31.190.131/home/ pero luego de hacer el proceso mencionado del dominio el acceso al sistema se empezó a cargar mediante el puerto 8001, es decir http://125.31.190.131:8001/home/ ya que si ingresaba como al principio solo levantaba apache y no el sistema en si.

Por si sirve el sistema carga mediante gunicorn django/python y mediante nginx los archivos static

El problema especifico seria nginx que dejo de responder ya que al ingresar al sistema no reconoce las rutas de los static. Me fije en los archivos log de error y no se encontraron, incluso las rutas de configuración donde se encuentran los static, tambien en la configuracion nginx se encuentra configurado “listen 80” y por las dudas quise cambiar a 8001 pero nginx deja de funcionar.

swap the js var node words for an html span list inside a div

I want to swap the words in the js, i want the words to come from a span word list inside a div, the source of this project is a codepen file, here is the link of the codepen file https://codepen.io/controversial/pen/wWVGOv I am not sure if editing this codepen file is allowed or not, but that is what I need to learn to do, thank you in advance.

   <div id="bubbles"></div>
    #bubbles {
  position: absolute;
  width: 100vw;
  height: 100vh;
  top: 0;
  left: 0;
}
    var nodes = new vis.DataSet([
  {label: "Pop"},
  {label: "Alternative"},
  {label: "Rock"},
  {label: "Jazz"},
  {label: "Hits"},
  {label: "Dance"},
  {label: "Metal"},
  {label: "Experimental"},
  {label: "Rap"},
  {label: "Electronic"},
]);
var edges = new vis.DataSet();

var container = document.getElementById('bubbles');
var data = {
  nodes: nodes,
  edges: edges
};

var options = {
  nodes: {borderWidth:0,shape:"circle",color:{background:'#F92C55', highlight:{background:'#F92C55', border: '#F92C55'}},font:{color:'#fff'}},
  physics: {
    stabilization: false,
    minVelocity:  0.01,
    solver: "repulsion",
    repulsion: {
      nodeDistance: 40
    }
  }
};
var network = new vis.Network(container, data, options);


// Events
network.on("click", function(e) {
  if (e.nodes.length) {
    var node = nodes.get(e.nodes[0]);
    // Do something
    nodes.update(node);
  }
});

I try using Google’s Bard and it froze and could not doit, I try perplexity and also could not doit.

Percentage Calculation Based on Quantity

Consider this javascript array here are 3 milestones.

const discounts = [
  { "discountBasedOn": "QUANTITY", "quantity": 5, "discount": 20 },
  { "discountBasedOn": "QUANTITY", "quantity": 8, "discount": 30 },
  { "discountBasedOn": "QUANTITY", "quantity": 10, "discount": 40 },
]

from given array i want to calculate each item Percentage of Calculation based on totalCartItems.

  1. Suppose totalCartItems is 4, transform the array like:
[
  { "discountBasedOn": "QUANTITY", "quantity": 5, "discount": 20, "percentageCompleted": 80 },
  { "discountBasedOn": "QUANTITY", "quantity": 8, "discount": 30, "percentageCompleted": 0 },
  { "discountBasedOn": "QUANTITY", "quantity": 10, "discount": 40, "percentageCompleted": 0 },
]

here until complete the current milestone next milstone should be 0%.

  1. Suppose totalCartItems is 5, transform the array like:
[
  { "discountBasedOn": "QUANTITY", "quantity": 5, "discount": 20, "percentageCompleted": 100 },
  { "discountBasedOn": "QUANTITY", "quantity": 8, "discount": 30, "percentageCompleted": 62.5 },
  { "discountBasedOn": "QUANTITY", "quantity": 10, "discount": 40, "percentageCompleted": 0 },
]
  1. Suppose totalCartItems is 8, transform the array like:
[
  { "discountBasedOn": "QUANTITY", "quantity": 5, "discount": 20, "percentageCompleted": 100 },
  { "discountBasedOn": "QUANTITY", "quantity": 8, "discount": 30, "percentageCompleted": 100 },
  { "discountBasedOn": "QUANTITY", "quantity": 10, "discount": 40, "percentageCompleted": 80 },
]

and so on.

I have tried this. this working. but here problem is current milstone is dependent on previous milstone. I want something like independent. is it possible? like each milestone will not dependent on others milstone. but also necessary feature is if current milstone is not reached to 100% next all milestone should be show as 0%

sortedTieredDiscounts.map((item, index, items) => {
    const isLastMilestoneReached = index === 0 || totalBundleItems >= items[index - 1].quantity;
    const calculateProgress = (totalBundleItems, quantity) => {
      const progress = (totalBundleItems / quantity) * 100;
      return Math.min(progress, 100);
    }
    const currentTierProgress = isLastMilestoneReached ? calculateProgress(totalBundleItems, item.quantity) : 0;
    return {
      ...item,
      percentageCompleted: currentTierProgress
    }
  })