why await is used before using premade methods which is present in userSchema [closed]

why there is await before user.comparepassword. it is a method which i made in usermodel.

this is controller for user regestration

module.exports.loginUser = async (req, res) => {
    const { email, password } = req.body;
    const user = await userModel.findOne({ email }).select('+password');
    
    if (!user) {
        return res.status(400).json({ errors: [{ msg: 'invalid credentials' }] });
    }

    const isMatch = await user.comparePassword(password);
    if (!isMatch) {
        return res.status(400).json({ errors: [{ msg: 'invalid credentials' }] });
    }

    const token = await user.generateAuthToken();
    return res.status(200).json({ token, user });
};

i am expecting an explanation for this. because it does not call database, but it is using await.can you give detail explanation about the topic

why await is used before using premade methods which is present in userSchema

why there is await before user.comparepassword. it is a method which i made in usermodel.

this is controller for user regestration

module.exports.loginUser = async (req, res) => {
    const { email, password } = req.body;
    const user = await userModel.findOne({ email }).select('+password');
    
    if (!user) {
        return res.status(400).json({ errors: [{ msg: 'invalid credentials' }] });
    }

    const isMatch = await user.comparePassword(password);
    if (!isMatch) {
        return res.status(400).json({ errors: [{ msg: 'invalid credentials' }] });
    }

    const token = await user.generateAuthToken();
    return res.status(200).json({ token, user });
};

i am expecting an explanation for this. because it does not call database, but it is using await.can you give detail explanation about the topic

Parallax effect between sections and Scrolling issue

I am working on a landing page using react and tailwind. You have a sticky navigation where you click links then view scrolls to that particular section which connected to the link because section has that id. In between this you have two sections about and features where about has sticky top-0 class features also has sticky top-0 class to create a parallax style effect. When scroll down or up using any link in navbar it works well but when you click on about link if you are in the top of the page then page scrolls down smoothly to about section but when you are down further in other section like features and click about link again from the navbar the scroll doesn’t take you to about section, rather it gets stuck and you have to click a lot of time so that about section finally reappears, this is happening because of position sticky. I tried many way like normal html css anchoring, or programmatic way of scrolling still doesn’t work. I was wondering if someone can help me to solve this issue.

my navigation

import { cart, logo } from "@/assets/getAssets";
import { useScrollContext } from "@/contexts/ScrollContext";
import { useOutletContext } from "react-router-dom";

export default function Navbar() {
  const { hideTopNav } = useOutletContext<{ hideTopNav: boolean }>();
  const { setClickedSection } = useScrollContext();
  const menus = [
    {
      id: 1,
      title: "About",
      path: "about",
    },
    {
      id: 2,
      title: "Features",
      path: "features",
    },
    {
      id: 3,
      title: "FAQs",
      path: "faqs",
    },
    {
      id: 4,
      title: "Contact",
      path: "contact",
    },
  ];

  const handleScroll = (
    e:
      | React.MouseEvent<HTMLAnchorElement>
      | React.MouseEvent<HTMLButtonElement, MouseEvent>,
    targetId?: string
  ) => {
    e.preventDefault();

    if (!targetId || targetId === "#") {
      // Scroll to top if no id provided
      window.scrollTo({ top: 0, behavior: "smooth" });
      return;
    }

    const section = document.getElementById(targetId);
    setClickedSection(targetId);
    if (section) {
      const yOffset = -10; // adjust based on header height
      const y =
        section.getBoundingClientRect().top + window.pageYOffset + yOffset;
      window.scrollTo({ top: y, behavior: "smooth" });
    }
  };

  return (
    <div
      style={{ top: hideTopNav ? "0px" : "40px" }}
      className="fixed left-0 z-[9999] w-full py-6 backdrop-blur-md transition-all duration-300"
    >
      <nav className="max-w-[1200px] mx-auto flex justify-between items-center py-[6px]">
        <div>
          <img src={logo} alt="logo image" className="max-w-[169px] h-auto" />
        </div>

        {/* menus */}
        <ul className="px-[10px] py-[10px] flex gap-[64px] items-center">
          {menus.map((item) => (
            <li key={item.id}>
              <a
                className="font-manrope font-medium text-sm text-white leading-[19.6px] tracking-[-0.28px] no-underline"
                href={`#${item?.path}`}
                onClick={(e) => handleScroll(e, item?.path)}
              >
                {item?.title}
              </a>
            </li>
          ))}
        </ul>

       
      </nav>
    </div>
  );
}

example of about and feature section


export  function About() {
  return (
    <section
      id="about"
      className="bg-green-500 p-10 py-[229px] mb-[128px] h-screen flex justify-center items-center sticky top-0 "
    >
      About
    </section>
  );
}
export function Features() {
  return (
    <section
      id="about"
      className="bg-yellow-500 p-10 py-[229px] mb-[128px] h-screen flex justify-center items-center sticky top-0"
    >
      Features
    </section>
  );
}

I tried normal way of html and css for scrolling in sections, even used programmatic way, using ref with global context to remove the sticky class, but since react re-renders when states change so sticky doesn’t go on the very first time, then have to click again then it will work so having a context with states didn’t helped also

PrismarineJS mineflayer-pathfinder – Bot ignores movement rules for first few seconds of goal

I am working on a Minecraft bot in JavaScript using Mineflayer-Pathfinder.

I am seeing strange behavior. Before I call bot.pathfinder.setGoal(), I set the movement rules using pathfinder.setMovements(). However, when I do this, it seems like it takes the bot a few seconds for the movement rules to actually update. For the first few seconds as the bot carries out its goal, it sprints and does wild parkour moves to get to the target. This causes the bot to get rubber banded really bad on the server, and throws it off the path. Then, suddenly, it starts following the rules I set. Walking slowly, no parkour, etc.

The temporary workaround I found was to just set a delay before calling setGoal. I’ve found it can take at least 2 seconds for the bot to obey the rules set. However, the fact that I’m using timing for something like this tells me that I’ve likely done something critically wrong.

One thing I tried is to await for a path_update or path_reset after setting the movements, but it never seems to trigger….

await new Promise(res => bot.once('path_reset', res));

Nowhere else in my codebase am I setting the movements to anything different from the rules I set in my buildConstrainedMovments().


// helper to construct Movments
export function buildConstrainedMovements(bot, mcData) {
    const m = new Movements(bot, mcData);
    m.canDig = false;
    m.allowWater = false;
    m.allowSprinting = false;
    m.allow1by1towers = false;
    m.allowParkour = false;
    m.canOpenDoors = true;
    m.maxDropDown = 5;

    if (!m.blocksToAvoid) m.blocksToAvoid = new Set();
    const avoidNames = [
        'cobweb','sweet_berry_bush','powder_snow','campfire','soul_campfire','fire','magma_block','scaffolding',
        ...Object.keys(mcData.blocksByName).filter(n => /trapdoor/.test(n))
    ];
    for (const name of avoidNames) {
        const b = mcData.blocksByName[name];
        if (b) m.blocksToAvoid.add(b.id);
    }
    m.liquidCost = 100;
    return m;
}

// Child functions of makePearlPuller
/**
 * Create a pearl-pulling helper bound to a bot instance.
 * Usage:
 *   const pullPearl = makePearlPuller(bot, cfg, logger);
 *   await pullPearl('Notch', { x: 0, y: 64, z: 0 });
 */
export function makePearlPuller(bot, cfg, logger) {
    
    // Helper functions...
    bot.on('goal_reached', async (goal) => {
        if (!activePull) return;
        // Handle goal reached...
    });

    return async function pullPearl(username, homeCoords) { // <- Problem function
        if (activePull) return Promise.resolve();

        return new Promise(async (resolveOuter) => {
        _resolvePearlRun = resolveOuter; // scope in parent function

        try {
            const moves = await buildConstrainedMovements(bot, mcData);
            await bot.pathfinder.setMovements(moves);
            
            // ... Here I figure out where the coordinates to an active ender pearl is, and populate best with the coordinates

            // For some reason, if I don't wait a couple seconds, the bot ignores the movement rules set and starts sprinting,
            // doing parkour, etc.
            // bot.pathfinder.setGoal(new GoalNear(best.x, best.y, best.z, 2)); <- Won't work
            setTimeout(() => {
                try {
                    bot.pathfinder.setGoal(new GoalNear(best.x, best.y, best.z, 2));
                } catch (e) {
                    logger?.warn?.('[pearl] setGoal failed:', e?.message || e);
                    activePull = null;
                    finishPull();
                }
            }, 3000);

        } catch (err) {
            logger?.error?.('[pearl] unexpected error:', err);
            activePull = null;
            finishPull();
        }
        });
    };
}

Node Version: v18.19.1

Packages:

minecraft-data: 3.99.1

mineflayer: 4.20.0

mineflayer-pathfinder: 2.4.5

Generate a downloadable PDF from a template with HTML in a web client [closed]

I need to create a PDF file for a customer order. The PDF should be downloadable in the web client. The document is about 3 pages long and includes:

  • A colored table with headers

  • Several paragraphs of text

  • A company logo

Ideally, the PDF should be based on a template where I can insert variables dynamically.

Is there a way to create an HTML page as a template and then use a PDF generator to render the HTML into a PDF?

We have 2025 .. there must be a comfortable way of doing that besides compolicated and complex js libraries where I have to set every pixel.

This is the first time in a time where AI is not helping much.

Thanks in advance!

Blazor JSinterop invokeMethodAsync on blur event is affecting js component behavior

I’ve modified a blazor-js component based on QuillJs to enable two-way binding from the text editor to blazor/c# property

I’ve done this by adding a ‘blur’ event listener and invoking a method c# method from js:

(All source code here)
https://github.com/gismofx/TextEditor/blob/3ea6d0705a443d8ea81bdcce46814ef2261e1e26/src/Blazored.TextEditor/wwwroot/Blazored-BlazorQuill.js#L40

//On Blur - we update the object in dotnet
            quillElement.__quill.editor.scroll.domNode.addEventListener('blur',
                () => {
                    if (quillElement.__quill.options.debug === "info") {
                        console.log('info: Quill Editor blur event for ' + quillElement.id);
                    }
                    QuillFunctions.dotNetRefs.get(quillElement.id).invokeMethodAsync('DeltaChanged', QuillFunctions.getQuillContent(quillElement));
                }
            );

The two-way binding works just fine.

Issue:
When interacting with quill’s toolbar, e.g. to change some highligted text’s format, the cursor jumps to start of text and formatting it not applied. If you repeat, it applied the fomatting. This happens every time.

See recording of strange behavior:
strange behavior

If I remove the invokeMethodAsync call, it restores correct functionality and formatting is applied correctly.

Is there different event to use or another way to keep binding and not affect the quill functionality?

how should i clear my npm installation error (The term ‘npm’ is not recognized as the name of a cmdlet, function, script file, or operable program.) [closed]

enter image description here

how can i solve this program?

i just want to install npm in my vscode.
(npm : The term ‘npm’ is not recognized as the name of a cmdlet, function, script file, or operable
program. Check the spelling of the name, or if a path was included, verify that the path is correct
and try again.)

Programming interface with Web Dev Technology [closed]

I am just in beginning to learn JavaScript after HTML AND CSS now. but before I was working python especially PYQT6 python library for GUI applications. But I have experienced limitations and barrier using as New programmer while I was also working on my logic building now I have shift to Web Dev. Not for actually Web Development but for Making GUI interface and I was Amazed when I used HTML CSS. It has so many features and flexibility you get as a new coder that you can’t get this on Pyqt6 or Tkinter. I hope I will learn JavaScript soon as start my programming carrier as soon as possible. If someone know how can I learn JavaScript as fastest and efficiently as possible. I would love to know about it in the comments

WordPress RestAPI in Javascript. How to get array data out of the response

I am working on a Gutenberg block and am modifying the Edit.js file. I want to fetch the root categories in the database. From the reading I have done, it seems a good way to do this is to use the REST API and perform a call like this:

var categories = fetch("http://localhost/wordpress_ttm/wp-json/wp/v2/categories").then(response => response.json())

This all works fine and gives me back a response. Here is the structure of the response.

categories: Promise { "fulfilled" }
​​
<state>: "fulfilled"
​​
<value>: (10) […]
​​​
0: {…}
​​​
1: {…}
​​​
2: {…}
​​​
3: {…}
​​​
4: {…}
​​​
5: {…}
​​​
6: {…}
​​​
7: {…}
​​​
8: {…}
​​​
9: {…}
​​​
length: 10
​​​
<prototype>: []
​​
<prototype>: Promise.prototype

How do I to get the data out of the response? I want to grab the array data and iterate over it, but I’m not sure how to do that. Any help is appreciated.

Custom File upload Component in Livewire Laravel

I am trying to create a reusable Livewire input-file component, Such that :

  1. Easy embed in any (parent) and pass the model name (ex = “file1”)
  2. How to store() the file is in control of (parent) Form

So far, I have created a child component and a parent form. The problem is that in return, I get a “string” and not a file object from Livewire component. Can anyone help in correcting the thing or even suggest how to do it in a better way?

SingleFileUpload(component)

<?php

namespace AppLivewire;

use LivewireComponent;
use LivewireAttributesModelable;
use LivewireWithFileUploads;

class SingleFileUpload extends Component
{
    use WithFileUploads; 
    #[Modelable]          // lets parent bind with wire:model="file1"
    public $value = null; // receives TemporaryUploadedFile from Livewire

    /** Public props to customize UI/behavior */
    public string $label   = 'Upload file';
    public string $accept  = '';        // e.g. "image/png,image/jpeg"
    public bool   $multiple = false;    // set true if you enable multi
    public ?string $errorKey = null;    // parent field name for @error display

    public function render()
    {
        return view('livewire.single-file-upload');
    }
}

Blade File

// other code for div styles  ....
    <input
        type="file"
        wire:model.live="value"
        @if($accept) accept="{{ $accept }}" @endif
        @if($multiple) multiple @endif
        class="file-input file-input-bordered w-full"
    />

// Other code for progress bar ...

Usage In parent form
Blade

<livewire:single-file-upload wire:model="file1" :label="'Photo 1'" accept="*" :errorKey="'file1'" />

FormCompoenent

class FormComp extends Component
{
 use WithFileUploads; 
 public function save($method)
    {
        $this->validate(); 
        $stored1 = $this->file1->store('frt_api/uploads/' . $timestamped_folder_path); //<--- Fails recived a string instead of file
    }
}

If I dd($this->file1) , I get livewire-file:eCQNvlZlJu4j15E88m9Rt98BXUW4wU-metacGVyZmVjdGNyb3BpY29udXNlci5wbmc=-.png hence unable to figure out how to store it on parent side

retrieve from an array and/or subarray [closed]

I have the following array/subarray. How would I go about retrieving the data from the array to run an update query:

    Array
(
    [court] => Array
        (
            [442] => ccal11
            [443] => ccal222
        )

    [judge] => Array
        (
            [442] => Robert Harper11
            [443] => Harriett L Haag22
        )

    [address] => Array
        (
            [442] => 300 Oak St Ste 500
Abilene TX 7960211
            [443] => 300 Oak St Ste 501
Abilene TX 7960222
        )

    [phone] => Array
        (
            [442] => 325-674-132311
            [443] => 325-674-120822
        )