How to dynamically adjust this image for this PDF such that the image is directly below the text?

In this code, I need to adjust the code such that the image is directly below the text. When I run this code,

Here is my current code:

var pdf = new jsPDF('p', 'pt', 'letter');
let w = 40;
let h = 100;

source = `Some text`;
pdf.addImage(chartIMG, 'PNG', w, h + 50, 180, 100);

pdf.fromHTML(source, w, h, { 'width': 522 }, function () {
  pdf.save('Test.pdf');
});

Here, the chartIMG object should then be placed 50 pixels below the text, through the h+50 clause. However, if I try to lengthen the text, the image stays in it’s same place. Any help is appreciated.

Jest – how to test if constructor of a class was called with param

I have those two classes:

// src/example.js

class A {
  name = undefined

  constructor(name) {
    this.name = name
  }

  say_my_name() {
    console.log('The arg is: ', this.arg1)
  }
}

class B {
  constructor(name) {
    this.a = new A(name)
  }

  run() {
    this.a.say_my_name()
  }
}

module.exports = { A, B }

I want to test if class B instantiated class A with correct name parameter. In other words if class A constructor was called with specified value.

My test case looks like this

const { A, B } = require('../src/example')

it('should run', () => {
  const b = new B('test')
  b.run()
  // how to test if class A's constructor was called with 'test'?
})

I’ve looked through stackoverflow and google but could not find similar example. Tried to make it work like this:

const example = require('../src/example')

const B = example.B

jest.spyOn(example, 'A')

it('should run', () => {
  const b = new B('test')
  b.run()
  expect(example.A).toHaveBeenCalledWith('test')
})

or this one

const example = require('../src/example')

const B = example.B

example.A = jest.fn()

it('should run', () => {
  const b = new B('test')
  b.run()
  expect(example.A).toHaveBeenCalledWith('test')
})

But both of those fail with Number of calls: 0.

Any idea how to make it work? Is this even possible with jest?

Thank you.

How to get maximum available size of innerHeight and innerWidth of window?

I want to calculate the maximum available size of innerHeight and innerWidth of window when the browser is opened to whole screen (not full-screen mode)

I tried these codes:

window.screen.availHeight - (window.outerHeight - window.innerHeight)

window.screen.availWidth - (window.outerWidth - window.innerWidth)

but they didn’t work at all

In Firefox I can’t get correct values because it always subtracts 16px (as I understand and measured it is scroll width):

enter image description here

In Chrome and Firefox I get different answers for the above codes when the browser is opened to whole screen and when they are windowed

Is it possible to achieve using JS?

If the answer is yes, then: Is there a cross-browser solution (without checking which browser does the user use)?


OS Windows 10 (64-bit)
Firefox 134.0
Chrome 131.0.6778.265

how to globally import packages in vue3 & inertia & vitejs

im using laravel, vue3, vitejs and inertia to create my app
my problem is: when i import my packages (like sweet alert) globally in my app.js, i will get error like Uncaught (in promise) ReferenceError: Swal is not defined but when i import that package in my inertia pages (.vue pages) it will work, actually i have to import the package in every page i need that.

My app.js:

import './bootstrap';
import { createApp, h } from 'vue'
import { createInertiaApp } from '@inertiajs/vue3';
import Swal from 'sweetalert2';



createInertiaApp({
resolve: async name => {
    const pages = import.meta.glob('/Modules/**/resources/assets/js/Pages/**/*.vue', { eager: false });
    const matchingPageKey = Object.keys(pages).find(key => key.endsWith(`/${name}.vue`));

    let page;
    if (matchingPageKey) {
        const module = pages[matchingPageKey];
        // check if module = function then module is lazyload (eager = false) so it needs await
        page = typeof module === 'function' ? await module() : module;
    }

    return page;
},
setup({ el, App, props, plugin }) {
    const app = createApp({ render: () => h(App, props) });
    app.use(plugin);
    app.mount(el);
},
});

Debugging “Connection was closed. Reason: Render process gone.” in Instagram Chat Scroll Automation

I am automating scrolling to the top of an Instagram chat to load older messages using the following JavaScript code executed in the browser’s console:

Code:

let stopScrolling = false; // stop scrolling manually
let attemptCount = 0; // number of attempts
const maxAttempts = 100; // Number of retries before checking for stop condition

function scrollToTop() {
   const chatContainer = document.querySelector(
       '.x78zum5.xdt5ytf.x1iyjqo2.xs83m0k.xc8icb0.x6ikm8r.x10wlt62.x1ja2u2z > .x78zum5.xdt5ytf.x1iyjqo2.x6ikm8r.x10wlt62.x1n2onr6 > .x78zum5.xdt5ytf.x1iyjqo2.xs83m0k.x1xzczws.x6ikm8r.x1odjw0f.x1n2onr6.xh8yej3.x16o0dkt'
   );

   if (!chatContainer) {
       console.error("Chat container not found.");
       clearInterval(scrollInterval);
       return;
   }

   let lastScrollTop = chatContainer.scrollTop;

   const scrollInterval = setInterval(() => {
       if (stopScrolling) {
           console.log("Scrolling stopped manually.");
           clearInterval(scrollInterval);
           return;
       }

       chatContainer.scrollTop -= 1000;
       attemptCount++;

       if (chatContainer.scrollTop === lastScrollTop) {
           if (attemptCount >= maxAttempts) {
               console.log("Reached the beginning of the chat or no more messages are loading.");
               clearInterval(scrollInterval);
           }
       } else {
           attemptCount = 0;
       }
       
       lastScrollTop = chatContainer.scrollTop;
       console.log("attemptCount", attemptCount);
   }, 800);
}

scrollToTop();

Issue:
After running for some time, the script encounters the following error:

Connection was closed. Reason: Render process gone.
Reconnect when ready by reopening DevTools.

This issue seems related to a browser rendering process crash, potentially due to resource overload or incorrect targeting of dynamic elements in the Instagram chat interface.

What I’ve Tried:

  • Adjusted the scroll interval and decrement values.
  • Limited the number of attempts to break infinite loops.
  • Used a manual flag (stopScrolling) to terminate the process.

Questions:

  • What could cause the “Render process gone” error in this Instagram chat scrolling scenario?
  • How can I optimize the script to avoid browser crashes and excessive resource usage?
  • Are there better techniques for automating scrolling in dynamically loading web interfaces like Instagram?

Environment:

  • Platform: Instagram Web
  • Browser: Chrome
  • Script Execution: Developer Tools Console

Any help or suggestions are appreciated!

Adding Data Hub custom envelope file to collection

I’m working on a MarkLogic Data Hub project and encountering issues when trying to add generated envelope documents to a collection (dita-envelope) during a custom step in an ingestion flow.

Context
  • Flow Step: Using a custom step to process .ditamap files and create envelope documents.
  • Requirement: The generated envelope documents should be added to the dita-envelope collection in the staging database.
Approaches Tried
1. Using xdmp.documentAddCollections
if (cts.docAvailable(envelopeUri)) {
    xdmp.documentAddCollections(envelopeUri, ["dita-envelope"]);
}

Issue: Throws XDMP-OWNTXN errors because declareUpdate() is not allowed within the managed transaction context of a Data Hub custom step and without it gives error that declareUpdate is missing.

2. Adding Collection Metadata in flowUtils.writeContentArray
const outputContent = {
    uri: envelopeUri,
    value: envelope,
    context: {
        metadata: {
            collections: ["dita-envelope"],
        },
    },
};
flowUtils.writeContentArray([outputContent], options.database);

Issue: While the document gets written to the database, it is not assigned to the dita-envelope collection, only adds the metadata to the envelope.

3. Using addMetadataToContent from flow-utils.mjs
flowUtils.addMetadataToContent(outputContent, flowName, stepName, jobId);
flowUtils.writeContentArray([outputContent], options.database);

Issue: Adds metadata to the file about the collection but doesn’t actually assign the document to the collection.

4. Creating Placeholder Documents in the Collection
const placeholderUri = "/placeholder.json";
xdmp.documentInsert(placeholderUri, {}, {collections: ["dita-envelope"]});

Issue: Successfully creates the collection but doesn’t assign the envelope documents to it.

Current Environment

MarkLogic Version: 11.0
Data Hub Version: 6.1.1
Database Context: Using staging and final databases as part of the ingestion flow.

Question
  1. How can I programmatically assign documents to a collection in a MarkLogic Data Hub custom step without using declareUpdate()?
  2. Is there a reliable way to assign collections during the document creation process using flowUtils.writeContentArray or any other Data Hub utility?

Any guidance or suggestions for best practices to achieve this would be greatly appreciated!

useEffect hook not being executed

I Am creating a shoe website and but there is a problem in the following component it normally works fine but when i try to copy the url paste in another tab and try to open it directly then it gives me the error because i am supposed to recieve data from parent route and i tried the following work around but its not working but why

export default function Article() {
    console.log("component is rendered");
    const { user } = useAuth();
    const navigate = useNavigate();
    const {id} = useParams();
    // article data coming from previous route
    const location = useLocation()
    const { article } = location.state || {};
    // cart
    const { addToCart , articleLoadingState , setArticleLoadingState } = useCart();
    const [sales, setSales] = useState(0);

    const [Article,setArticle] = useState(article);

    console.log(article)
    useEffect(() => {
        const fetchArticleData = async () => {
            console.log("fetch article data");
            if (!article) {
                try {
                    const docRef = doc(db, "Articles", id);
                    const docSnap = await getDoc(docRef);

                    if (docSnap.exists()) {
                        console.log(docSnap.data());
                        setArticle(docSnap.data());
                    }
                } catch (err) {}
            } else {
                setArticle(article);
            }
        };

        fetchArticleData(); // Call the async function
    }, [article,id]);

console.log(article) prints undefined in the console but then why is console.log("fetch article data") not being printed in console that means the hook is not being executed but why and console.log("component is rendered"); is also working and the error i recieve is

Article.jsx:49 Uncaught TypeError: Cannot read properties of undefined (reading 'colors')
    at Article (Article.jsx:49:76)

because of this line in code

    const [selectedColor, setSelectedColor] = useState(Object.keys(Article.colors)[0],);
                                  

this is the code of app component

function App() {
    return (
        <>
            <header>
                <Header />
            </header>
                <Nav />
            <Routes>
                <Route path="/" element={<Home />} />
                <Route path="/products/:category" element={<Products />} />
                <Route path="/products/:category/:id" element={<Article />} />
                <Route path="/login" element={<Login />} />
                <Route path="/signup" element={<SignUp />} />
                <Route path="/sizeguide" element={<SizeGuide />} />
                <Route path="/return-exchange-policy" element={<Return_Exchange_Policy />} />
                <Route path="/terms-of-service" element={<Terms_of_service />} />
                {/* Protected Routes */}
                <Route path="/cart" element={ <ProtectedRoute> <Cart /> </ProtectedRoute> }/>
                <Route path="/wishlist" element={ <ProtectedRoute> <WishList /> </ProtectedRoute> }/>
                <Route path="/orders" element={ <ProtectedRoute> <Orders /> </ProtectedRoute> }/>
                <Route path="/checkout" element={ <ProtectedRoute> <CheckOut /> </ProtectedRoute>} />
            </Routes>

        </>
    );
}

export default App;

full code of component

import React, { useState, useEffect } from "react";
import { MdAddShoppingCart } from "react-icons/md";
import { Button , Spinner } from "@nextui-org/react";
import { fireIcon } from "../../assets/images";
import { useNavigate , useLocation , useParams} from "react-router-dom";
import { useCart } from "../../context/CartContext";
import { useAuth } from "../../context/AuthManager";
import { doc, getDoc } from "firebase/firestore";


export default function Article() {
    console.log("component is rendered");
    const { user } = useAuth();
    const navigate = useNavigate();
    const {id} = useParams();
    // article data coming from previous route
    const location = useLocation()
    const { article } = location.state || {};
    // cart
    const { addToCart , articleLoadingState , setArticleLoadingState } = useCart();
    const [sales, setSales] = useState(0);

    const [Article,setArticle] = useState(article);

    console.log(article)
    useEffect(() => {
        const fetchArticleData = async () => {
            console.log("fetch article data");
            if (!article) {
                try {
                    console.log("fetch article data");
                    const docRef = doc(db, "Articles", id);
                    const docSnap = await getDoc(docRef);

                    if (docSnap.exists()) {
                        console.log(docSnap.data());
                        setArticle(docSnap.data());
                    }
                } catch (err) {}
            } else {
                setArticle(article);
            }
        };

        fetchArticleData(); // Call the async function
    }, [article,id]);

    // article data
    const [selectedColor, setSelectedColor] = useState(Object.keys(Article.colors)[0],);// currently selected color
    const [selectedImage, setSelectedImage] = useState(0); // Track the active image index
    const [imageCounter, setImageCounter] = useState(1); // Track the current image number (1-indexed)
    const [isTransitioning, setIsTransitioning] = useState(true); // To control the sliding effect
    const [selectedSize, setSelectedSize] = useState(Article.sizes[0]); // Default to the first size
    const [amount, setAmount] = useState(1);

    // destructing the article data
    const { colors, images } = Article;
    const articleData = {
        articleNo: Article.id,
        originalPrice: Article.price,
        discount: Article.discount,
        available: Article.available,
        images,
        category: Article.collection,
        vendor: Article.vendor,
        sizes: Article.sizes,
        colors,
    };



    // fn for adding component to cart
    const handleAddToCart = async () => {
        setArticleLoadingState(true);

        const cartItem = {
            id: Article.id,
            originalPrice: Article.price,
            discount: Article.discount,
            available: Article.available,
            images: images[selectedColor],
            category: Article.collection,
            vendor: Article.vendor,
            size: selectedSize,
            color: selectedColor,
            quantity: amount,
        };

        try {
            await addToCart(cartItem); // Add item to the cart
        } catch (error) {
        } finally {
            setArticleLoadingState(false);
        }
    };



    const discountedPrice =
        articleData.originalPrice * (1 - articleData.discount / 100);

    const handleColorChange = (color) => {
        setSelectedColor(color);
        setSelectedImage(0); // Reset selected image when changing color
        setImageCounter(1); // Reset counter when changing color
        setIsTransitioning(false); // Temporarily stop the sliding effect
    };

    const handleImageSelect = (index) => {
        setSelectedImage(index); // Update the active image
        setImageCounter(index + 1); // Update the counter (1-indexed)
    };

    // Set up the automatic image change every 5 seconds
    useEffect(() => {
        const interval = setInterval(() => {
            setSelectedImage((prevIndex) => {
                let nextIndex = prevIndex + 1;

                // If the next index exceeds the number of images, reset to 0
                if (nextIndex >= articleData.images[selectedColor].length) {
                    nextIndex = 0;
                    setIsTransitioning(false); // Stop the sliding effect temporarily
                    setTimeout(() => {
                        setIsTransitioning(true); // Re-enable the sliding effect after a brief pause
                    }, 0); // Wait for a short period before re-enabling the transition
                }

                setImageCounter(nextIndex + 1); // Update counter (1-indexed)
                return nextIndex;
            });
        }, 5000); // Change every 5 seconds

        return () => clearInterval(interval); // Clean up the interval when the component unmounts
    }, [selectedColor, articleData.images]);

    useEffect(() => {
        // Set initial sales value to a random number between 10 and 15
        const initialSales = Math.floor(Math.random() * (15 - 10 + 1)) + 10;
        setSales(initialSales);

        // Set up interval to increment sales by 1, 2, or 3 every 2 minutes
        const interval = setInterval(
            () => {
                const increment = Math.floor(Math.random() * 3) + 1; // Random value between 1 and 3
                setSales((prevSales) => prevSales + increment);
            },
            5 * 60 * 1000,
        ); // 2 minutes in milliseconds

        return () => clearInterval(interval); // Clean up the interval on component unmount
    }, []);

    return (
        <>
            <section className="md:w-full w-[98%] mt-10 max-w-7xl mx-auto flex flex-col md:flex-row md:flex-wrap gap-x-2 justify-center md:items-start items-center gap-y-4">
                <div className="flex lg:flex-row-reverse flex-col items-start md:w-2/4 w-[95%] md:mr-6 justify-center gap-y-2 gap-x-2">
                    <div className="w-full min-w-[250px] relative overflow-hidden bg-hero">
                        {/* Main Image with Sliding Effect */}
                        <div
                            className={`flex transition-transform duration-1000 ease-in-out ${isTransitioning ? "" : "transform-none"
                                }`}
                            style={{
                                transform: isTransitioning
                                    ? `translateX(-${selectedImage * 100}%)` // Slide images horizontally
                                    : "none", // Disable the slide effect temporarily
                            }}
                        >
                            {articleData.images[selectedColor].map(
                                (image, index) => (
                                    <img
                                        key={index}
                                        src={image}
                                        alt={`Main Image ${index + 1}`}
                                        className="w-full"
                                    />
                                ),
                            )}
                        </div>
                    </div>
                    <div className="flex lg:flex-col flex-row gap-x-2 gap-y-2 lg:mt-4 sm:mt-1 mt-0">
                        {articleData.images[selectedColor].map(
                            (image, index) => (
                                <div
                                    key={index}
                                    className={`cursor-pointer rounded-md p-1 w-16 h-20 sm:w-14 sm:h-16 flex items-center  ${selectedImage === index ? "border-1 border-black" : ""}`}
                                    onClick={() => handleImageSelect(index)} // Update the active image on click
                                >
                                    <img
                                        src={image}
                                        alt={`Small Image ${index + 1}`}
                                        className="w-11/12"
                                    />
                                </div>
                            ),
                        )}
                    </div>
                </div>

                <div className="w-[95%] md:w-2/5 min-w-[250px] flex flex-col gap-y-3 order-3 md:order-none md:mt-0 mt-6 pl-6 md:pl-6">

                    <p className="text-gray-600 font-asul">FOOTPULSE</p>
                    <h1 className="md:text-2xl text-xl text-black font-bold flex w-full justify-between">
                        {articleData.articleNo}

                        {articleData.discount > 0 && (
                            <div className="rounded-full bg-red-500 w-fit text-white px-4 py-1 text-sm font-bold mr-16">
                                -{articleData.discount}%
                            </div>
                        )}
                    </h1>

                    <div className="flex text-[#DD3327] ml-6 my-3 text-base">
                        <img src={fireIcon} alt="" className="mr-2" />
                        <span>{sales} sold in last 12 hours</span>
                    </div>

                    <div className="flex gap-x-4 items-center">
                        <p className="text-red-500 font-bold text-2xl flex">
                            Rs.{discountedPrice.toFixed(2)}
                        </p>
                        {articleData.discount > 0 && (
                            <p className="text-gray-500 text-2xl font-bold line-through text-md mt-0">
                                Rs.{articleData.originalPrice}
                            </p>
                        )}
                    </div>

                    <hr className="border-gray-300 md:my-1 my-3" />

                    <div className="flex flex-col text-gray-700 font-palanquin text-lg gap-y-2">
                        <p className="text-black">
                            <span className="text-gray-600"> Available </span>:{" "}
                            {articleData.available
                                ? "In Stock"
                                : "Out of Stock"}
                        </p>
                        <p className="text-black">
                            <span className="text-gray-600 "> Vendor </span>:{" "}
                            {articleData.vendor}
                        </p>
                        <p className="text-black">
                            <span className="text-gray-600"> Type </span>:{" "}
                            {articleData.category}
                        </p>
                    </div>

                    <div className="flex flex-wrap gap-2 items-center mt-4">
                        <span className="font-bold">Sizes:</span>
                        {articleData.sizes.map((size, index) => (
                            <span
                                key={index}
                                className={`px-3 py-1 border rounded-full cursor-pointer hover:bg-gray-200 ${selectedSize === size ? "border-black bg-gray-300" : ""
                                    }`}
                                onClick={() => setSelectedSize(size)} // Update the selected size
                            >
                                {size}
                            </span>
                        ))}
                    </div>

                    <div className="flex flex-wrap gap-2 items-center mt-4">
                        <span className="font-bold">Colors:</span>
                        {Object.keys(articleData.colors).map((color, index) => (
                            <span
                                key={index}
                                className={`w-6 h-6 rounded-full border border-gray-600 cursor-pointer transition-all duration-200 ${selectedColor === color ? "border-2 border-gray-600" : ""}`}
                                style={{
                                    backgroundColor: articleData.colors[color],
                                }}
                                onClick={() => handleColorChange(color)}
                            ></span>
                        ))}
                    </div>

                    <div className="flex w-[95%] mx-auto flex-col sm:flex-row gap-4 mt-4">

                        <div className="flex items-center justify-between gap-2 border border-gray-300 rounded-full px-3 py-2 text-black w-[30%]">
                            <button
                                className="text-md font-bold"
                                onClick={() =>
                                    setAmount((prev) => Math.max(prev - 1, 1))
                                }
                            >
                                -
                            </button>
                            <p className="text-md font-bold">{amount}</p>
                            <button
                                className="text-md font-bold"
                                onClick={() => setAmount((prev) => prev + 1)}
                            >
                                +
                            </button>
                        </div>



                        <Button
                            className="bg-gray-950 text-white py-2 font-semibold"
                            radius="full"
                            onClick={handleAddToCart}
                            disabled={articleLoadingState}
                        >
                            {articleLoadingState ? (
                                <Spinner size="sm" />
                            ) : (
                                <>
                                    Add to Cart
                                    <MdAddShoppingCart
                                        size={20}
                                    />
                                </>
                            )}
                        </Button>


                        <Button
                            radius="full"
                            color="success"
                            className="text-white"
                            onClick={() => {
                                handleAddToCart()
                                if (user) {
                                    addToCart();
                                    navigate("/checkout")
                                } else {
                                    navigate("/login")
                                }
                            }}
                        >
                            Buy Now
                        </Button>

                    </div>

                </div>
            </section>
        </>
    );
}

and the url looks like this
http://localhost:5173/products/casual/AP34524
tell me if you need anything else

React native (android) – implement with src

I try to implement in my react native app this one :

<script async id="cp-map-loader" src="//calisthenics-parks.com/js/map.min.js?init=27,-38,2&language=fr" type="text/javascript"></script>

The only thing i had accomplished is to get a white empty WebView …

Can someone help me please ! 🙂

Why does my copy button disappear when I click another button?

I am relatively new to programming and am trying to program a calculator. I tried to make a copy button to copy the result of the calculation. However, when I click another button, like a number, the copy button disappears.

const display = document.getElementById("display");
const calculation = document.getElementById("calculation");
const buttons = document.querySelectorAll(".btn");
const copyButton = document.getElementById("copy");

let calcString = "";
let result = null;

buttons.forEach((button) => {
    button.addEventListener("click", () => {
        const value = button.dataset.value;

        if (button.classList.contains("clear")) {
            calcString = "";
            display.textContent = "0";
            calculation.textContent = "0";
            result = null;
        } else if (button.classList.contains("equals")) {

            try {
                result = eval(calcString);
                display.textContent = result;
                calculation.textContent = `${calcString} =`;
                calcString = result.toString();
            } catch (error) {
                display.textContent = "Error";
                calculation.textContent = "Invalid Input";
                calcString = "";
                result = null;
            }
        } else {

            calcString += value;
            calculation.textContent = calcString;
            display.textContent = value;
        }
    });
});

copyButton.addEventListener("click", () => {
    if (result !== null && result !== "Error") {
        navigator.clipboard.writeText(result)
            .then(() => {
                alert("Result copied to clipboard");
            })
            .catch((err) => {
                console.error("Error copying to clipboard: ", err);
            });
    } else {
        alert("Nothing to copy");
    }
});
<head>
    <meta charset="UTF-8">
    <title>Calculator</title>
    <link rel="stylesheet" href="styles.css">
    <script src="main.js"></script>
</head>
<body>
<div class="calculator">
    <div class="calculation" id="calculation">
        <h1 class="calculation-text">0</h1>
        <button class="copy" id="copy">Copy</button>
    </div>
    <div class="display" id="display">0</div>
    <div class="buttons">
        <button class="btn" data-value="7">7</button>
        <button class="btn" data-value="8">8</button>
        <button class="btn" data-value="9">9</button>
        <button class="btn operator" data-value="/">÷</button>

        <button class="btn" data-value="4">4</button>
        <button class="btn" data-value="5">5</button>
        <button class="btn" data-value="6">6</button>
        <button class="btn operator" data-value="*">×</button>

        <button class="btn" data-value="1">1</button>
        <button class="btn" data-value="2">2</button>
        <button class="btn" data-value="3">3</button>
        <button class="btn operator" data-value="-">−</button>

        <button class="btn" data-value="0">0</button>
        <button class="btn" data-value=".">.</button>
        <button class="btn clear" id="clear">C</button>
        <button class="btn operator" data-value="+">+</button>

        <button class="btn equals" id="equals">=</button>
    </div>
</div>
</body>

I want the copy button to be next to the result, however to fix this problem I have to move the copy button to be outside of the result div:

<button class="copy" id="copy">Copy</button>
<div class="calculator">
    <div class="calculation" id="calculation">
        <h1 class="calculation-text">0</h1>
    </div>

Can anyone help me fix this problem?

scroll down automatically on dropdown menu when users enters input

i have a dropdown menu which lists countries

         <input type="text" onkeyup="filtrar()">

    <li><a class="dropdown-item" href="#" data-code="AF">Afghanistan</a></li>
    <li><a class="dropdown-item" href="#" data-code="AL">Albania</a></li>
    <li><a class="dropdown-item" href="#" data-code="DZ">Algeria</a></li>   
</ul>

i have a script which highlights the options which contain the letters inserted by the user

countries.forEach(item => {
      const itemtext = item.textContent.toLowerCase(); 
      if (inputlow.length === 0) {
          item.classList.remove('selected-country');
      }
      else if (itemtext.includes(inputlow)) { 
        item.classList.add('selected-country');  
      } else {
        item.classList.remove('selected-country');
      }
        
    });

my issue is i want it to auto scroll down to the first selected country.

Axios post request not returning a valid promise

I am using axios for a post request but during execution an error pops up for some users “can’t read properties of undefined, reading then()”

const getHomePageDetails = () => {
    let request = {step: OnlineFlowWorkFlowStep.HOME};
    let url = process.env.REACT_APP_BASE_URL_DEV) + "/fetch-details";
    const accessToken = LocalStorageService.getAccessToken();
    const config = {
        headers: {'Authorization': accessToken,"Content-Type": "application/json" }
    }
    axios.post(url, request, config).then((response) => {
        populateResponse(response);
    }).catch((error) => {
        console.log(error)
    });
}

After some changes I used fetch API first and on failure I used axios but the issue still persisted for some case where fetch api fails and code goes to axios and the error mentioned above pops up how can i handle it?

let retryCount = 0;
const getHomePageDetails = useCallback(async () => {
    let request = {step: OnlineFlowWorkFlowStep.HOME};
    let url = process.env.REACT_APP_BASE_URL_DEV) + "/fetch-details";
    const accessToken = LocalStorageService.getAccessToken();
    const config = {
        headers: {'Authorization': accessToken,"Content-Type": "application/json"}
    }

    try {
        config.method = 'POST';
        config.body = JSON.stringify(request);
        const response = await fetch(url, config);
        response.data = await response.json();
        populateResponse(response);
        return;
    } catch (error) {
        try {
            axios.post(url, request, config).then((response) => {
                populateResponse(response);
                return;
            }).catch((error) => {
                if (retryCount < 1) {
                    retryCount++;
                    getHomePageDetails();
                    return;
                }
            });
        } catch (error) {
            if (retryCount < 1) {
                retryCount++;
                getHomePageDetails();
                return;
            }
        }

    }
})

Can a style change triggered by a style .css file be listened from Java Script?

First of all, apologies for being so new in this field, because although I have some experience, many topics of JavaScript, jQuery, css, are unknown for me.

The thing is that I need to listen for style changes which are triggered via my style .css file.

My .html example:

<p class="test">My text</p>

My .css example:

.test:not(:hover) {
    background: #000;
}

.test:hover {
    background: #2ca464;
}

And, in my .js, I would like to listen to that background color change.

I am using a quite old jquery version: jquery-1.11.1

And I have found that when changes are made programatically, it works, but when they are not made programatically, the listener is never called

// https://stackoverflow.com/a/43547684/5698125
function listenToAttributeChange(myDollarThis, attributeName, myCallbackFunction) {
    const target = myDollarThis[0];
    var observer = new MutationObserver(function(mutations) {
        myCallbackFunction(myDollarThis);
    });

    observer.observe(target, { 
      attributes: true, 
      attributeFilter: [attributeName] });
}

function listenToAttributeChangeForSelector(mySelector, attributeName, myCallbackFunction) {
    $(mySelector).each(function () {
        listenToAttributeChange($(this), attributeName, myCallbackFunction);
    });
}


// and invoking it like this:
    var myListener = function(myDollarThis) {
        if (myDollarThis.css("background-color") ...) ...
    };

    listenToAttributeChangeForSelector(".test", "style", myListener);

I could check that myHoverFunction is invoked when the change to my element is done programatically, as for instance, when this code is invoked:

    $( ".test" ).each( function() {
        $( this ).css("background", "rgb(0, 0, 0)");
    });

But it is not invoked when the change is done via style .css

Does anybody know if there is any way to listen to style changes which are not done programatically, but regarding my style .css file?

Issue with DELETE Request in Node.js/DynamoDB API – ValidationException

I’m working on a backend project using AWS DynamoDB and Node.js, where I’ve implemented a REST API. While the POST and GET requests are working perfectly, the DELETE request fails with a ValidationException error:

The provided key element does not match the schema

Here’s the relevant code snippet:

if (req.method === "DELETE" && parsedUrl.pathname === "/api/users") {
    const userID = parsedUrl.query.userID;  

    if (!userID) {
        res.writeHead(400);
        return res.end(JSON.stringify({ error: "userID is required" }));  
    }

    const params = {
        TableName: "Trivia-app-users", 
        Key: {
            "userID": userID,  
        },
    };

    try {
        await dynamoDb.delete(params).promise();
        res.writeHead(200);
        return res.end(JSON.stringify({ message: "User data deleted successfully!" }));  
    } catch (error) {
        console.error("Error deleting data from DynamoDB:", error);
        res.writeHead(500);
        return res.end(JSON.stringify({ error: "Failed to delete user data" }));
    }
}

Here’s what I’ve checked so far:

  1. The DynamoDB table’s partition key is named userID (case-sensitive) and is of type String.

  2. The userID parameter is extracted correctly from the request query string, and its type is also String.

  3. The params object seems to be properly structured when logged:

    { TableName: 'Trivia-app-users', Key: { userID: 'someUserID' } }
    
  4. I’ve tested the GET request with the same table, and it retrieves data successfully.

Despite all this, the DELETE request consistently throws the ValidationException.

I’ve searched for solutions on Stack Overflow and consulted ChatGPT, but I haven’t found anything that resolves the issue.

What could be causing the ValidationException for the DELETE request, and how can I fix it?

Electron-updater always requests “update.xml” and I don’t know how to remove it

I’m using Electron with electron-updater for auto-updating, but I’m facing an issue where it’s always trying to request an update.xml file, and I don’t want that. I’m getting the following error:

Error: ENOENT: no such file or directory, open '/Users/leo/Desktop/projects/bloxyspin 3.1 global-eng/client/app/APP VERSIONS/darwin/bloxyspin-darwin-arm64/bloxyspin.app/Contents/Resources/app-update.yml'

This is the code I’m using:

const { app, BrowserWindow, ipcMain, session } = require('electron');
const { autoUpdater } = require('electron-updater');
const path = require('path');
const packageJson = require('./package.json');

let mainWindow;
let loaderWindow;

autoUpdater.autoDownload = true;
autoUpdater.autoInstallOnAppQuit = true;

function createLoaderWindow() {
  const window = new BrowserWindow({
    width: 300,
    height: 200,
    resizable: false,
    fullscreenable: false,
    frame: false,
    alwaysOnTop: true,
    transparent: true,
    webPreferences: {
      contextIsolation: true,
      enableRemoteModule: false,
      preload: path.join(__dirname, 'preload.js'),
    },
    show: false,
  });

  window.loadFile('./appfiles/loading/index.html');
  window.once('ready-to-show', () => {
    window.show();
    window.webContents.send('update-status', 'Checking for Updates...');
    setTimeout(() => {
      autoUpdater.checkForUpdates();
    }, 2000);
  });

  return window;
}

function createMainWindow() {
  mainWindow = new BrowserWindow({
    width: 1024,
    height: 768,
    frame: false,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
    },
  });

  mainWindow.loadFile('./appfiles/app/index.html');
  mainWindow.once('ready-to-show', () => {
    loaderWindow.close();
    mainWindow.show();
    mainWindow.maximize();
  });
}

autoUpdater.on('update-available', (info) => {
  loaderWindow.webContents.send('update-status', 'Update Available! Downloading...');
});

autoUpdater.on('error', (err) => {
  loaderWindow.webContents.send('update-status', err);
});

autoUpdater.on('update-downloaded', (info) => {
  loaderWindow.webContents.send('update-status', 'Update Downloaded! Installing...');
  autoUpdater.quitAndInstall();
});

autoUpdater.on('update-not-available', () => {
  loaderWindow.webContents.send('update-status', 'starting...');
  setTimeout(() => {
    createMainWindow();
  }, 1000);
});

function createMenuTemplate() {
  return [
    {
      label: 'File',
      submenu: [
        { label: 'Restart', click: () => app.relaunch() && app.exit() },
        { label: 'Quit', click: () => app.quit() },
      ]
    },
    {
      label: 'Edit',
      submenu: [
        { role: 'undo' },
        { role: 'redo' },
        { type: 'separator' },
        { role: 'cut' },
        { role: 'copy' },
        { role: 'paste' },
        { type: 'separator' },
        { role: 'selectall' },
      ]
    },
    {
      label: 'View',
      submenu: [
        { role: 'reload' },
        { role: 'toggledevtools' },
        { type: 'separator' },
        { role: 'back' },
        { role: 'forward' },
      ]
    },
    {
      label: 'Help',
      submenu: [
        { label: 'Check for Updates', click: () => checkForUpdates() },
        { label: 'Report Bug', click: () => require('electron').shell.openExternal("https://discord.gg/bloxyspin") },
        {
          label: 'About',
          click: () => openAboutWindow(),
        },
      ]
    }
  ];
}

function openAboutWindow() {
  const aboutWindow = new BrowserWindow({
    width: 400,
    height: 300,
    resizable: false,
    fullscreenable: false,
    minimizable: false,
    title: 'About',
    webPreferences: {
      contextIsolation: true,
    },
  });

  aboutWindow.loadFile('./appfiles/loading/index.html');
  aboutWindow.once('ready-to-show', () => {
    aboutWindow.webContents.send('update-status', `Version ${packageJson.version}`);
    aboutWindow.show();
  });
}

app.on('ready', () => {
  loaderWindow = createLoaderWindow();
  autoUpdater.checkForUpdates();
});

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  if (!mainWindow) {
    loaderWindow = createLoaderWindow();
    autoUpdater.checkForUpdates();
  }
});

ipcMain.on('set-cookie', (event, cookie) => {
  const ses = session.fromPartition('persist:my-app');
  ses.cookies.set(cookie)
    .then(() => console.log('Cookie set:', cookie))
    .catch(err => console.error('Error setting cookie:', err));
});

ipcMain.handle('get-cookies', async () => {
  const ses = session.fromPartition('persist:my-app');
  try {
    const cookies = await ses.cookies.get({});
    return cookies;
  } catch (err) {
    console.error('Error getting cookies:', err);
    throw err;
  }
});

Why is autoUpdater looking for the update.xml file and how to stop it from doing so?

how to create a new vite react project without boilerplate code?

When creating a new React-Typescript project with:

npm create vite@latest

I get a new project with a lot of boilerplate code, like CSS, components and images that I have to remove in order to start coding. This is getting annoying every time I have to create a project.

I explore all the options available in the menu, but I couldn’t find any.