How can I get the event when user type a URL and go to it?

I saw on a website that we can see when a use try to refresh the page ( using F5 or clicking the refresh button ) in this way:

if (performance.navigation.type === 1)

My question is: Let’s say the user don’t refresh the page but he type another URL to my other page. How can I get that event?

I say that because I have stored in my Redux state if user is logged in. When the page is type another URL, my state is lost. So, I want to catch that moment and check if I have a token in localstorage.

Is it possible to insert a span at a paragraph range? It gets problematic if the paragraph already has spans

I am trying to insert a new span into a paragraph that already has spans. If the paragraph doesn’t have any spans the inserting of the new span works perfectly.

But it gets messed up when one or more spans already exists in the paragraph. Is it even possible to make this work?

At the last 3 lines of the function is where the paragraph gets put back together to insert the new span in between. I am having trouble converting the split paragraph back into a HTML format, it always seems to stay like a string or something else is getting in the way. You can get an idea by running the code and selecting some text, it will insert the span at the mouseup event.

function replaceSelectedParagraphTextBySpan() {
  // get range and text of selected text in paragraph
  let text = "";
  if (window.getSelection) {
    text = window.getSelection().toString();
  } else if (document.selection && document.selection.type != "Control") {
    text = document.selection.createRange().text;
  }
  
  const storedSelections = []
  const currSelection = window.getSelection();
  for (let i = 0; i < currSelection.rangeCount; i++) {
    storedSelections.push(currSelection.getRangeAt(i))
  }
  const rangeStart = storedSelections[0].startOffset
  const rangeEnd = storedSelections[0].endOffset

  // our paragraph
  const textObject = document.getElementById('textObject')

  const frontParagraph = textObject.innerHTML.substring(0, rangeStart)
  const backParagraph = textObject.innerHTML.substring(rangeEnd, textObject.length)
  // I tried here to convert the front and backParagraph into a paragraph element because instead it
  // just remains a string
  const pElementFront = document.createElement('p').innerHTML = frontParagraph
  const pElementBack = document.createElement('p').innerHTML = backParagraph

  // create our span for inserting
  const span = document.createElement('span')
  span.innerHTML = " <this text got added> "

  // insert new span into paragraph at selected range
  textObject.innerHTML = pElementFront
  textObject.appendChild(span)
  textObject.innerHTML = textObject.innerHTML + pElementBack
}

const paragraph = document.getElementById('textObject')
paragraph.addEventListener('mouseup', e => {
  replaceSelectedParagraphTextBySpan()
})
<p id="textObject"><span>Select some </span>text and the selected text will get replaced by a span</p>

Google sheets API sorting by date

I’m using nodejs with google sheets API and I’m trying to sort data by column with date string that looks like this: ‘dd.mm’, for example ‘01.03’. Currently I’m trying to do it by using batchUpdate, but it doesnt work. It sorts by day, 01 is first, 02 is second etc… My request looks like this:

await googleSheets.spreadsheets.batchUpdate({
    spreadsheetId,
    requestBody: {
      requests: [
        {
          sortRange: {
            range: {
              sheetId,
              startRowIndex,
              endRowIndex,
              startColumnIndex,
              endColumnIndex,
            },
            sortSpecs: [
              {
                dimensionIndex,
                sortOrder,
              },
            ],
          },
        },
      ],
    },
  });

How can I make google sheets API see the columns as dates, not as strings? Because I assume thats where the problem is, the date string is sorted like a normal string.

Adding auto expand functionality to collapsible Content script

I have used THIS SCRIPT to create collapsible sections into my website: LINK

as you can see I have problem since inside the collapsible section, I inserted a drop down menu’,
when I expand section and I click on drop down menu’ to see more voices, the collapsible section doesn’t expand automatically with the content. How can I make the collapsible section automatically expandcontract according to its content?

this is the Whole Code (Javascrip,CSS and HTML) and you can run snipet to see what happens (Section doesn’t expand according to it’s content):

window.addEventListener("DOMContentLoaded", e => {

  const getContainerHeight = el => {
    return window.getComputedStyle(el).getPropertyValue("height");
  };

  const setTransitionHeights = el => {

    let containerWasOpen = el.classList.contains("open");

    el.style.height = null;

    el.classList.remove("open", "ready");
    el.dataset.initial = getContainerHeight(el);

    el.classList.add("open");
    el.dataset.final = getContainerHeight(el);
    el.classList.remove("open");

    if(containerWasOpen) {
      el.classList.add("open");
      el.style.height = el.dataset.final;
    } else {
      el.style.height = el.dataset.initial;
    }

    el.classList.add("ready");

  };

  document.querySelectorAll(".collapsible.slow").forEach(current => {

    let toggler = document.createElement("div");
    toggler.className = "toggler";
    current.appendChild(toggler);

    setTransitionHeights(current);

    toggler.addEventListener("click", e => {
      current.style.height = current.classList.toggle("open") ? current.dataset.final : current.dataset.initial;
    });

  });

  window.addEventListener("resize", e => {

    document.querySelectorAll(".collapsible.slow").forEach(current => {
      setTransitionHeights(current);
    });

  });

});

</script>
<style>
ul, #myUL {
  list-style-type: none;
}

#myUL {
  margin: 0;
  padding: 0;
}

.caret {
  cursor: pointer;
  -webkit-user-select: none; /* Safari 3.1+ */
  -moz-user-select: none; /* Firefox 2+ */
  -ms-user-select: none; /* IE 10+ */
  user-select: none;
}

.caret::before {
  content: "25B6";
  color: black;
  display: inline-block;
  margin-right: 6px;
}

.caret-down::before {
  -ms-transform: rotate(90deg); /* IE 9 */
  -webkit-transform: rotate(90deg); /* Safari */'
  transform: rotate(90deg);  
}

.nested {
  display: none;
}

.active {
  display: block;
}
html *
{
   font-family: verdana !important;
}

body {
  background-image: url("bg.jpg");
  background-repeat: repeat;
}

.container {
  position: relative;
}

.vertical-center {
  width: 350;
  margin: 0;
  position: absolute;
  top: 12%;
  left: 5%;
  -ms-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}

.content {
  width: 850;
  margin: 0;
  padding-bottom: 25px;
}

.empty {
  width: 100%;
}


/* Tooltip container */
.tooltip {
  position: relative;
  display: inline-block;
  border-bottom: 1px dotted black; /* If you want dots under the hoverable text */
}

/* Tooltip text */
.tooltip .tooltiptext {
  visibility: hidden;
  top: -5px;
  left: 105%;
  width: 220px;
  background-color: black;
  color: #fff;
  text-align: center;
  padding: 5px 0;
  border-radius: 6px;
 
  /* Position the tooltip text - see examples below! */
  position: absolute;
  z-index: 1;
}

/* Show the tooltip text when you mouse over the tooltip container */
.tooltip:hover .tooltiptext {
  visibility: visible;
}
.tooltip .tooltiptext::after {
  content: " ";
  position: absolute;
  top: 20%;
  right: 100%; /* To the left of the tooltip */
  margin-top: -5px;
  border-width: 5px;
  border-style: solid;
  border-color: transparent black transparent transparent;
}


  .boxed {
    border: 1px solid #ccc;
    padding: 1em 2em;
  }

  .collapsible.slow {
    position: relative;
    overflow: hidden;
    padding-bottom: 0.5em;
    transition: height 0.5s ease-out;
  }
  .collapsible.slow > * {
    display: none;
  }
  .collapsible.slow > p:first-child,
  .collapsible.slow.open > *,
  .collapsible.slow.ready > * {
    display: revert;
  }

  .collapsible.slow > .toggler {
    position: absolute;
    left: 0;
    bottom: 0;
    width: 100%;
    background: #fff;
    text-align: center;
    cursor: pointer;
  }
  .collapsible.slow > .toggler::after {
    content: "25bc";
  }
  .collapsible.slow.open > .toggler::after {
    content: "25b2";
  }
</style>
<div class="collapsible slow boxed">
<p align="center"><i> <strong>ONTOLOGICAL</strong></i></p>
<ul class="nested">
      <li><span class="caret">Voice One</span>
        <ul class="nested">
          <li><span class="caret">First Way</span>
            <ul class="nested">
              <li>01 Item one</li>
              <li>02 Item two</li>
              <li>03 Item three</li>
              <li>04 Item four</li>
            </ul>
          <li><span class="caret">Second Way</span>
            <ul class="nested">
              <li>01 Item one</li>
              <li>02 Item two</li>
              <li>03 Item three</li>
              <li>04 Item four</li>
            </ul>
          <li><span class="caret">Third Way</span>
            <ul class="nested">
              <li>01 Item one</li>
              <li>02 Item two</li>
              <li>03 Item three</li>
              <li>04 Item four</li>
            </ul>
          </li>
        </ul>
<li><span class="caret">Voice Two</span>
        <ul class="nested">
          <li><span class="caret">First Way</span>
            <ul class="nested">
              <li>01 Item one</li>
              <li>02 Item two</li>
              <li>03 Item three</li>
              <li>04 Item four</li>
            </ul>
          <li><span class="caret">Second Way</span>
            <ul class="nested">
              <li>01 Item one</li>
              <li>02 Item two</li>
              <li>03 Item three</li>
              <li>04 Item four</li>
            </ul>
          <li><span class="caret">Third Way</span>
            <ul class="nested">
              <li>01 Item one</li>
              <li>02 Item two</li>
              <li>03 Item three</li>
              <li>04 Item four</li>
            </ul>
          </li>
        </ul>
      </li>  
    </ul>
  </li>
</ul>
<p></p>
</div>
<script>
var toggler = document.getElementsByClassName("caret");
var i;

for (i = 0; i < toggler.length; i++) {
  toggler[i].addEventListener("click", function() {
    this.parentElement.querySelector(".nested").classList.toggle("active");
    this.classList.toggle("caret-down");
  });
}
</script>

jQuery $.parseJSON(); behaving differently in two calls

I’m using jQuery to get and parse some JSON from my ASP.Net MVC backend. I’m recieving the data correctly:

data: "{"0":"Imgs/staticResistor.png","1":"Imgs/wire.png"}"

Function to get data:

$.getJSON('https://localhost:44338/Editor/GetImgUrlFromTypeID/')
                .done((data) => {
                    console.log("JSON: " + $.parseJSON(data)[0]);
                    let json = $.parseJSON(data)[0];
                    //return $.parseJSON(data);
                })
                .fail((error) => {
                    console.log("GET request failed: " + error);
                    return "didnt work";
                });

However, when I assign $.parseJSON(data)[0]; to a variable or return it, it’s undefined:

json: undefined

I can’t discern why the method is behaving differently in different calls.

in media printing, the header is broken on two pages except for first three

enter image description here

enter image description here

As shown in two images, after the 5th page in my printed report the header begin to be broken on two pages and all the styles are broken.

CSS:

  table {
    page-break-inside: auto;
  }
  tr {
    page-break-inside: avoid;
    page-break-after: auto;
  }
  thead {
    display: table-header-group;
  }
  tfoot {
    display: table-footer-group;
  }

How to get value of updated state immediatly in useEffect

In the following I am updating the value of a state and then trying to use it inside useEffect only but cannot get the value of the updated state can anyone help me regarding how can i get updated state immediately inside useEffect only

Thank you

    useEffect(() => {
                dispatch(setSecondaryInvName(barcodeData))
                console.log("secondaryInventoryName == ", secondaryInventoryName)
            }
    })

cypress test webservice response (xml)

Is there a simple way to test API calls and test the response of that calls? For now we do stuck at a simple xml response from within the reponse itself. We like to use xpath (cypress plugin) to crawl the xml like:

cy.request(`${DOCUMENT_FACADE}`).then((response) => {
  //response is a valid JSON and its body property holds a string (xml)  

  cy.get(response.body).xpath("//*[name() = 'myName']") //this fails by "Not a DOM Object"
  
  //Then we tried to give it a DOM object
  var parser = new DOMParser(),
      doc = parser.parseFromString(response.body, 'text/xml');
  cy.get(doc).xpath("//*[name() = 'myName']").should('have.length', 1) //fails with "expected undefined to have a length of 1 but got 0
});

Maybe we totally got something wrong about this quite important part of testing I assume.

Don’t accept variables in AJax function

function clear_yes_button(clicked_id) {
  var myVar = "test";
  document.getElementById("yes_" + clicked_id).innerHTML = " ";
  <% if current_user.present? %>
  $.ajax({
    type: "PATCH",
    url: "<%= read_report_path(clicked_id) %>",
  })
  <% end %>
  }

But “clicked_id” in read_report_path(clicked_id)
undefined local variable or method `clicked_id’ for #ActionView::Base:0x00000000019370

How to pass clicked_id?

React useState, adding new object to array of objects

This a doubt I have regarding the best practice when pushing a new object in an array of objects via setState.

In the below implementation the ‘prevObjects’ are being spread into the new array to set the state. This passes the references of the old objects, but does not mutate the array or the objects. Hence does that mean the below implementation is good? It is working, but could it be problematic in some edge cases?

const [objArray, setObjArray] = useState([{ name: John }, { name: Jane }]);

setObjArray((prevObjects) => [...prevObjects, newObject])

HTML Page to a PDF in Angular

I’m working with Angular and I’m resolving an issue where I need to develop a report and be able to convert the entire HTML page to a PDF clicking on a button.
I’m looking on the internet and found a JSPDF package, but I can’t render the HTML entire page to a PDF, can anyone help me with that, is there another package or similar stuff that I can be able to make that?
Can I do that using jspdf?

Image of the code

Injecting Javascript/JQuery in React IFrame

I am trying to embed Grafana dashboard into my react application. I want to hide Grafana Cycle View component and Sidebar using Javascript/JQuery once the dashboard is being loaded in the dialogue box, but I have no success in doing so.

This is my React code that I am trying to do:

const iFrame = useRef(null);

const injectJSiFrame = () => {
        let script = document.createElement("html");
        script.append(`
            <script>
            $('[aria-label="Cycle view mode"]')[0].style.display = 'none';
            </script>
        `);
        iFrame.current.appendChild(script);
    }

return (
        <div>
           <Dialog header="Dashboard" visible={displayDialogue} style={{ width: '90vw' }} footer={renderFooter('displayBasic')} onHide={() => onHide('displayBasic')}>
        <iframe src="dashboard-url" onLoad={injectJSiFrame} width="1300" ref={iFrame} height="1000" frameBorder="0" className="grafana-panel" id="grafanaframe"></iframe>              
           </Dialog>
        </div>
)

I have also tried using Javascript property but still no luck:

document.querySelectorAll('[aria-label="Cycle view mode"]');

Filter button with Javascript & React

Good day! I am hoping to get some help with a project I am working on. I created a filter functionality so that when a user click on a button, they can filter my projects based on what type of project it is.

I was able to get the “ALL” button to work but the other buttons are not working.
The expected output is when I click on the button it filters out the other projects and keeps the one that matches the category.
However the current output is when I click on the button, the projects disappear.

This is my code:

    import React, {useState} from "react";
import ReactDOM from "react-dom";
import styles from "./projects.module.scss";
import cards from "./allData";


function Projects() {
 
  const [state, setState] = useState(cards);

  const handleBtns = (e) => {
      let word = e.target.value;
      function isCardActive() {
        for(const card of cards) {
            if (cards.category === "FEATURED") {
                return true;
            } else if (cards.category === "WEB APP") {
                return true;
            } else if (cards.category === "MOBLE APP"){
                return true
            }
        } 
      };

      if(word === 'All') { 
          setState(cards)
      } else if(word === 'Featured') {
          const filtered = cards.filter(isCardActive);
          setState(filtered);

    }  else if(word === 'webApp') {
        const filtered = cards.filter(isCardActive);
        setState(filtered);

  } else if(word === 'mobileApp') {
    const filtered = cards.filter(isCardActive);
    setState(filtered);
  }
}


    return(
        <div className={styles.projects} id="projectHash">
           <section>
               <h3>PROJECTS</h3>
            </section>

            
             <section id={styles.filterMain}>
            <button className={`${styles.filterBox} ${styles.active}`} onClick={handleBtns} type="button" value="All"  >VIEW ALL</button> 
            <button className={styles.filterBox} onClick={handleBtns} type="button" value="Featured"  >FEATURED</button>
            <button className={styles.filterBox} onClick={handleBtns} type="button" value="webApp"  >WEB APP</button>
            <button className={styles.filterBox} onClick={handleBtns} type="button" value="mobileApp" >MOBILE APP</button>  
                 
            </section>

            <section>

           {state.map((cards) => (
                <div className={styles.projectcard} key={cards.id} >

                <h4>Project Name: {cards.title} </h4>
                <br/>
                <h4>{cards.image}</h4>
               
            </div>

           ))}
           </section>
            
        </div>
    )
};

export default Projects;

This is code for the file that contains the array of data

import card1 from "../../assets/card1.jpg";
import card2 from "../../assets/card2.jpg";
import card3 from "../../assets/card3.jpg";
import card4 from "../../assets/card4.jpg";
import card5 from "../../assets/card5.jpg";
import card6 from "../../assets/card6.jpg";

 const cards = [
    {
        title: 'VICTORY FOLIO',
        category: ['WEB APP', 'FEATURED'],
        description: 'Lorem ipsum dolro sit amt, consestcuer elit',
        image: card1,
        id: 1

    },
    {
        title: 'IN WHOLENESS PRACTICE',
        category: 'WEB APP',
        description: 'Lorem ipsum dolro sit amt, consestcuer elit',
        image: card2,
        id: 2
    },
    {
        title: 'TRIBE HAIRCARE',
        category: ['WEB APP', 'MOBILE APP', 'FEATURED'],
        description: 'Lorem ipsum dolro sit amt, consestcuer elit',
        image: card3,
        id: 3
    },
    {
        title: 'TRIBE SKINCARE',
        category: ['WEB APP', 'MOBILE APP'],
        description: 'Lorem ipsum dolro sit amt, consestcuer elit',
        image: card4,
        id: 4
    },
    {
        title: 'BUG TRACKER',
        category: 'WEB APP',
        description: 'Lorem ipsum dolro sit amt, consestcuer elit',
        image: card5,
        id: 5
    },
    {
        title: 'PATIENT PORTAL',
        category: 'MOBILE APP',
        description: 'Lorem ipsum dolro sit amt, consestcuer elit',
        image: card6,
        id: 6
    }

];

export default cards;

Process HTTP request in batch in NodeJs

Problem

I have a single server that can process 10 HTTP requests in a minute. If I get more than 10 requests, then I would like to save them somewhere to respond to them later.

Latency is not a problem here, clients can wait

What I did

import express from "express";
const app = express();
const Q = [];

async function scheduler() {
  // if Q is empty then wait for  request to come in
  if (!Q.length) {
    setTimeout(scheduler, 1000);
    return;
  }

  // send response to all currently available requests
  let currentLength = Q.length;
  for (let i = 0; i < currentLength; i++) Q[i].res.send("Q" + Q[i].id);

  // remove the requests whose response is sent
  Q.slice(0, currentLength);
  scheduler();
}

scheduler();

app.get("/", (req, res) => {
  // store HTTP requests
  Q.push({ req, res, id: req.query.id });
});

app.listen(process.env.PORT || 5000, () => console.log("Server is running..."));

I tried to store the requests in the array, then send a response by another function.

This is just a simulation

I tried the following script to test the script

import axios from "axios";

const promises = [];
for (let i = 0; i < 25; i++) {
  promises.push(axios.get(`http://localhost:5000?id=${i}`));
}

console.time();
Promise.allSettled(promises).then((res) => {
  console.timeEnd();
  console.log(res.map((httpRes) => httpRes?.value?.data));
});

I am getting successful response for each request

[
  'Q0',  'Q1',  'Q2',  'Q3',
  'Q4',  'Q5',  'Q6',  'Q7',
  'Q8',  'Q9',  'Q10', 'Q11',
  'Q12', 'Q13', 'Q14', 'Q15',
  'Q16', 'Q17', 'Q18', 'Q19',
  'Q20', 'Q21', 'Q22', 'Q23',
  'Q24'
]

But, still I am getting the below error on server terminal

(node:26071) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:561:11)
    at ServerResponse.header (/home/rahul/Desktop/projects/temp/puppeteer/node_modules/express/lib/response.js:776:10)
    at ServerResponse.send (/home/rahul/Desktop/projects/temp/puppeteer/node_modules/express/lib/response.js:170:12)
    at scheduler (file:///home/rahul/Desktop/projects/temp/puppeteer/index.js:43:52)
    at Timeout.scheduler [as _onTimeout] (file:///home/rahul/Desktop/projects/temp/puppeteer/index.js:47:3)
    at listOnTimeout (internal/timers.js:557:17)
    at processTimers (internal/timers.js:500:7)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:26071) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:26071) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.