Odering a list of integers in javascript?

arr is an array of integers. There are no repeating integers in arr. A function f(x,y) acting on two elements in the list moves x to y’s position and y to x’s position. Find out the least number of times you can call f so that the resulting array is in ascending order. Input Format
The first line of input is an integer n which Is the length of the array The second line is a list of space-separated integers. Input Constraints
There will be at least one integer in the array. Output Format
An integer which represents the minimum number of swaps to be made. Using javascript. Example, input 4 2854 output 1. If we swap 8 with 4, the array is sorted. so the output is 1

`function solution(n, arr) {
  let swaps = 0;
  let visited = new Array(n).fill(false);

  for (let i = 0; i < n; i++) {
    if (visited[i] || arr[i] === i + 1) continue;

    let cycleSize = 0;
    let j = i;

    while (!visited[j]) {
      visited[j] = true;
      cycleSize++;
      j = arr[j] - 1;
    }

    swaps += (cycleSize - 1);
  }

  return swaps;
}
`your text``

How Can I Add A Cover Image To My QR Code Maker

I want to add a 150 by 100 centered cover image that is automatically part of the qr codes when creating the qr codes. How can I do that. I have the qr code maker in a CodePen. Thanks!

I simply edited the qr code maker in a somewhat unique way, and when testing, the qr code maker is running. However, I currently don’t know to include a centered custom cover image in the qr code images. Thanks!

text

`<div class="qrcode-form">
    
  <p><b>NON TRACKING<br>QR CODE MAKER</b></p>
  
  <form>
    <input type="url" id="website" name="website" placeholder="https://YourURL.com" autocomplete="off" required />
    <button type="button" onclick="generateQRCode()">
      Generate QR Code
    </button>
  </form>

  <div id="qrcode-container">
  
    <img style="margin-top: 30px;" class="bounce animated infinite" src="Q-R-Arrow-Down.svg" height="32" alt="Scroll Down" title="Scroll Down">
      
    <h4 style="color: #000">DEFAULT COLOR 250 By 250</h4>
    <div id="qrcode" class="qrcode"></div>
    
    <img style="margin-top: 30px;" class="bounce animated infinite" src="Q-R-Arrow-Down.svg" height="32" alt="Scroll Down" title="Scroll Down">
    
    <h4 style="color: #4169E1">ROYAL BLUE 250 By 250</h4>
    <div id="qrcode-royal-blue" class="qrcode cover-image"></div>
    
    <img style="margin-top: 30px;" class="bounce animated infinite" src="Q-R-Arrow-Down.svg" height="32" alt="Scroll Down" title="Scroll Down">
    
    <h4 style="color: #663399">ROYAL PURPLE 250 By 250</h4>
    <div id="qrcode-royal-purple" class="qrcode"></div>
    
    <img style="margin-top: 30px;" class="bounce animated infinite" src="Q-R-Arrow-Down.svg" height="32" alt="Scroll Down" title="Scroll Down">
    
    <h4 style="color: #228B22">FOREST GREEN 250 By 250</h4>
    <div id="qrcode-forest-green" class="qrcode"></div>
    
    <img style="margin-top: 30px;" class="bounce animated infinite" src="Q-R-Arrow-Down.svg" height="32" alt="Scroll Down" title="Scroll Down">
    
    <h4 style="color: #A52A2A">BROWN 250 By 250</h4>
    <div id="qrcode-brown" class="qrcode"></div>
    
  </div> </div>
  
  <div class="qrcode-info">1) Enter https://DomainName.com, TEL: 777-777-777, SMS: 777-777-7777, Or TEXT; 2) Click The Generate QR Code Button; 3) Scroll Down To Pick Your Preferred Color;
  4) DownLoad The QR Code PNG Image.<br><br>The ROYAL QR Code Maker DOESN'T Use Any Trackers!</div>

  <script>
    function generateQRCode() {
      let website = document.getElementById("website").value;
      if (website) {
          
        let qrcodeContainer = document.getElementById("qrcode");
        qrcodeContainer.innerHTML = "";
        new QRCode(qrcodeContainer, website);
        
        /*With Some CSS*/
        let qrcodeContainer2 = document.getElementById("qrcode-royal-blue");
        qrcodeContainer2.innerHTML = "";
        new QRCode(qrcodeContainer2, {
          text: website,
          width: 250,
          height: 250,
          colorDark: "#4169E1",
          colorLight: "#FFF",
          correctLevel: QRCode.CorrectLevel.H
        });
        
        /*With Some CSS*/
        let qrcodeContainer3 = document.getElementById("qrcode-royal-purple");
        qrcodeContainer3.innerHTML = "";
        new QRCode(qrcodeContainer3, {
          text: website,
          width: 250,
          height: 250,
          colorDark: "#663399",
          colorLight: "#FFF",
          correctLevel: QRCode.CorrectLevel.H
        });
        
        /*With Some CSS*/
        let qrcodeContainer4 = document.getElementById("qrcode-forest-green");
        qrcodeContainer4.innerHTML = "";
        new QRCode(qrcodeContainer4, {
          text: website,
          width: 250,
          height: 250,
          colorDark: "#228B22",
          colorLight: "#FFF",
          correctLevel: QRCode.CorrectLevel.H
        });
        
        /*With Some CSS*/
        let qrcodeContainer5 = document.getElementById("qrcode-brown");
        qrcodeContainer5.innerHTML = "";
        new QRCode(qrcodeContainer5, {
          text: website,
          width: 250,
          height: 250,
          colorDark: "#A52A2A",
          colorLight: "#FFF",
          correctLevel: QRCode.CorrectLevel.H
        });
        
        document.getElementById("qrcode-container").style.display = "block";
      } else {
        alert("Please Enter a VALID URL, PHONE NUMBER, SMS NUMBER, Or TEXT!");
      }
    }
  </script>`

How to become a backend developmer [closed]

I want to become back end immediately

I am teaching the basics of front end, then how to become back end immediately, I expect I can intensive toturial become back end developer I
I am teaching the basics of front end, then how to become back end later
Is it true that it is very difficult to become a backend?

Is it possible to get a boolean return value when using set.add() in JavaScript?

I am using a loop to add to a Set in JavaScript. Something like:

let mySet = new Set();

$('li').each(function() {
  mySet.add($(this).text());
})

This works fine. However, I wanted to see if I could leverage .add() to tell me if the item was successfully added or not, without iterating through the set looking for a match again.

Does anyone know if this is possible?

How to change vuetify expansion panel animation

I’m currently using Vuetify with chart.js I tried to implement a chart.js inside a v-expansion-panel :

          <v-expansion-panels class="my-4" variant="popout">
            <v-expansion-panel title="Item">
              <v-expansion-panel-text>
                <TrajectoryChart :trajectory="coloredLines"></TrajectoryChart>
              </v-expansion-panel-text>
            </v-expansion-panel>
          </v-expansion-panels>

But both animations are not working good together, I would like both animations working smoothly without any latency. I would like to change v-expansion-panel animation’s behavior to not wait for his content to load to expand

Expansion not working

I’ve added a timeout to display my graph after 300ms which remove the latency

<template>
  <div v-if="showChart" id="chart-container" class="rounded pa-2 w-100">
    <canvas ref="chartCanvas"></canvas>
  </div>
  <div id="chart-container-substitute"></div>
</template>

... 

onMounted(async () => {
  showChart.value = true;
  await nextTick();
  setTimeout(() => {
    createChart();
  }, 300);
});

But the expansion is still done in two times but instead of this mini-useless first expansion :

First useless expansion animation

I would prefer that the expansion is done completly in one time.

Any idea how to solve this ?

How to allow users to preview website template responsively before downloading in laravel?

Hello everyone i’m building a website using laravel framework where users can download templates and themes that suits their needs.

I wan’t to implement a feature where users can preview templates or themes responsively (desktop, mobile and tablet ) before downloading them

What techniques or tools are suitable to achieve this? Any example or recomendations like preview feature on

https://startbootstrap.com/previews/freelancer#google_vignette ,would be appreciated

Thanks in advance

How to update a field in React Hook Form based on other fields’ values?

I’m using React Hook Form and have three input fields in a form: a start date, an end date, and a third field that shows the number of nights between the two dates (night difference). I want to update the night difference field whenever the start date or end date fields change. I’m working on the form for booking a vacation by employee, night duration is calculated automatic and also for informational purposes for employee.

I wonder is there a way too not using onChange but inside place the code inside {…register, {…HERE…}}

This is my solution https://codesandbox.io/p/sandbox/chz4z8.

OCR From

What I want to do is use

 <input type="file" id="file" name="file" accept="image/jpeg,image/jpe,image/jpg,image/png,image/bmp">

To use the camera from the device or select some picture/image, happens when this happens automatically apply OCR and extract the text from the picture/image and put this text on a <input type="text">.

Is this possible to use just JavaScript or some library.js? I know that it is possible to use back end technology, but if it is possible to do this on the front end with JS that would be perfect.

Dynamically resizing the Gallery Block Container in Squarespace so all images are the same size despite their orientation

So my goal is to have all my images display as the same size, i.e., if a horizontal image is 1300x1000px, then the vertical images in the gallery should be 1000x1300px. As it is now, the gallery-container has a static size based off the widest width image and that images height, it does not seem to incorporate the tallest images height. This results in a gallery where the horizontal images are larger than the vertical images, i.e., 1300x1000px for horizontals and 800x1000px for verticals.

I’ve tried a ton of different CSS approaches and feel that I really am at a place where Javascript is required to achieve this behavior from the gallery-container.

Thanks for helping!

What is the correct way of handling forms in Nextjs (or other server side rendering react frameworks)?

I have a large form in my Next.js app. I use react-hook-form and zod for managing state of the form and validation.

But this entire form is a separate page. And to make it possible to use react-hook-form hooks I need to use ‘use client’ directive which makes my entire component with the form a client component.

The question is how can I get benefits from Next.js + SSR for similar cases? Or it is fine to make entire page client component?

It also worth mentioning that I have a lot of UI components wrapped in react-hook-form’s <Controller> cuz I need to manually set values and trigger validation in some cases.

Is there any way to utilize SSR in similar cases?

FileSaver saveAs function does not download all the files using Promise.allSettled

I have a TypeScript function that tries to download a large number of small documents concurrently. Here’s the code:

const bulkDownload = async (analyses: FullAnalysesResponse[]) => {
  setIsLoading(true);

  const promises = analyses.map(async (analysis) => {
    const documentInfo = await getDocumentInfo({ documentId: analysis.downloadFileId! });
    const attachment = await downloadDocument({ documentId: analysis.downloadFileId! });
    FileSaver.saveAs(new File([attachment], documentInfo.name, { type: documentInfo.mimeType }));
  });

  const results = await Promise.allSettled(promises);

  setIsLoading(false);

  results.forEach((result, index) => {
    const analysisSerialNumber = analyses[index].deviceSerialNumber;
    result.status === 'fulfilled'
      ? successfulQueries.push(analysisSerialNumber)
      : failedQueries.push(analysisSerialNumber);
  });

  return { failedQueries, successfulQueries };
};

The issue is that when I trigger this function to download multiple files at once, not all the files are downloaded. The number of downloaded files changes every time I run the function, and I never get all the files. All the API calls are working, so all the promises are successful. The issue seems to come from the FileSaver.saveAs function.

I also tried a version that uses a simple for...of loop, which works fine:

const bulkDownload = async (analyses: FullAnalysesResponse[]) => {
  setIsLoading(true);
  
  const successfulQueries: string[] = [];
  const failedQueries: string[] = [];

  for (const analysis of analyses) {
    try {
      const documentInfo = await getDocumentInfo({ documentId: analysis.downloadFileId! });
      const attachment = await downloadDocument({ documentId: analysis.downloadFileId! });
      FileSaver.saveAs(new File([attachment], documentInfo.name, { type: documentInfo.mimeType }));
      successfulQueries.push(analysis.deviceSerialNumber);
    } catch (error) {
      failedQueries.push(analysis.deviceSerialNumber);
    }
  }

  setIsLoading(false);

  return { failedQueries, successfulQueries };
};

The for...of version works reliably but is slower since it downloads the files sequentially. I would like to understand why the first (concurrent) function is not working as expected. I assumed that running the downloads concurrently would be more efficient.

Any insights on why this happens, and how to fix it while keeping the performance benefits of concurrent downloads?

How to merge two PDF files without leaving blank spaces between its content

I need to merge two pdf files, in my case, the second must start where the first ends. I mean, it can not exist blank spaces between the content of the two files. At this time i can merge it but the content of the second starts on a new page

const newPdfDoc = await PDFDocument.load(newPdfArrayBuffer);
    for (let i = 0; i < newPdfDoc.getPageCount(); i++) {
    const [newPage] = await pdfDoc.copyPages(newPdfDoc, [i]);
        //...
        //. some stuff like scale, setFonts, fontSizes, etc 
        //...
    }
    pdfDoc.addPage(newPage);

How to deal with image that tries to render out of bounds in a magnifier

I am using a modified version of this w3schools tutorial for a magnifying glass W3Schools. I’m trying to make my glass as functional as possible, dealing with it being able to render even on the furthest edges of my image.

Unfortunately I’m having an issue with the top and left edges “freezing” the glass whenever the edge of the glass reaches the edge of the image. This is most likely due to the glass rendering the image from the top left corner, creating the problem of trying to render part of an image that doesn’t actually exist.

My question is how can I get my glass to render the zoomed image all the way up to the edges of the image, while still keeping the glass centered over my cursor. I want the overflow to smoothly be able to hide outside of the image, without constraining the glass at all within the image itself.

I attached the full code here: FullFiddle and a testable example here: TestFiddle (may have to press run again to get the glass to update properly). Notice how the top and left edges don’t magnify properly all the way to the edge while the bottom and right edges do. Let me know if theres any other questions.

    // The moveMagnifier function sets the position of the glass to the position of the cursor
    function moveMagnifier(e) {
         e.preventDefault();

         pos = getCursorPos(e); // Calls function to get cursor position
         x = pos.x;
         y = pos.y;

         glass.style.left = `${x - w}px`; // Centers glass position over cursor
         glass.style.top = `${y - h}px`;

         glass.style.backgroundPosition = `-${x * zoom - w}px -${y * zoom - h}px`;
         
         }

     // Function for finding the cursor based on the bounds of the image
     function getCursorPos(e) {
         let xPos = e.clientX - imgRect.left; // Gets cursor position based on image position
         let yPos = e.clientY - imgRect.top;
         return { x: xPos, y: yPos };
         }

TLDR: Magnifying glass is extending out of bounds and want it to be able to handle zooming in on the edges of the image.

P.S: If anyone has a better way to handle hiding the actual overflow of the glass or any other corrections please let me know.

I would assume a solution would be to create an invisible padding of sorts around each image that still allows it to render properly. I don’t know how I would go about that properly though.