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;
  }

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.

React form input values in JS

I am using NextJS with bulma CSS to create a simple application. I have this following form:

const MyPage = () => {
const [firstName, setFirstName] = useState('')
const [secondName, setSecondName] = useState('')

const createNftHandler = async() => {
   // Todo: perform some action with firstName and secondName
}

const updateFirstName = event => {
    setFirstName(event.target.value)
}

const updateSecondName = event => {
    setSecondName(event.target.value)
}

return (
<section className='mt-5'>
    <div className='container'>
        <div className='field'>
            <label className='label'>My Form</label>
            <div className='control'>
                <input onChange={updateFirstName} className='input' type='type' placeholder='Enter First Name'></input>
            </div>
        </div>
        <div className='field'>
            <div className='control'>
                <input onChange={updateSecondName} className='input' type='type' placeholder='Enter Second Name'></input>
            </div>
        </div>
        <button onClick={createUser} className='button is-primary'>Create</button>
    </div>
</section>
)
}
export default MyPage

I have to call updateFirstName and updateSecondName on every input change.
I want to get these input field’s value on createUser() function call only. Please suggest how to do it or any other better approach.

How to allow javascript form to skip questions without producing text which assumes an answer?

I have created a page with a form for people to complete, which when completed produces a text file of the person’s answers.

However I want people to have the option of skipping a question if they don’t want to answer it.

The problem with the code below is that if you skip a question it still produces the preceding/following text and spaces.

i.e. if a person doesn’t want to answer the question about their age, the below code will still produce text which reads “Age:[space][space]” in the text file.

If someone skips a question how to I stop the text file still producing the above? Ideally I want it to be completely ignored in the text file if the question hasn’t been answered.

    // Get the data from each element on the form.
    const name = document.getElementById('txtName');
    const age = document.getElementById('txtAge');
    const email = document.getElementById('txtEmail');
    const country = document.getElementById('selCountry');
    const msg = document.getElementById('msg');
    
    // This variable stores all the data.
    let data = 
        'r Name: ' + name.value + ' rn ' + 
        'Age: ' +age.value + ' rn ' + 
        'Email: ' + email.value + ' rn ' + 
        'Country: ' + country.value + ' rn ' + 
        'Message: ' + msg.value;
    
    // Convert the text to BLOB.
    const textToBLOB = new Blob([data], { type: 'text/plain' });
    const sFileName = 'formData.txt';      // The file to save the data.

    let newLink = document.createElement("a");
    newLink.download = sFileName;

    if (window.webkitURL != null) {
        newLink.href = window.webkitURL.createObjectURL(textToBLOB);
    }
    else {
        newLink.href = window.URL.createObjectURL(textToBLOB);
        newLink.style.display = "none";
        document.body.appendChild(newLink);
    }

    newLink.click(); 

Что такое триггерная рассылка? [closed]

ТРИГГЕРНАЯ РАССЫЛКА — это последовательность писем, которые отправляются при наступлении определенных событий. Это может быть брошенная корзина, отсутствие активности пользователя в течение какого-либо времени, успешно оформленный заказ.
★★★★★★★★★★★★★★★★★★★★★★★
Для примера мы создадим рассылку вручную, не используя готовые шаблоны. В основных параметрах рассылки вы можете:

Ввести название рассылки. Будьте внимательны и обязательно продумайте название. Его увидит получатель.
Выберите сайт, от имени которого будет отправлена рассылка.
Добавьте описание для письма. Его тоже увидит получатель.
Выберите условие для запуска рассылки. На этом пункте мы остановимся подробнее ниже.
Выберите условие достижение цели. Оно будет отображаться в метрике.

How to click on multiple dropdown & select same values from all dropdown in cypress

I am able to click on all dropdowns but am not able to select values from them one by one.

cy.xpath('/html/body/app-root/div/mat-sidenav-container/mat-sidenav-content/app-configurable-product-management/form/div[2]/mat-card/mat-card-content/app-configurable-product-inventory/form/div/div/div/div')
            .each($row => {
                //Click on drop down
                cy.wrap($row).find(':nth-child(4) > .common-form-field-width > .mat-form-field-wrapper > .mat-form-field-flex > .mat-form-field-infix').click({timeout: 2000, force:true})
                //Select same values from all dropdown (Not working)
                cy.contains('In Stock').click({timeout: 2000, force:true})
                cy.wait(2000)
            })

Map function stores the value of the last object in the array to all values

I am getting data from Firestore and using the map function to display all of that data. I am sending one of the arguments within a URL to get an image. I am sending a cryptocurrency pair in a URL to get an image in response. I am also displaying the pair in the table. However, when I send the same symbol in the map function, all of my pairs get the same pair sent in the url, the last pair of the data.
To simplify the issue:

Steps:

  1. Map function to display data
  2. Pair attribute is sent in the link to get image with every map function (click button to see image)
  3. Pair function also displayed in the table

Result:

  1. The pair in the table is unique and displaying correctly
  2. All urls in the map function get the same pair, the pair of the last object.

Code snippet

 {data.map((trade) => (
            <tr>
              <td>
                <div style={{ display: "flex" }}>
                  <img
                    src={trade.image}
                    style={{
                      width: "30px",
                      height: "30px",
                      marginTop: "13px",
                      marginRight: "5px",
                    }}
                    alt="btc"
                  />
                  <p className="coin-name">{trade.symbol.baseAsset}</p>
                </div>
              </td>
              <td>{trade.symbol.symbol}</td>
              <td>{trade.qty}</td>

              <td>{Math.round(trade.multiplier)}x avg volume</td>

              <td>{trade.price}</td>
              <td>{trade.exchangeDetails.name.toUpperCase()}</td>
              <td>{Math.round(trade.tradeValue * 1000) / 1000}</td>
              <td>
                <div>
                  <Button
                    onClick={handleOpen}
                    style={{ backgroundColor: "#142F37 ", color: "white" }}
                  >
                    View Graph
                  </Button>
                  <Modal
                    open={open}
                    onClose={handleClose}
                    aria-labelledby="modal-modal-title"
                    aria-describedby="modal-modal-description"
                  >
                    <Box sx={style}>
                      <img
                        src={`https://2zpbbz.chart-img.com/v1/tradingview/advanced-chart?symbol=${trade.symbol.symbol}`}
                        alt="No graph for this pair"
                        style={{ width: "500px" }}
                      />
                    </Box>
                  </Modal>
                </div>
              </td>
            </tr>
          ))}

UI

Get image as array buffer and display

I have written a file to an array buffer and stored on IPFS. At another point I wish to pull this buffer from IPFS and have the image displayed on the page. I am struggling with this as the blob does not seem to be located.

Adding photo as array buffer:

// Read photo
let photoFile = e.target.photo.files[0];
let reader = new window.FileReader();
let that = this;
reader.onloadend = function (e) {
  let res = reader.result;
  that.setState({photoString: res});
}

if (photoFile) {
  await reader.readAsArrayBuffer(photoFile);
}

// Add photo to IPFS
await ipfs.add(photoFile).then(async (result, error) => {
  let photoHash = result.path;
  if (error) {
    console.error(error)
  }
});

When trying to get from IPFS and display:

let holderPhoto = await $.get(`https://ipfs.infura.io/ipfs/${IPFSPhotoHash}`);
    const blob = new Blob( [ holderPhoto ] );
    const url = URL.createObjectURL( blob );
    const img = document.getElementById( 'photo' );
    img.image = require(url);
    img.onload = e => URL.revokeObjectURL( url );


<CardMedia id="photo" component="img" height="420" alt="Licence Photo"/>

Error:
components sync:2 Uncaught (in promise) Error: Cannot find module ‘blob:http://localhost:3000/ff4f9e6a-7fae-4cc2-93b3-a6234719c87f’

How to remove any text inside parentheses in a text node in a dynamically created iframe list called in a Bootstrap modal?

So I have a bootstrap modal that calls a .html file in an iframe (my .html file on the same domain) that always produces a different result which is what I need. However the contents generated in the list always creates a text node inside each li of the list containing text wrapped in parentheses. I want to keep all the text that is not inside the parentheses, but remove ANY text that appears inside parentheses ().

So my modal is called here:

<div class="modal-body"><iframe id="researchiframe" name="display-frame" style="width:100%;height:600px;"></iframe></div>

Then it loads my .html file into the iframe and displays the information I want in a list.

<div class="row">
<div class="col-lg-8 offset-lg-3" id="research_result">
<h4 id="research_result_title">Details</h4>

<center>
<ul id="research_result_details" style="padding:0px">
// text I want to remove appears in here //
</ul>
</center>

The list that it generates comes out like this…

<li><h5 class="title" style="display:inline-block;">My Title</h5>:These are the results I want to keep (Theses are the results I want to remove)</li>

So inside the li it creates text that I want to keep, and also text inside (parentheses) I want to remove.

Any help with this is greatly appreciated.