Using 0 after selecting form to reset

I didn’t get why we use 0 after selecting form to rest in jquery?
Can anyone help

I tried on beforeSend method in Ajax jquery, but I found we can reset the total form with reset() option, and can show our messages too that we sent through json encode from php file

Calculadora de IMC – Primeiro projeto de HTML com CSS e JavaScript inline [closed]

Calculadora de IMC
Calculadora simples de IMC (Índice de Massa Corporal) feita com HTML, CSS e JavaScript.
Aqui está: https://nicolasbraganca.github.io/calculadora-imc/

Funcionalidade
Calcula o IMC a partir da altura e peso informados pelo usuário.
Exibe o resultado com base nas classificações da OMS.
Valor exibido é um número (índice), não uma porcentagem.
Observação
O IMC é um índice numérico, sem unidade ou símbolo de porcentagem. O resultado ajuda a identificar a faixa de peso da pessoa (normal, sobrepeso, etc).

Como usar
Informe sua altura (em metros).
Informe seu peso (em kg).
Clique em “Calcular”.
O resultado será exibido em forma de alerta.

Esse é o meu primeiro projeto postado aqui, embora eu ja tenha feito mais uns 2 em pouco mais de 2 semanas de estudos. Estou muito empolgado e feliz de estar conseguindo exercitar e aprender algo que eu tinha tanto medo. Então se você tem alguma dica, adendo ou até mesmo alguma palavra que vá me deixar ainda mais empolgado, espero que deixe aqui o seu comentário(nem sei se no github da para comentar haha).

Eu acredito que tenha conseguido exercer o que eu queria, embora precise de melhorias, estou orgulhoso desse projeto!
Adoraria de dicas de programação, tanto na parte de lógica de programação quanto de estudos iniciais!
Grato desde já!

Is bushatza a name [closed]

bushatzaneed to know what it is

I was thinking about it cause it keeps popping up is it what it looks like how do I know what to do with it if I could see where it’s coming from thenits possible I could fix what it is and stop it from happening

Parcel resolver-glob is not working as expected after upgrading to 2.14.4

I recently upgraded one of my project’s ParcelJS from version 2.13.3 to 2.14.4. Everything works as expected, except for the glob imports.

JS

import images from "../../../img/gallery/*.jpg";

export const data = [
    {
        id: 1,
        name: "Spread Sheets",
        files: "312",
    },
    {
        id: 2,
        name: "Documents",
        files: "4532",
    },
    {
        id: 3,
        name: "Downloaded Files",
        files: "15876",
    },
    ...
];

data.forEach((item) => {
    filePreview = `<div class="h-24 w-100">
                        <img src="${images[item.img]} " alt="">
                   </div>`;

    ...
});

.parcelrc

{
    "extends": "@parcel/config-default",
    "resolvers": [
        "@parcel/resolver-glob",
        "..."
    ]
}

After bulding, I see the images are not displaying and inspecting the image tags shows as below:

<img src="[object Object] " alt="">

Also, console.log(images), returns only the file names and not the path.

{
    "1": {},
    "2": {},
    "3": {},
    "4": {},
    "5": {},
    "6": {},
    "7": {},
    "8": {},
}

(Here, 1, 2, 3… are the image names.)


I’m experiencing this issue only after upgrading Parcel to version 2.14.4 — everything was working fine in 2.13.3, so I’m not sure what exactly I’m missing.

I’ve also updated the import statement to

import * as images from "../../../img/gallery/*.jpg";

But the issue remains the same.

Why are curly braces required when a function is returned inside a function?

This code from a tutorial is working so this is a general knowledge question.
In the return {logout} line, why are curly braces required? I know to use them when multiple objects are returned from the function, but is this necessary when only a single function is being returned?

import { useAuthContext } from './useAuthContext';

export const useLogoutContext = () => {
const { dispatch } = useAuthContext();
    const logout = () => {
        //remove user from storage
        localStorage.removeItem('user');
        //dispatch logout action
        dispatch({ type: 'LOGOUT' });
    };
    return { logout };
};
import { Link } from 'react-router-dom'
import { useLogout } from '../hooks/useLogout'

const Navbar = () => {
  const { logout } = useLogout()

  const handleClick = () => {
    logout()
  }

  return (
    <header>
      <div className="container">
        <Link to="/">
          <h1>Workout Buddy</h1>
        </Link>
        <nav>
          <div>
            <button onClick={handleClick}>Log out</button>
          </div>
          <div>
            <Link to="/login">Login</Link>
            <Link to="/signup">Signup</Link>
          </div>
        </nav>
      </div>
    </header>
  )
}

export default Navbar

I tried removing the curly braces and it broke the code.

Saving a file using Google Drives API to a specific location

I have a PHP app that saves some information into a .CSV file. I want to upload it to my Google Drive.

This seems to upload the file:

$service = new Google_Service_Drive($client);

$fileMetadata = new Google_Service_Drive_DriveFile(array(
    'name'      => 'file.csv',
    'parents'    => [$FOLDER_ID]
));

$file = $service->files->create($fileMetadata, array(
    'data' => $product_data,
    'mimeType' => 'application/octet-stream',
    'uploadType' => 'multipart',
    'fields' => 'id'
));

This has some weird issues:

  1. To upload it to a specific folder, I have to know the FILE ID, as opposed to simply adding the path.

  2. It will continuously add files with the same name instead of overwriting the file.

After some research, I can use $service->files->update to overwrite the existing file. However, to do that, I would need to know the $file_id.

Is there a way to upload files using the path, as opposed to IDS?
Is there a way to create the file if it doesn’t exist, or overwrite it if it does?

I can only think of two ways to do this:

  1. Hardcode the file name and DIR ids, then update it if it ever changes.
  2. Write code that scans the drive to figure out if the folder and file ids

I am adapting from the Dropbox API, which comparatively was much more intuitive.

Any help is appreciated – thanks

PHP not releasing memory of variable

I have a server which has 2 PHP scripts that run continuously in the background. One of those scripts, for some reason, is not releasing memory and it’s making the other script fail because eventually I have no available RAM left on the server.

I created a pretty simple POC so you can check by yourself. Basically I have a function that checks the available RAM memory (using free command) three times, and after the first time I execute the function that makes memory be consumed and never released. I even tried gc_collect_cycles but nothing happens.

What amazes me, is that after the script finishes completely, if I go to my SSH and execute “free” all the used memory is indeed released however if I add a long sleep at the end o my script, the memory will keep being used. Notice that inside the function test() a local variable is created and it is explicitly unsetted, but for some reason PHP still holds the memory.

<?php

set_time_limit(0);
ini_set("memory_limit","-1");



function show_available_ram() {

    $temp1111 = shell_exec('sudo free -m');

    preg_match("/Mem: +[0-9]+ +[0-9]+ +[0-9]+ +[0-9]+ +[0-9]+ +([0-9]+)/",$temp1111,$temp2222);

    return $temp2222[1] . " MB";

}



function test() {

    $temp3333 = array();
    
    for ($i=0;$i<1000000;$i++) {
        
        $temp3333[] = array("key1" => md5($i), "key2" => $i);
        
    }

    unset($temp3333);

}



echo "nAAA: " . show_available_ram();

test();

sleep(2);

echo "nBBB: " . show_available_ram();

//I know it should not be needed the line below, but I am trying it anyway but it does not help.
gc_collect_cycles();

sleep(2);

echo "nCCC: " . show_available_ram();

?>

The code above outputs:

AAA: 1297 MB
BBB: 873 MB
CCC: 869 MB

So you can clearly see memory being used (on BBB and CCC but not released even after test() has already finished.

In the code above I use a few sleep so PHP can have time to garbage collect, but it does not help at all.

How to Remove “Contact Information” section from WooCommerce Checkout Blocks?

I’m using WooCommerce and trying to customize the checkout page. At the top, there’s a “Contact Information” section that includes a required Email Address field.

enter image description here

I want the checkout form to start directly from the “Billing Details”, without showing the email field or “Contact Information” section at all.

I tried using the following code in my functions.php file:

add_filter('woocommerce_checkout_fields', 'remove_billing_email_field');
function remove_billing_email_field($fields) {
    unset($fields['billing']['billing_email']);
    return $fields;
}

I also tried other similar code snippets from different sources, but none of them removed that section, and the email field still appears.

Additionally, I used the plugin Checkout Field Editor for WooCommerce by ThemeHigh. Even after removing the email field from the “Billing” block form, it still appears at the top under “Contact Information”.

Most tutorials and YouTube videos show the checkout starting directly from Billing Details, but in my case, this extra top section appears.

How can I properly remove or hide the Contact Information section, including the email field, from the WooCommerce Checkout Blocks page?

I tried both custom code snippets and plugin-based solutions. I used the Checkout Field Editor for WooCommerce by ThemeHigh and removed the email field from the Billing block, but it still shows up in the “Contact Information” section.

I expected that removing the email field from either the billing fields or the plugin interface would completely hide the entire top section (including its heading), and the checkout form would start directly from the “Billing Details” section — just like shown in most tutorials.

But none of the methods I’ve used actually removed that top section. It continues to appear, even with the email field supposedly removed.

Why do I get an error when making JavaScript documentation with WebDoc?

I’m trying to do a documentation for my JavaScript little library. Because I don’t like the JSDoc appearance, I wanted to use WebDoc (npmjs.org/@webdoc/cli). I’ve installed the latest version, but when I execute webdoc, I find this error :

C:UserstakvorianeDocumentsGitHubmathlib>webdoc
This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason:
Error: Path contains invalid characters: docs<webdoc.internal>src
    at checkPath (C:UserstakvorianeApplicationsNode.jsnode_modules@webdocclinode_modulesfs-extralibmkdirsmake-dir.js:20:21)
    at module.exports.makeDir (C:UserstakvorianeApplicationsNode.jsnode_modules@webdocclinode_modulesfs-extralibmkdirsmake-dir.js:45:3)
    at Object.<anonymous> (C:UserstakvorianeApplicationsNode.jsnode_modules@webdocclinode_modulesuniversalifyindex.js:21:10)
    at C:UserstakvorianeApplicationsNode.jsnode_modules@webdocclinode_modulesfs-extraliboutputindex.js:20:11
    at C:UserstakvorianeApplicationsNode.jsnode_modules@webdocclinode_modulesuniversalifyindex.js:21:38
@webdoc took 1849ms to run!

C:UserstakvorianeDocumentsGitHubmathlib>webdoc

Here is my webdoc.conf.json :

{
  "$schema": "https://webdoc.nyc3.digitaloceanspaces.com/schemas/v1/webdoc.conf.schema.json",
  "source": {
    "include": [
      "./src"
    ],
    "exclude": [
      "node_modules"
    ]
  },
  "template": {
    "applicationName": "Vanilla.js"
  }
}

And here is src/main.js :

/**
 * @function isMultiple
 * @description This function checks whether a number is a multiple of another number.
 * @param {number} a - The number that is maybe a multiple of the other
 * @param {number} b - The number that is maybe a divisor of the other
 * @returns {boolean}
 * @example
 * console.log(isMultiple(3, 6)) // True because 6 / 3 = 2 with remainder 0
 * console.log(isMultiple(5, 8)) // False because 8 / 5 = 1 with remainder 3
 */

export const isMultiple = (a, b) => {
    if (typeof a !== "number") {
        throw new TypeError(`'a' must be of type 'number', not '${typeof a}'.`)
    }

    if (typeof b !== "number") {
        throw new TypeError(`'b' must be of type 'number', not '${typeof b}'.`)
    }
    
    return b % a === 0
}

Why do I get this error and how can I fix it?

Change CSS style of external JavaScript script?

Hey I am trying to change some CSS styles of an external JavaScript script (igv.js). I run this script embedded in an HTML file as suggested here.

<div id="igv_div">
<script type="module">
    import igv from "https://cdn.jsdelivr.net/npm/[email protected]/dist/igv.esm.min.js"
    const div = document.getElementById("igv_div")
    const config = {
            genome: "hg19"
    }
    const browser = await igv.createBrowser(div, config) 
</script>
</div>

I was able to change some colors globally at once using somtehing like this:

<style>
#igv_div {filter: invert(88%);}
</style>

However, nothing I try changes individual elements. When, I simply try to set the CSS style of an element in the HTML header it seems that this is completely ignored.

<style>
.igv-track-label {color: red;}
</style>

However, I can manipulate it using the selector in the browser directly, so I guess the style is hardcoded somewhere in the script itself and overrides my modified CSS. Is there a way of overriding the style of the script without changing the script itself, when running it from an HTML file?

How to make the setter function in react asynchronous

I have a situation, where I am rendering Rows inside another row, where the first row is an accordion. On click of the row, the API call happens and the resultant data is showed in the row inside

So my approach was

to have an accordionData which is an object and when the user clicks:

  1. I get rowId
  2. Do the API call
  3. Set the accordionData
  4. Set its corresponding states(for loader) to false, each row has its loading state

CODE:
`const [accordionData, setAccordionData] = useState({});
const [loading, setLoading] = useState<Record<string, boolean>>({});

// Used RTK Query
const {
    data: accordionRowDetails,
    isFetching: accordionFetching,
    isLoading: accordionLoading,
    isError: accordionError,
} = useGetJobNodeQuery(rowId, {
    skip: !rowId,
});

// Toggle accordion for API call
const handleToggleAccordion = (rowId: string) => {
    const isCurrentlyOpen = openRows[rowId] || false;

    setOpenRows((prev) => ({
        ...prev,
        [rowId]: !isCurrentlyOpen,
    }));

    if (!isCurrentlyOpen && !accordionData[rowId]) {
        setLoading((prev) => ({
            ...prev,
            [rowId]: true,
        }));

        setRowId(rowId);
    }
};

useEffect(() => {
    if (accordionRowDetails && rowId) {
        setAccordionData((prev: AccordionData) => ({
            ...prev,
            [rowId]: accordionRowDetails?.response || [],
        }));

        setLoading((prev) => ({
            ...prev,
            [rowId]: false,
        }));
    }

    if (accordionError && rowId) {
        console.error(
            `Failed to fetch accordion data for row ${rowId}:`,
            accordionError
        );

        setLoading((prev) => ({
            ...prev,
            [rowId]: false,
        }));

        setAccordionData((prev: AccordionData) => ({
            ...prev,
            [rowId]: [],
        }));
    }
}, [accordionRowDetails, accordionError, rowId]);`

Issue arises
The accordion data for that particular row and false setter for loader gets set together and the row shows up early, that too with old stale data. Need help to resolve this. How to get rid of this behavior?

Things tried

  1. Flush sync
  2. Combined the states into a single state (both accordiondata and loader states).
  3. Adding a setTimeout for loader works, but this is not a healthy practice

None of these worked. I tried to create few promises as well but there seems to be some issue.

Need help

Thanks

How to trigger multiple actions (Open Off-Canvas Menu & Scroll to Top) with a single button in Avada Theme (WordPress)?

I’m using the Avada WordPress theme and have a menu trigger button in the Global Header that opens an Off-Canvas Menu (created using Avada’s Off-Canvas builder).

Right now, clicking the button successfully opens the Off-Canvas menu.

What I want to do:

When the user clicks the trigger button, I want it to:

  1. Open the Off-Canvas Menu (current behavior)
  2. Scroll the page to the top (new behavior)

Is there a way to assign multiple actions to the same trigger in Avada? If not, how can I use JavaScript (preferably without breaking theme updates or overriding Avada’s core behavior) to achieve this?