The script attribute used in html cannot run as expected [duplicate]

This is an example from w3school, I practice typing html, but I don’t know where is the problem
My intention is for the button to hide the city element, but somehow the button doesn’t work.

<!DOCTYPE html>
<html>
    <head>
        <meta charset = "utf-8">
    </head>
    <body>
        <button onclick = "myFunction()">Hide Elements</button>
        <h2 class = "London">London</h2>
        <p>london is beautiful.</p>

        <h2 class = "Tokyo">Tokyo</h2>
        <p>Tokyo is beautiful.</p>

        <h2 class = "Paris">Paris</h2>
        <p>Paris is beautiful.</p>

        <script>
            function myFunction(){
                var x = document.getElementsByClassName("city");
                for(var i= 0;i < x.length;i++){
                    x[i].style.display = "none";
                }
            }
        </script>
    </body>
</html>

Testing a react component using custom hooks with crud operations functions

I am trying to test a functional component (AddTodo). AddTodo is using a custom hooks which is returning todoList, addItemInTodoList and other functions. I’m mocking the custom hook and using mockResolvedValueOnce to set the todoList and other functions. Is this the right approach to test react component using custom hook.

Here is my AddTodo component

import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import useTodoList from '../hooks/useTodoList';
import Button from '../Components/button';
import Input from '../Components/input';

function AddTodo() {
  const navigate = useNavigate();
  
  const { todoList, addItemInTodoList } = useTodoList();
  const [todoText, setTodoText] = useState('');

  const handleTodoTextChange = (e) => {
    if(e.key === 'Enter') {
      handleAddItemClick();
      return;
    };
    setTodoText(e.target.value);
  };

  const handleAddItemClick = async () => {
    let data = {
      key: todoList.length + 1,
      text: todoText,
      date: new Date().toLocaleString()
    };
    const result = await addItemInTodoList(data);
    if (result) {
      navigate('/');
    }
  };

  return (
    <div className='flex flex-col w-25'>
      <h2>Add Todo Item</h2>
      <div className='flex'>
        <Input placeholder='Write something' value={todoText} onChange={handleTodoTextChange} onKeyPress={handleTodoTextChange} />
        <Button type='primary' value='Add' onClick={handleAddItemClick} />
      </div>
    </div>
  );
}

export default AddTodo;

Here is my useTodo custom Hook

import { useState, useEffect } from 'react';

export default function useTodoList(todoItemKey) {
  const CACHE_NAME = "todo-list";
  const ENDPOINT = "https://localhost:3000";

  const [todoList, setTodoList] = useState([]);

  const [selectedTodoItem, setSelectedTodoItem] = useState({});

  useEffect(() => {
    const todoItem = todoList.find(item => item.key === parseInt(todoItemKey));
    setSelectedTodoItem(todoItem);
  }, [todoList]);

  useEffect(() => {
    const getTodoList = async () => {
      try {
        const cache = await caches.open(CACHE_NAME);
        const response = await cache.match(ENDPOINT);

        if (!response) {
          return;
        }

        const responseBody = await response.json();
        setTodoList(responseBody);
      } catch (error) {
        console.log("getToken error:", { error });
      }
    };
    getTodoList();
  }, []);

  const addItemInTodoList = async (data) => {
    const updatedTodoList = [...todoList, data]
    try {
      const cache = await caches.open(CACHE_NAME);
      const responseBody = JSON.stringify(updatedTodoList);
      const response = new Response(responseBody);
      await cache.put(ENDPOINT, response);
      return true;
    } catch (error) {
      console.log("saveToken error:", { error });
      return false;
    }
  };

  const updateItemInTodoList = async (data) => {
    let updatedTodoList = todoList.filter(item => item.key !== data.key);
    updatedTodoList = [...updatedTodoList, data];
    updatedTodoList = updatedTodoList.sort((a, b) => new Date(a.date) - new Date(b.date));
    try {
      const cache = await caches.open(CACHE_NAME);
      const responseBody = JSON.stringify(updatedTodoList);
      const response = new Response(responseBody);
      await cache.put(ENDPOINT, response);
      return true;
    } catch (error) {
      console.log("saveToken error:", { error });
    }
  };

  const deleteItemInTodoList = async (todoItemKey) => {
    const updatedTodoList = todoList.filter(item => item.key !== todoItemKey);
    try {
      const cache = await caches.open(CACHE_NAME);
      const responseBody = JSON.stringify(updatedTodoList);
      const response = new Response(responseBody);
      await cache.put(ENDPOINT, response);
      setTodoList(updatedTodoList);
    } catch (error) {
      console.log("saveToken error:", { error });
    }
  };

  return { todoList, addItemInTodoList, updateItemInTodoList, deleteItemInTodoList, selectedTodoItem, setSelectedTodoItem };
}

Here is my AddTodo test

import { fireEvent, getByText, render } from '@testing-library/react';
import '@testing-library/jest-dom';
import { MemoryRouter } from 'react-router-dom';
import useTodoList from '../hooks/useTodoList';
import AddTodo from '../Pages/AddTodo';

jest.mock('../hooks/useTodoList');

afterEach(() => {
  jest.clearAllMocks()
})

test('should render add todo page', () => {
  useTodoList.mockResolvedValueOnce({ todoList: [], addItemInTodoList: () => { }, updateItemInTodoList: () => { }, deleteItemInTodoList: () => { }, selectedTodoItem: {}, setSelectedTodoItem: () => { } });
  const { getByPlaceholderText } = render(
    <MemoryRouter>
      <AddTodo />
    </MemoryRouter>
  );

  const input = getByPlaceholderText(/write something/i);
  expect(input).toBeInTheDocument();

  fireEvent.change(input, { target: { value: 'Todo Item 1'} });

  const btn = getByText(/add/i);
  fireEvent.click(btn);

  expect(addItemInTodoList).toBeCalledWith(/todo item 1/i);
});

How to implement sorting in mat-table using angular7

I am trying to implement sorting in using angular version 7.3.

Below is my source code:

<table
  mat-table
  [dataSource]='dataSource'>
  <ng-container matColumnDef="position">
    <th mat-header-cell *matHeaderCellDef> No. </th>
    <td mat-cell *matCellDef="let element"> {{element.position}} </td>
  </ng-container>
  <ng-container matColumnDef="name">
    <th mat-header-cell *matHeaderCellDef> Name </th>
    <td mat-cell *matCellDef="let element"> {{element.name}} </td>
  </ng-container>
  <ng-container matColumnDef="weight">
    <th mat-header-cell *matHeaderCellDef> Weight </th>
    <td mat-cell *matCellDef="let element"> {{element.weight}} </td>
  </ng-container>
</table>

Here is the javascript file source is:

const ELEMENT_DATA: PeriodicElement[] = [
  {position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H'},
  {position: 2, name: 'Helium', weight: 4.0026, symbol: 'He'},
  {position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li'},
  {position: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be'}
];

@Component({
  selector: 'table-basic-example',
  styleUrls: ['table-basic-example.css'],
  templateUrl: 'table-basic-example.html',
})
export class TableBasicExample {
  displayedColumns: string[] = ['position', 'name', 'weight', 'symbol'];
  dataSource = ELEMENT_DATA;
}

I am using angular version 7 and the sorting feature I am not able to write. Need help in that as I am new to angular

How to write a recursive function without setTimeout [closed]

Is there a way to make this function recursive without using setTimeout? Basically once all the work for the choicesObj[answer.choice]() is complete, I want to recall the prompt with the choices list. The problem right now is that it will call the prompt after 2 seconds even if the associated function with choicesObj[answer.choice]() is not done running.

const choicesObj = {
    'View all departments': viewDepartments, 
    'View all roles': viewRoles, 
    'View all employees': viewEmployees,
    'View employees by manager': viewByManager,
    'View employees by department': viewByDepartment, 
    'Add a department': addDepartment, 
    'Add a role': addRole,
    'Add an employee': addEmployee, 
    'Update an employee role': updateRole,
    'Update employee manager': updateManager,
    'Delete a department': deleteDepartment,
    'Delete a role': deleteRole,
    'Delete an employee': deleteEmployee,
    'EXIT': exitApp
}
const prompt = async () => {
    const answer = await inquirer.prompt({
        name: 'choice',
        type: 'list',
        message: 'What would you like to do?',
        choices: Object.keys(choicesObj)
    })
    if (answer) {
        choicesObj[answer.choice](); 
        setTimeout(function(){
            prompt(); // recursion after 2s
        }, 2000);
    }
};

Interpreting Uniswap V3 prices

I am quite new to Javascript and Uniswap. I am using Uniswap V3 to fetch the price from the DAI/USDC pool. My “main” funciton looks as follows:

async function main() {

  const [immutables, state] = await Promise.all([
    getPoolImmutables(),
    getPoolState(),
  ]);

  const DAI = new Token(1, immutables.token0, 18, "DAI", "Stablecoin");
  const USDC = new Token(1, immutables.token1, 6, "USDC", "USD Coin");

  const DAI_USDC_POOL = new Pool(
    DAI,
    USDC,
    immutables.fee,
    state.sqrtPriceX96.toString(),
    state.liquidity.toString(),
    state.tick
  );
  
  const token0Price = DAI_USDC_POOL.token0Price;

  console.log("The price is: ", token0Price);
}

And I am getting the following output:

The price is:  Price {
  numerator: JSBI(6) [
    435696740,
    805184612,
    508287463,
    671994784,
    427409972,
    4,
    sign: false
  ],
  denominator: JSBI(7) [ 0, 0, 0, 0, 0, 0, 4096, sign: false ],
  baseCurrency: Token {
    chainId: 1,
    decimals: 18,
    symbol: 'DAI',
    name: 'Stablecoin',
    isNative: false,
    isToken: true,
    address: '0x6B175474E89094C44Da98b954EedeAC495271d0F'
  },
  quoteCurrency: Token {
    chainId: 1,
    decimals: 6,
    symbol: 'USDC',
    name: 'USD Coin',
    isNative: false,
    isToken: true,
    address: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48'
  },
  scalar: Fraction {
    numerator: JSBI(2) [ 660865024, 931322574, sign: false ],
    denominator: JSBI(1) [ 1000000, sign: false ]
  }
}

The USDC price seems to make some sense (denominator, 1000000), however I am not sure how to interpret the DAI price from the output. If anyone can provide any hints or point me to a resource that explains the output, I would highly appreciate it. Thanks!

Not able to load React from import map json when using scopes

Error:
Application ‘navigation’ died in status LOADING_SOURCE_CODE: Unable to resolve bare specifier ‘react’ from https://localhost:3200/shared-lib/[email protected]

Import Map looks like:


    {
      "imports": {},
      "scopes": {
        "https://localhost:4000/ui/": {
          "react": "https://localhost:3200/shared-libs-ui/[email protected]",
          "react-dom": "https://localhost:3200/shared-libs-ui/[email protected]"
        }
      }
    }

How to pass function as prop to component in React

I have a component that generates input in Form. I’m trying to pass a function to OnChange event, but always getting error

import {  FormGroup, FloatingLabel, FormControl } from "react-bootstrap";

const FormInput = (props) =>{ 

return(

    <FormGroup controlId={props.controlId} className="mb-3"> 
    <FloatingLabel label={props.label}>
        <FormControl type={props.type} name={props.controlId} placeholder={props.label} onChange={props.onChange} />
    </FloatingLabel>
</FormGroup>
)

}

export default FormInput;

And in my App I’m passing props to Component. Can’t figure out how to pass function to get value on input

import React, { Component } from "react";
import {
Container,
Row,
Form,
Button,

} from "react-bootstrap";
import FormInput from "./FormInput";
import {  FormGroup, FloatingLabel, FormControl } from "react-bootstrap";


class AddRecipe extends Component {
constructor() {
super();
this.state = {
  recipeImage: "",
  recipeName: "",
  recipeIngredients: "",
};


this.handleChange = this.handleChange.bind(this);

}
handleChange = (e) =>{
this.setState({
  [e.target.name]: e.target.value,
});

}

render() {
return (
  <Container>
    <Row>

    
      <Form inline="true" className="mt-5">
        <FormInput
          controlId="recipeImage"
          label="Image URL"
          type="url"
          handleChange={this.handleChange}
        />
        <FormInput
          controlId="recipeName"
          label="Recipe Name"
          type="text"
          handleChange={this.handleChange}
        />
        <FormInput
          controlId="recipeIngredients"
          label="Ingredients"
          type="textarea"
          handleChange={this.handleChange}
          
        />

        <Button>Add</Button>
      </Form>
    </Row>
  </Container>
);
}
}

export default AddRecipe;

How to pass handleChange function as props, so I can write value to my state?

.getElementByClassName doesn’t recognize Ajax.GET elements?

This is the problem that i encountered:

I have an api that makes an Ajax.GET and in the success function, creates a button, a div, and a bunch of span with information in it, and a class for each one of them.
That same GET, shows all the info of the db correctly inside of a already existing div in the HTML document, but when i want to make a function which the result does a “console.log(“clicked”)”, it doesn’t recognize the data from the get.

If I make a button with a class, it does recognize it tho.

What am i doing wrong? Thanks in advance!

enter image description here

Not able to access camera on application deployed on heroku

Me and my friends build this project on face detection and tracking using opencv,flask, python and mediapipe. We deployed our project on Heroku (https://face1-detection.herokuapp.com/) but found out that video = VideoCapture(0) does not work when hosted. I tried searching on Stackoverflow but they did not worked for me. I am just beginner in socket.io and other such stuff.I have no idea regarding how to solved this problem.
Please help me to resolve this issue. It helps a lot.
Thank you.

javascript libraries can’t work together on Firefox but works fine in Chrome or Edge

I have two javascript libraries: interact.js and sortable.js, the first is used to resize html elements like div, the second is used to order html elements in screen like a list.

Libraries works fine in Chrome and Edge but in Firefox sortable.js is working and interact.js is not working, if i change to touch simulation mode in Firefox (like tablet touch screen) now interact.js is working and sotable.js not (reverse effect).

Firefox developer console shows nothing, i have no clue about a possible error or debug information.

I would like to know:

  1. Is there any software tool or browser developer tools option to
    visualize any library conflict or firefox diference compared with
    chrome ? in order to detect and solve this issue.
  2. Why Firefox manage methods not exactly like Chrome ?, what could be happen in this case ?
  3. There is probably a click conflict since we use click to drag element and order in the list (sortable.js) and the same click in corner to resize elements (interact.js), how can i get debug information from this in order to solve in Firefox ???

Regards

How to get attribute from the button that i click?

sorry for my english first.
I have the following problem: i have some buttons named stripe_pro_new, stripe_pro_new2, stripe_pro_new3 etc.
And i have 2 functions that return 2 attributes. how can i return the attribute of the button that i press? (current function return the attributes for “stripe_pro_new

button example:

<button id="stripe_pro_new" name="pro_plan" data-name="<?php echo __( 'Month' );?>" data-price="<?php echo (float)$config->basic_pro_plan;?>" class="btn stripe valign-wrapper"><?php echo __( 'buy_now' );?> <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path fill="currentColor" d="M20,8H4V6H20M20,18H4V12H20M20,4H4C2.89,4 2,4.89 2,6V18A2,2 0 0,0 4,20H20A2,2 0 0,0 22,18V6C22,4.89 21.1,4 20,4Z"></path></svg></button>

functions that return the attribute stripe_pro_new:

function getDescription()
   {
        var val = document.getElementById("stripe_pro_new").getAttribute("data-name");  
        return val;
   }
   function getPrice()
   {
        var val1 = document.getElementById("stripe_pro_new").getAttribute("data-price");  
        return val1;

   }

Getting confused that how to code this download function in javascript

I host a static html file on netlify here is the url…

https://laughing-lewin-eb42f8.netlify.app/

How can I code these download function, because if I define the image url with https://cors-anywhere.herokuapp.com like… var url = 'https://cors-anywhere.herokuapp.com/https://c4.wallpaperflare.com/wallpaper/203/636/834/minimalism-landscape-digital-windows-11-hd-wallpaper-preview.jpg';
Then I’m successfully download the images but when I trying to open the image file it show that it appears that we don’t support this file format

And if I define the url without https://cors-anywhere.herokuapp.com like…var url = 'https://c4.wallpaperflare.com/wallpaper/203/636/834/minimalism-landscape-digital-windows-11-hd-wallpaper-preview.jpg';Then it’s throw CORS error Access Control Allow Origin error and onething that I did not access the server side to configure Access Control Allow Origin because I host this site
on platform like github page, netlify or google blogger so how can I do that….

Can any one please give any idea…….

how to add child node using node-html-parser?

I’m trying to add a child node using node-html-parser

my html file looks like this:

...

 <tbody>
    <tr></tr>
   ...
 </tbody>
    

and node.js app:

const parse = require('node-html-parser').parse;

...

  const doc = parse(fs.readFileSync('./myfile.html','utf8'));
  doc.querySelector("tbody").appendChild("<tr></tr>");

but it’s giving an error:

Cannot create property 'parentNode' on string '<tr></tr>'