Fetching products from more bases(axios, nodejs)

This is my codeHello guys. I have a project that I have to finish in 3 days. My problem is when adding products to the cart, I have to fetch products from three different bases, while I only do fetching products from one base. How can I do that, please help. My code: const {data} = await axios.get(‘/api/products/${id}’); And this works but just from this base, i was trying const {data} = await axios.get(‘/api/products/${id}’ || ‘/api/felnes/${id}’ || ‘/api/primes/${id}’); but this doesn’t worked. to mention the variable must only be {data}, because otherwise I get an error id is undefined. I’m new in react.

Cropping the relevant part of the browser window after identifying the location of the interested element

I have a webpage where I’ve embedded a YouTube video in an iframe. I need to capture the screenshot of the YouTube video. Using libraries like html2canvas and dom2image didn’t work because of cross-domain limitations.

So, I came up with the idea of capturing the screenshot of the full browser window using getDisplayMedia() and then cropping the relevant part using drawImage(). In my head, it seems to make complete sense, just identifying the location of the iframe and then using drawImage to crop it. However, it does not crop the relevant part in all screen sizes. When I change screen resolution or zoom in, it seems to break.

Another idea would be to write an AI algorithm to capture this. But I think that is an overkill. Any ideas on how to make it work for all screen sizes and resolutions?

<h1>Hello</h1>
<div style="margin: 10;">
    <iframe 
        id="youtubeiframe" 
        width="640" 
        height="340" 
        src="https://www.youtube.com/embed/vDYP6AKw8bk?controls=0" 
        title="YouTube video player" frameborder="0" 
        allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" 
        allowfullscreen>
    </iframe>
</div>
<div id="picture" style="margin-top:60; background-color:'gray'"></div> 

<script>
        navigator.mediaDevices.getDisplayMedia({ preferCurrentTab: true }).then(stream => {
        captureStream = stream;
        track = captureStream.getVideoTracks()[0];
        const canvas = document.createElement("canvas");
        const context = canvas.getContext("2d");
        const offsets = document.getElementById("youtubeiframe")?.getBoundingClientRect();
        const posX = offsets.left;
        const posY = offsets.top;
        const width = offsets.width;
        const height = offsets.height;
        canvas.width = width;
        canvas.height = height;

        let image = new ImageCapture(track);
        const bitmap = image.grabFrame().then(bitmap => {
            context?.drawImage(bitmap, posX, posY, width, height, 0, 0, width, height);
            const pic = document.getElementById("picture");
            if(pic.childElementCount > 0)
                pic.replaceChild(canvas,pic.children[0]);
            else
                pic.appendChild(canvas);
        });
        
    });
    
</script>

how to remove an array item from firestore using JavaScript?

I’m trying to add a delete button to my page. the event listener callback is working properly except for the updateDoc function.

await updateDoc(doc(dataBase, 'users', `${auth.currentUser.uid}`), {
     [`${col}.books`]: arrayRemove(`${bookToDelete}`)
}).then(()=>{
      // fulfilled
      console.log('book deleted')
      }, ()=>{
      // rejected
      console.log('promis rejected')
})   

Col is the object that contains the books array. In the console it always prints book deleted, but in the firestore console, nothing changes. this is a screenshot of the database.enter image description here

I would really appreciate any help and thank you.

Using Place Autocomplete API to get Address Components

I am trying to to have a form that uses the Google Autocomplete API to populate a bunch of text fields after they click the name of the establishment. I am not super familiar with Javascript, so this one is somewhat of a struggle for me.

As is, I am currently getting it to populate the Name into the input box and the latitude and longitude. But everything else (address, address2, city, state) gets populated with “undefined”. Any ideas on how to get those values to populate into those input fields.

<html>
<head>
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=API&libraries=places"></script>
    <script>
        function initialize() {
          var input = document.getElementById('searchTextField');
          const options = {
          componentRestrictions: { country: "us" },
          fields: ["address_components", "geometry", "icon", "name"],
          strictBounds: false,
          types: ["establishment"],
          };
          var autocomplete = new google.maps.places.Autocomplete(input, options);
            google.maps.event.addListener(autocomplete, 'place_changed', function () {
                var place = autocomplete.getPlace();
                document.getElementById('locationName').value = place.name;
                document.getElementById('addr').value = place.adr_address;
                document.getElementById('addr2').value = place.address2;
                document.getElementById('city').value = place.city;
                document.getElementById('state').value = place.state;
                document.getElementById('lat').value = place.geometry.location.lat();
                document.getElementById('long').value = place.geometry.location.lng();
            });
        }
        google.maps.event.addDomListener(window, 'load', initialize);
    </script>
</head>
<body>
    <input id="searchTextField" type="text" size="50" placeholder="Enter a location" autocomplete="on" runat="server" />

    <input type="text" id="locationName" name="locationName" />
    <input type="text" id="addr" name="addr" />
    <input type="text" id="addr2" name="addr2" />
    <input type="text" id="city" name="city" />
    <input type="text" id="state" name="state" />
    <input type="hidden" id="lat" name="lat" />
    <input type="hidden" id="long" name="long" />

</body>
</html>

React play different audio files at once – working with different refs

I’m creating a small app that plays an audio file and have some functionalities (loop, stop, mute). My goal is to add some more audio files that all should be played and stopped at once (one button to control all), but each will have a mute button, and I’m not sure what is the best practice to do so. I used useRef and thought maybe I need to set a refs array but how will I be able to start/stop them all at once, but still have the ability to control the mute separately?

This is my code so far. I guess I should split and have a different component for the audio sounds. Thanks for helping!

import React, {useState, useRef, useEffect} from 'react'
import {ImPlay2} from "react-icons/im"
import {ImStop} from "react-icons/im"
import styled from "styled-components"
import drums from '../loopfiles/DRUMS.mp3'
//import other audio files//

const AudioPlayer = () => {
    const [isPlaying, setIsPlaying] = useState(false);
    const [isLooping, setIsLooping] = useState(false);
    const [isOnMute, setIsOnMute] = useState(false);
    const audioRef = useRef(new Audio(drums));
  
    useEffect(() => {
        if (isOnMute) {
            audioRef.current.volume=0;
        } 
        else {
            audioRef.current.volume=1;
        }
      }, [isOnMute]);
    useEffect(() => {
        if (isPlaying) {
            audioRef.current.play();
        } else {
            audioRef.current.pause();
            audioRef.current.load();
        }
      }, [isPlaying]);
      useEffect(() => {
        if (isLooping) {
            audioRef.current.loop = true;
        } else {
            audioRef.current.loop = false;
        }
      }, [isLooping]);
  return (
    <div> 
        {!isPlaying ? (
        <button type="button" 
        className="play" 
        onClick={() => setIsPlaying(true)}> 
        <ImPlay2></ImPlay2> Play 
        </button>
        ) : (
        <button type="button"
        className="pause"
        onClick={() => setIsPlaying(false)}> 
        <ImStop></ImStop> Stop 
        </button> 
        )}
        <Flex>
            <Switcher selected={isLooping} />
            <Text
            onClick={() => setIsLooping(true)}>
            Loop
            </Text>
            <Text
            onClick={() => setIsLooping(false)}>
            Unloop
            </Text>
        </Flex>
        <Flex>
            <Switcher selected={isOnMute} />
            <Text
            onClick={() => setIsOnMute(true)}>
            Mute
            </Text>
            <Text
            onClick={() => setIsOnMute(false)}>
            UnMute
            </Text>
        </Flex>
    
  

      
            
    </div>
  )
}
const Flex = styled.div`
  margin-top: 5px;
  display: flex;
  align-items: center;
  border-radius: 2px;
  background: grey;
  height: 20px;
  width: 120px;
  position: relative;
  margin-bottom: 5px;
`;
const Switcher = styled.div`
  background: black;
  border-radius: 2px;
  height: 20px;
  line-height: 41px;
  width: 50%;
  cursor: pointer;
  position: absolute;
  transition: 0.5s;
  -webkit-transition: 0.5s;
  -moz-transition: 0.5s;
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.16);
  z-index: 1;
  left: ${({ selected }) =>
    selected === true ? "0px" : "60px"};
`;

const Text = styled.div`
  color: ${({ selected }) => (selected ? "black" : "white")};
  font-size: 13px;
  font-weight: 20;
  line-height: 4px;
  padding: 30;
  width: 50%;
  text-align: center;
  cursor: pointer;
`;
export default AudioPlayer

PayPal JavaScript SDK button opens about:blank#blocked window in Django template but not in local HTML file

I’ve been trying to integrate PayPal buttons on my Django website, but I keep having this problem where the PayPal popup window appears as about:blank#blocked. I can see this error in console:

popup_open_error_iframe_fallback 
{err: 'n: Can not open popup window - blockedn    at Ie (…owser=false&allowBillingPayments=true:1342:297830', timestamp: '1644780862712', referer: 'www.sandbox.paypal.com', sdkCorrelationID: 'f12370135a997', sessionID: 'uid_d36969c1b2_mtk6mja6mzy', …}

What I don’t understand is that the problem isn’t there if I just open the HTML file itself in a browser… The script looks like this:

<!-- Set up a container element for the button -->
<div id="paypal-button-container" class='text-center mt-2'></div>

<!-- Include the PayPal JavaScript SDK -->
<script src="https://www.paypal.com/sdk/js?client-id=blahblahmyid&currency=EUR"></script>

<script>
    // Render the PayPal button into #paypal-button-container
    paypal.Buttons({
        locale: 'it_IT',
        style: {
            color: 'gold',
            shape: 'rect',
            layout: 'vertical',
            label: 'pay'
        },

        // Set up the transaction
        createOrder: function(data, actions) {
            return actions.order.create({
                purchase_units: [{
                    amount: {
                        value: '88.44'
                    }
                }]
            });
        },

        // Finalize the transaction
        onApprove: function(data, actions) {
            return actions.order.capture().then(function(orderData) {
                // Successful capture! For demo purposes:
                console.log('Capture result', orderData, JSON.stringify(orderData, null, 2));
                var transaction = orderData.purchase_units[0].payments.captures[0];
                alert('Transaction '+ transaction.status + ': ' + transaction.id + 'nnSee console for all available details');

                // Replace the above to show a success message within this page, e.g.
                // const element = document.getElementById('paypal-button-container');
                // element.innerHTML = '';
                // element.innerHTML = '<h3>Thank you for your payment!</h3>';
                // Or go to another URL:  actions.redirect('thank_you.html');
            });
        }


    }).render('#paypal-button-container');
</script>

What’s the problem ? I don’t understand.

Built-in Constructors and their Prototype —

The activity was to Log Array.prototype and Object.prototype to the console using only the arr variable and the proto property.

So these are the original code:

const arr = [1, 2, 3];

console.log(); // log the Array.prototype
console.log(); // log the Object.prototype

So What I did: I wrote on the first, console.log(arr.__proto__ === Array.prototype);
the second one is, console.log(arr.__proto__ === Object.prototype); but still not right.
It says that in the first log, the Array.prototype is the proto property of any array. the next one, the prototype property of Array.prototype refers to the object.prototype. I can’t figure it out what does it meant. I tried also writing like this: console.log(arr.__proto__ === Object.prototype); still not right. What am I missing here?

Knexjs how to handle multiple updates

I´m quite unsure on how to handle multiple updates / inserts in knex and return whatever it was successfull on the end or not.

I´m passing an array through req.body loop through it and trigger actions based on informations inside the array.

Example:

const data = [...req.body]
for(let i = 0; i < data.length; i++) {
        data[i].totals.length
        for(let y = 0; y < data[i].totals.length; y++) {
            if(data[i].totals[y].info === "Holiday") {
                calcHoliday(data[i].totals[y].total, data[i].id)
            } else if(data[i].totals[y].info === "ZA") {
                calcZA(data[i].totals[y].total, data[i].id)
            }
        }
        calcOvertime(data[i].totalSum, data[i].id)

        if(i === data.length -1) {
            res.json("Success")
        }
    }

The Array I´m passing in looks like this:

[
    {
    "id": 1,
    "totals": [
        {
            "info": "Holiday",
            "total": 4
        }
    ]
    },
    {
    "id": 1,
    "totals": [
        {
            "info": "Holiday",
            "total": 4
        }
    ]
    }
]

Function Example which gets called in for loop:

const calcHoliday = (hours, userid) => {
        knex.transaction(trx => {
            trx.insert({
                created_at: convertedTime,
                info: "Booking Holiday - Hours: " + hours,
                statuscode: 200
            }).into("logs")
                .then(() => {
                    return trx("hours")
                        .decrement("holiday_hours", hours)
                }).then(trx.commit)
                .catch(trx.rollback)
        }).then(() => console.log("WORKED"))
            .catch(err => console.log(err))
}

This is working perfectly fine but I can´t figure out how to gather the results from each table update in order to respond if everything worked or an error appeared. If I call e.g. after one calcHoliday call .then(resp => res.json(resp) I receive only the response from the first operation.

In short I need a way on how to res.json if everything succeeded or an error appeared somewhere.

Thanks in advance!

Adding a circle element on multi-line chart for each datapoint D3 JS

I have the following code and am looking to add a circle element for each data point, however, am getting the error:

Error: attribute cx: Expected length, “NaN”.

Any help is greatly appreciated!

  var w = 960;
  var h = 500;
  var margin = { top: 75, right: 75, bottom: 75, left: 75 };
  var width = w - margin.left - margin.right,
      height = h - margin.top - margin.bottom;

// append svg element to the body of the page
// set dimensions and position of the svg element
  var svg = d3.select("body").append("svg")
      .attr("id", "line_chart")
      .attr("width", w)
      .attr("height", h);
  var container = svg.append("g")
      .attr("id", "container")
      .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

d3.dsv(",", pathToCsv, function (d) {
      if (+d.year >= 2015 && +d.year <= 2019) {
          return {
              name: d.name,
              year: +d.year,
              rating: Math.floor(+d["average_rating"]),
              users: +d["users_rated"]
          }
      }
  }).then(function (data) {
      console.log(data);
  
  // Define x axis scale for line chart
      var xScale = d3.scaleLinear()
          .domain([0, d3.max(data, function (d) { return d.rating; })])
          .range([0, width]);
      var xAxis = d3.axisBottom(xScale)
            .ticks(10);

      var yScale = d3.scaleLinear()
          .domain([0, d3.max(filtered_data[2], function (d) { return d.count; })])
          range([height, 0]);
      var yAxis = d3.axisLeft(yScale);
      y_axis.call(yAxis);

      // d3's line generator
      var line = d3.line()
          .x(function (d) { return xScale(d.rating); })
          .y(function (d) { return yScale(d.count); })

      // colors list
      var colors = ["#1f77b4", "#ff7f0e", "#17becf", "#bcbd22", "#bcbd22"];

      // Add each line to line chart
      lines.selectAll("line-paths")
          .data(filtered_data)
          .enter()
          .append("path")
          .attr("d", function (d) { return line(d); })
          .style("fill", "none")
          .style("stroke", function (d, i) { return colors[i]; });

      circles.selectAll("line-circles")
              .data(filtered_data)
              .enter()
              .append("circle")
              .attr("cx", function (d) { return xScale(d.rating); })
              .attr("cy", function (d) { return yScale(d.count); })
              .attr("r", 3);

For reference, my data is formatted as follows:

Data Setup

so essentially its a nested array with 5 lines and need to append 50 total elements.

How to correctly call a function from Node.JS to Express.JS

I have a completed script that acts as a parser. The script is written in NodeJS and it works properly. The script returns an array of data and also saves it to my computer.
I would like to run this script from the frontend, at the click of a button. As far as I understand, I have to send a request to the server? It’s suggested to use Express for the server, but I still haven’t figured out how to call a third-party script from it, much less return any data from it.
Right now all I want is for my script to run when I make a request for the root directory “/” and send me a json in response (or for example a json file)

const express = require('express')
const runParser = require("./parser");
const app = express()
const port = 3000

const  doParse=async(req,res,next)=>{
   await runParser()
}

app.get('/', async (req, res,next) => {
  await doParse(req,res)
    next()
})

app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
})

how to change my icon layout to flex on css

I’m trying to change my icons to flex but that didn’t work. This was my original CSS code:

.recipe-icons {
  display: grid;
  grid-template-columns: repeat(3, 1fr); 
  gap: 1rem;
  margin: 2rem 0;
  text-align: center;
}

I also tried setting display to flex, justify-content to center and all that but that didn’t work either. How can I fix this? This is my html code for my icons:

div class="recipe-icons">
            <article>
              <!-- single recipe icon -->
              <i class="fas fa-clock"></i>
              <h5>prep time</h5>
              <p>30 min.</p>
              <!-- single recipe icon -->
              <i class="far fa-clock"></i>
              <h5>cook time</h5>
              <p>15 min.</p>
              <!-- single recipe icon -->
              <i class="fas fa-user-friends"></i>
              <h5>servings</h5>
              <p>6 servings</p>
              <!-- recipe tags -->
              <div class="recipe-tags">
                Tags: <a href="tag-template.html">beef</a>
                <a href="tag-template.html">breakfast</a>
                <a href="tag-template.html">pancakes</a>
                <a href="tag-template.html">food</a>
              </div>
            </article>
</div>

How to wait until navigator.notification.prompt() input has been given

I am using a Cordova app to embed a React app. In a certain point, the user connects to the camera and a notification appears when a QR code is detected. I want that the code execution waits until user has entered his/her answer “Yes/No”, but I can’t get it to work. Notification prompt message works as expected though.

I need it to pause somehow, as in an async function (like prompt would, for instance). How could I pause the code execution until the user has chosen Yes/No in screen? I guess with some async/await but don’t see where… I have tried unsuccessfully so far:

let test = null;
let input2 = null;
notification = navigator.notification.prompt("Do you know this QR code?",
     async function(input) {
     input2 = input;
     test = await NotificationFunction(input, Camera_content);
     console.log(test)
     console.log('input2')
     return [test, input2]
     });

let test2= await notification
console.log(test2)
console.log(notification)
console.log(await test)

Thanks a lot in advance!

Retrieve a repeating person’s name in array of string

Everyone!
I’m currently working on the project where I should merge some pdf files into one using Laravel.
I receive response from Airtable response.
The main thing is that after merging pdf files I’m gonna set a name of merged pdf file.
For example, I have to merge these files:

0:"D:DevelopmentsAirtablePDFCombinerairtable-pdf-combinerstorageapp/pdf_filesSalvageQuoteSummaryreportChristenPretrick.pdf"
1:"D:DevelopmentsAirtablePDFCombinerairtable-pdf-combinerstorageapp/pdf_filesSummaryReportChristenPretrick.pdf"
2:"D:DevelopmentsAirtablePDFCombinerairtable-pdf-combinerstorageapp/pdf_filesEstimateChristenPretrick.pdf"
3:"D:DevelopmentsAirtablePDFCombinerairtable-pdf-combinerstorageapp/pdf_filesPhotoSheetChristenPretrick.pdf"
4:"D:DevelopmentsAirtablePDFCombinerairtable-pdf-combinerstorageapp/pdf_filesComp26700.00.pdf"
5:"D:DevelopmentsAirtablePDFCombinerairtable-pdf-combinerstorageapp/pdf_filesComp26888.00.pdf"
6:"D:DevelopmentsAirtablePDFCombinerairtable-pdf-combinerstorageapp/pdf_filesComp27991.00.pdf"
7:"D:DevelopmentsAirtablePDFCombinerairtable-pdf-combinerstorageapp/pdf_filesNADA.pdf"

As you see, in first three files there is a name of person: “ChristenPretrick”, which should be a name of the merged pdf file.

But how to get only this name in this array using the Laravel Controller.
Please leave me feedback, will be extremely appreciated to your answer.
Best Regards.