I am using JavaScript , I am having problems using template literal

So when I use template literals with statements it doesn’t seem to give me results like my mentor. For example

I need help . Am I not using the right braces or is do I have to install something on vs code to allow the required result show?

let firstname = ‘Akpofure’;
console.log(‘people refer to me by ${firstname}’ ); 

Result should be : people refer to me by Akpofure .
Instead I am getting : people refer to me by ${firstname}

Why is the variable in my code not working? [duplicate]

I am new to React and I was practicing this code but for some reason, the variable that I used in the code i.e., name and count doesn’t seem to work. Kindda sure that if I have to print the name using console.log then I have to write it like —–console.log(‘Hello $(name)’);—–. I have done the same thing with name and count but they are being printed as text instead of variable.

Expected output:

John you have clicked me 2 time/s.

Actual output:

${name} you have clicked me ${count} time/s.

Please tell me how do i Fix this

function Button() {
  let count = 0;

  const handleClick = (name) => {
    if (count < 3) {
      count++;
      console.log('${name} you have clicked me ${count} time/s.');
    } else {
      console.log('${name} stop clicking me!');
    }
  };

  return <button onClick={() => handleClick('John')}>Click Me</button>;
}
export default Button;

Overfetching with prisma, and GraphQL?

As I understand it, beyond describing exactly what your api should look like, GraphQL is also meant to save resources by only returning data that you asked for. But when I write resolvers like this:

    const user = await context.prisma.user.findUnique({
      where: {authProviderId: args.authProviderId},
      include: {
        profile: {
          include: {
            basicInfo: true,
          },
        },
      },
    });

And I only need certain fields returned, doesn’t that negate the whole ressource preservation?

Thanks!

D3 scale works in v6 but not in v7

I have code using d3 v6.7.0 that sets up a scale like so:

const range = [0, 828.156];
const domain = [[300,1],[300,2],[300,3],[400,1],[400,2],[400,3],[400,4]]
const scale = d3.scaleBand()
  .domain(domain)
  .range(range);

// test 1: this works in both v6 and v7
const a = domain[3];
console.log('array a', a);
console.log('scaled a:', scale(a));

// test 2: declaring a new, identical array to the one above, 
// also works in v6
const b = ([400, 1]);
console.log('array b', b);
console.log('scaled b:', scale(b));
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/6.7.0/d3.min.js" integrity="sha512-cd6CHE+XWDQ33ElJqsi0MdNte3S+bQY819f7p3NUHgwQQLXSKjE4cPZTeGNI+vaxZynk1wVU3hoHmow3m089wA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

In d3 v7.9.0, this no longer works:

const range = [0, 828.156];
const domain = [[300,1],[300,2],[300,3],[400,1],[400,2],[400,3],[400,4]]

const scale = d3.scaleBand()
  .domain(domain)
  .range(range);

// test 1: this works in both v6 and v7
const a = domain[3];
console.log('array a', a);
console.log('scaled a:', scale(a));

// test 2:  declaring a new, identical array to the one above, 
// does not work in v7, but it does work in v6
const b = ([400, 1]);
console.log('array b', b);
console.log('scaled b:', scale(b));
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.9.0/d3.min.js" integrity="sha512-vc58qvvBdrDR4etbxMdlTt4GBQk1qjvyORR2nrsPsFPyrs+/u5c3+1Ct6upOgdZoIl7eq6k3a1UPDSNAQi/32A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

Has something changed from v6 to v7, or what am I doing wrong?

Logic for the implementation of “select / unselect” checkbox sequencially in Java script

I have a main JSP Page which shows the Club (lottery) information like Plus icon, Lottery number, lucky number, purchase date, others for the search criteria. This page can have Single club/ Multiple clubs

There is an dynamic jsp page which has been included in the main page which shows the installment details and checkboxes and dynamic jsp code written in Javascript (jsp page get created when we click on PLUS Icon in the main page).
In the dynamic jsp page there are check box which need to be checked/unchecked sequentially by the user.
A validation is needed to be implemented for the above. I have tried multiple logic but its not working.

This code doesn’t work in all condition. For example,
Scenario 1) When uncheck the middle checkbox alert message shown buy checkbox got unchecked.
If fix one issue it creates another issue.

Lastly I have posted here for support. Thanks in Advance.

Javascript Code:

function CheckedOrNot(lotNo, k) {

// here lotNo is the lottery number and k is the position of the checkbox

var checkbox = document.getElementById("chckBox_" + lotNo + "_" + k);

// totalcheckbox is the number of checkboxes for each lottery. Max Value of totalcheckbox  is 24 and minimum is 1)

var totalcheckbox = document.getElementById("totalInstallment_" + lotNo).value;

// in case of first checkbox it should validate lock/unlock of that lottery and do required steps 
if (k == 0) {
    validateLotteryLock(lotNo, checkbox, k);
}

// Sequential checkbox checking validation
for (var i = 0; i < k; i++) {
    var prevCheckbox = document.getElementById("chckBox_" + lotNo + "_" + i);
    if (!prevCheckbox && k !== 1) {
        alert("You haven't paid previous dues. Please select installments sequentially.");
        document.getElementById("chckBox_" + lotNo + "_" + i) = prevCheckbox;
        return false;
    }
}

// If the second installment is checked, prevent unchecking the first installment
if (k == 1 && checkbox) {
    var firstCheckbox = document.getElementById("chckBox_" + lotNo + "_0");
    var firstCheckboxVal = firstCheckbox.checked;
    if (firstCheckboxVal && !checkbox) {
        alert("You cannot uncheck the first installment while the second installment is checked.");
        firstCheckbox.checked = true; // Revert the first checkbox state back to checked
        return false; // Stop further execution
    }
}

// Display alert if checkbox is unchecked without paying previous dues
if (!checkbox) {
    alert("You have unpaid previous dues. Please pay previous installments before selecting the current one.");
    return false; // Stop further execution
}

var checkboxTrueResult = 0;
var checkboxFalseResult = 0;
for (var i = totalcheckbox; i > 0; i--) {
   var prevCheckbox = document.getElementById("chckBox_" + lotNo + "_" + i);
   
   if (prevCheckbox) {
        //alert("prevCheckbox is true");
        checkboxTrueResult = checkboxTrueResult + 1;
   }
   
   if (!prevCheckbox) {
        checkboxFalseResult = checkboxFalseResult + 1;
        //alert("prevCheckbox is false");
   }
}
   
   if (checkboxTrueResult > 0 && checkboxFalseResult == 0) {
        alert("1");
   }
   
   if (checkboxFalseResult > 0 && checkboxTrueResult == 0) {
        alert("2");
   }
// Calculate total amount for the selected installment
calculateClubAmount(lotNo, k);
}

For reference, Please refer the screenshots:

Main Page
Main Page

Main Page with Dynamic Page having checkboxes
MainPage with Dynamic Table

windows.print() shows another page when exporting to any media

I’m having an issue where a specific part of the page is being printed and when the print dialog shows up, it’ll say two pages are being printed and they look exactly the same. I intend for one page to be printed as there’s only one page.

I had noticed that when messing with print scale and setting it to 99 scale, it’ll only say that there’s one page being exported, but when set to 100 scale, it’ll say there’s two pages being exported.

mousemove Event Listener not working when cursor is in front of a

i have a script which adds a trail to the cursor, its controlled via event listeners and Canvas, it works fine except when hovering over an iframe, in which instance the trail stops and mousemovements are no longer being reported until the mouse stops hovering over the iframe.

I have tried adding extra event listeners to specifically handle when hovering over an iframe to no avail, and I have also tried seeing if there was an issue with Z-indexxing and the canvas, however this did not fix any errors.

As an extra note, I cannot add pointer-events:none; to the iFrame, as that would disallow users to communicate with the embedded content, which is crucial for my use instance (vimeo).

my code is as seen below:

// Check if the user agent contains 'iPhone' or 'iPad'
if (/(iPhone|iPod|iPad)/.test(navigator.userAgent)) {
    console.log("no trail.");
} else {

    const canvas = document.querySelector("canvas");
const ctx = canvas.getContext('2d');

// for intro motion
let mouseMoved = false;

const pointer = {
    x: .5 * window.innerWidth,
    y: .5 * window.innerHeight,
}
const params = {
    pointsNumber: 40,
    widthFactor: .3,
    mouseThreshold: .6,
    spring: .3,
    friction: .5
};

const trail = new Array(params.pointsNumber);
for (let i = 0; i < params.pointsNumber; i++) {
    trail[i] = {
        x: pointer.x,
        y: pointer.y,
        dx: 0,
        dy: 0,
    }
}

window.addEventListener("click", e => {
    updateMousePosition(e.pageX, e.pageY);
});
window.addEventListener("mousemove", e => {
    mouseMoved = true;
    updateMousePosition(e.pageX, e.pageY);
});
window.addEventListener("touchmove", e => {
    mouseMoved = true;
    updateMousePosition(e.targetTouches[0].pageX, e.targetTouches[0].pageY);
});

function updateMousePosition(eX, eY) {
    pointer.x = eX;
    pointer.y = eY;
}

setupCanvas();
update(0);
window.addEventListener("resize", setupCanvas);


function update(t) {

    ctx.strokeStyle = '#ff5800';

    // for intro motion
    if (!mouseMoved) {
        pointer.x = (.5 + .3 * Math.cos(.002 * t) * (Math.sin(.005 * t))) * window.innerWidth;
        pointer.y = (.5 + .2 * (Math.cos(.005 * t)) + .1 * Math.cos(.01 * t)) * window.innerHeight;
    }

    ctx.clearRect(0, 0, canvas.width, canvas.height);
    trail.forEach((p, pIdx) => {
        const prev = pIdx === 0 ? pointer : trail[pIdx - 1];
        const spring = pIdx === 0 ? .4 * params.spring : params.spring;
        p.dx += (prev.x - p.x) * spring;
        p.dy += (prev.y - p.y) * spring;
        p.dx *= params.friction;
        p.dy *= params.friction;
        p.x += p.dx;
        p.y += p.dy;
    });

    ctx.lineCap = "round";
     ctx.beginPath();
    ctx.moveTo(trail[0].x, trail[0].y);

    for (let i = 1; i < trail.length - 1; i++) {
        const xc = .5 * (trail[i].x + trail[i + 1].x);
        const yc = .5 * (trail[i].y + trail[i + 1].y);
        ctx.quadraticCurveTo(trail[i].x, trail[i].y, xc, yc);
        ctx.lineWidth = params.widthFactor * (params.pointsNumber - i);
        ctx.stroke();
    }
    ctx.lineTo(trail[trail.length - 1].x, trail[trail.length - 1].y);
    ctx.stroke();
    
    window.requestAnimationFrame(update);
}

function setupCanvas() {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
}

}
body{
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  max-width: 100%;
  overflow-x: hidden;
}

#trail{
  position: absolute;
  pointer-events: none;
  z-index: 9999999999999999;
  -webkit-filter: drop-shadow(0px 0px 5px rgb(255, 255, 255));
  filter: drop-shadow(0px 0px 5px rgb(255, 255, 255));
  width: 100%;
  height: 100%;
}
<iframe src="https://www.example.com" title="Test iFrame">
</iframe>

<canvas id="trail"></canvas>

Unique key prop to list of elements not working

I keep getting the warning: Each child in a list should have a unique “key” prop.

But i have applied a key with an index number to my element yet i don’t see it in the html via dev tools and the key is incrementing so they should be unique. I don’t understand why i still get this warning.

This is my code setup (im using react-bootstrap):

<Nav>
  {items.map((item, index) => (
    <NavLink item={item} index={index} onClick={handleClick} />
  ))}
</Nav>

My nav link element is created like this:

export default function NavLink({ item, index, onClick }: NavLinkProps) {
  let classes = `me-${navSpacing} fs-${fontSize} text-decoration-underline`;
  classes += item.active ? " active" : "";
  const Icon = item.icon;
  console.log(index);
  return (
    <Nav.Link className={classes} key={index} onClick={() => onClick(item.key)}>
      <Icon className={`me-${iconSpacing}`} />
      {item.text}
      {item.page && typeof item.page === "string" && <ExternalIcon />}
    </Nav.Link>
  );
}

My console log output shows (though its not clear to me why i see double) so it is incrementing the index value:

enter image description here

In the dev tools the html does not show a key attribute:

enter image description here

What am i misunderstanding here?

In an HTML document, how do I control how a PDF document is rendered to show page breaks and a margin?

I am trying to create a web page with an embedded PDF. My code works but it doesn’t show breaks between the document’s pages or a margin (in the same way that Chrome does when used as a PDF viewer). My problem is that I am too unfamiliar with handling PDFs in JS to find the documentation I need. I have tried googling for pdfjslib and pdf.min.js but the hits all refer to “PDF.js” which I am not using – I think!

Here is my code:

<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.12.313/pdf.min.js"></script>
<script>
  // Set worker path to worker bundle of pdf.js
  pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.12.313/pdf.worker.min.js';
</script>
  
  <script>
    // PDF.js initialization
    const container = document.getElementById('pdfRenderer');
    const renderPage = (pageNumber, pdf) => {
      pdf.getPage(pageNumber).then(page => {
        const canvas = document.createElement('canvas');
        const context = canvas.getContext('2d');

        // Set the scale for rendering
        const viewport = page.getViewport({ scale: 1 });

        // Set canvas dimensions to PDF page dimensions
        canvas.height = viewport.height;
        canvas.width = viewport.width;

        // Render the PDF page into the canvas context
        page.render({
          canvasContext: context,
          viewport: viewport
        });

        container.appendChild(canvas);

        // Render next page if available
        if (pageNumber < pdf.numPages) {
          renderPage(pageNumber + 1, pdf);
        }
      });
    };

    pdfjsLib.getDocument('Fergus-pdf-small.pdf').promise.then(pdf => {
      renderPage(1, pdf);
    });
  </script>

Any pointers/suggestions greatfully received.

Fetching data from Google Maps through API [closed]

I’m creating a real-time moving company form for Top Notch Moving Services.
I want fetch the data of city, state and country according to the zipcode of user.

Sign Up for ZipCodeAPI: Register for an account on ZipCodeAPI and obtain an API key.

Integrate ZipCodeAPI into Your Form: Add JavaScript code to your form that triggers an API request to ZipCodeAPI whenever a user enters a zip code.

Retrieve Data: Once the API call is made, retrieve the relevant data such as city, state, and country from the API response.

Display Data in Form: Populate the corresponding fields in your form with the retrieved data (city, state, country) based on the user’s entered zip code.

image in twitter when sharing content

I have a page with an image, but when I share it on twitter the picture does not show up, as it does in other sites

...
<main id="main">

    <section class="single-page">
      
        <div class="container" data-aos="fade-up">
          <div class="row">
            <div class="col-lg-8">
                <h2 >Lorem Ipsum is not simply random </h2>
              <div class="d-flex align-items-center details-post-data">
                <div class="post-meta d-flex">
                  <p class="post-author">Mystic Rivers </p>
                  <p class="post-sperator"> - </p>
                  <p class="post-date">
                    <time datetime="2023-01-01">02-04-2024 16:00</time>
                  </p>
                </div>
                  <p><br/>&nbsp;</p>
              </div>
              <div class="col-lg-12">
                <img src="/assets/images/blog/saturn.jpg" class="img-fluid rounded-4 mb-4"  />
              </div>
...

enter image description here

Issue creating database for a HTML Form using PHP [duplicate]

I am creating my CV website and am creating a contact me form at the bottom of my website. So I am using HTML, CSS, PHP and Java to help me with this. Basically, I want to create a database in myPHP within Hostinger as my server to view and download people’s entries. I am having trouble getting the HTML to communicate with PHP to make it work properly.

I’ve tried using formsubmit but it times out so frequently so I am opting to learn PHP and use this as a learning tool. My issue is I get a HTTP 405 or 500 error after I hit the submit button. Can someone help me with my PHP code please? I will post both HTML and PHP. The HTML code is in a file called form.html and the PHP code is inside the file dbnew.php. Thanks in advance

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form action="dbnew.php" method="POST">
        <div class="input-box">
            <div class="input-field">
                <label for="fullName">
                <input type="text" name="fullName" placeholder="Full Name" required>
                <span class="focus"></span>
                </label>
            </div>
            <div class="input-field">
                <label for="email">
                <input name="email" type="email" id="email" pattern="/^[a-zA-Z0-9.!#$%&*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:.[a-zA-Z0-9-]+)*$/" placeholder="Email Address" required>
                <span class="focus"></span>
                </label>
            </div>
        </div>
            <div class="input-box">
                <div class="input-field">
                    <label for="phone">
                    <input type="tel" id="phone" name="phone" placeholder="Phone Number" required>
                    <span class="focus"></span>
                    </label>
                </div>
            
                <div class="input-field">
                <label for="emailSubject">
                <input type="text" name="emailSubject" placeholder="Email Subject" required>
                <span class="focus"></span>
                </label>
                </div>
            </div>
            <div class="textarea-field">
                <textarea name="emailMessage" id="" cols="30" rows="10" name="message" placeholder="Your Message" required></textarea>
                <span class="focus"></span>
                
            </div>

            <div class="btn-box btns">
                <button type="submit" class="btn">Submit</button>
            </div>
            
    </form>
</body>
</html>
<?php
 $fullName = $_POST['fullName'];
 $email = $_POST['email'];
 $phone = $_POST['phone'];
 $emailSubject = $_POST['emailSubject'];
 $emailMessage = $_POST['emailMessage'];

 if (!empty($fullName) || !empty($email) || !empty($phone) || !empty($emailSubject) || !empty($emailMessage)){
    $servername = "https://mywebsite.com";
    $database = "u292472425_mywebsite";
    $username = "u42424823_username";
    $password = "MyPassword#1234";


 
    // Create connection
$conn = new mysqli($servername, $username, $password, $database);
if (mysqli_connect_error()) {
        
            die('Connection error('. mysqli_connect_errno().')'. mysqli_connect_error());
        
        }else{
            $SELECT = "SELECT email From register Where email = ? Limit = 1";
            $INSERT = "INSERT Into register (fullName, email, phone, emailSubject, emailMessage) values(?, ?, ?, ?, ?)";
    
        $stmt = $conn->prepare($SELECT);
        $stmt->bind_param("s", $email);
        $stmt->execute();
        $stmt->bind_result($email);
        $stmt->store_result();
        $rnum = $stmt->num_rows;

        if ($rnum==0) {
            $stmt->close();

            $stmt = $conn->prepare($INSERT);
            $stmt->bind_param("ssiss", $fullName, $email, $phone, $emailSubject, $emailMessage);
            $stmt->execute();
            echo "New record inserted successfully";
        } else {
            echo "Someone already registered using this email";
        }
        $stmt->close();
        $conn->close();

        }
    } else{
        echo "All fields are required";
        die();
    }
?>

multiple template bootstrap in angular16

Suis débutant sur Angular et aimerai bien mettre sur pied deux Modules: l’un Admin ayant un template Administrateur et l’autre Module ayant un autre template Bootstrap. Mon souci ici est que je me rend compte que mes pages chargent leurs ressources depuis le fichier index.html ; et les deux templates ne peuvent entièrement partager ce fichier au risque de créer des conflits, notamment sur les fichiers style.css et bootstrap.css

Alors je me demandais si déjà mon défi est possible, si oui comment celà peut etre fait.

Merci de me filer quelques pistes à propos

Mon souci ici est que je me rend compte que mes pages chargent leurs ressources depuis le fichier index.html ; et les deux templates ne peuvent entièrement partager ce fichier au risque de créer des conflits, notamment sur les fichiers style.css et bootstrap.css

Function is not defined node.js [closed]

I have the functions below and I’m getting an error in the first function, saying that “getID” is not defined, despite being in module.exports and being imported. I am sure I’m importing the correct file. I have two files below:

authTokenGenerator:

const accounts = require('./queries/accounts.js');
const alph = ["a", "b", "c", "d", "e", "f", "g", 
            "h", "i", "j", "k", "l", "m", "n", 
            "o", "p", "q", "r", "s", "t", "u", 
            "v", "w", "x", "y", "z" ];

module.exports = {
    authTokenGenerator: (email) => {
        return new Promise((resolve) => {
            (async () => {
                var auth = "";

                for (var i = 0; i < 10; i++) {
                    if (Math.floor(Math.random() * 2) == 0) auth += alph[Math.floor(Math.random() * 25)]
                    else auth += Math.floor(Math.random() * 10);
                }
        
                if (!isEmpty(email)) {
                    var id = await accounts.getId(email);

                    var tokenStored = await accounts.storeSessionToken(id, auth, expirationDateTime());

                    if (tokenStored) return resolve(auth);
                    else return resolve("An error has occured")
                }
            
                return resolve(auth);
            }) ();
        })
    }

accounts.js:

module.exports = {
    getId: (email) => {
        return new Promise((resolve) => {
            (async () => {
                var id = await getId(email);

                return resolve(id);
            }) ();
        })
    }
}


function getId(email) { // I tried renaming this function but that didn't work
    return new Promise((resolve) => {
        var getId = `SELECT id FROM accounts WHERE email="${email}"`;

        db.query(getId, (err, res) => {
            if (err) throw err;
            return resolve(res[0].id);
        })
    })
}

There are more functions in each of these files than are included in this post. In the file accounts.js I have the getId function in module.exports, which calls the function getId outside of the exports. Below is the error:

var id = await accounts.getId(email);
                                            ^

TypeError: accounts.getId is not a function
    at /Users/name/Desktop/name/Portal/API/generator.js:19:45
    at /Users/name/Desktop/name/Portal/API/generator.js:28:16
    at new Promise (<anonymous>)
    at Object.authTokenGenerator (/Users/name/Desktop/name/Portal/API/generator.js:9:16)
    at resolve (/Users/name/Desktop/name/Portal/API/schema.js:92:56)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async graphqlMiddleware (/Users/name/Desktop/name/Portal/API/node_modules/express-graphql/index.js:125:26)

Node.js v21.6.2
[nodemon] app crashed - waiting for file changes before starting...