HTML JS trigger button enter

Was trying to get this working that I saw from another post here. I got it working but I can get the enter to work. I tried to tie in https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_trigger_button_enter but for the life of me cant get both to work.

Hope someone can help!

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>Untitled Page</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js"></script>

<script type="text/javascript">

$(document).ready(function(){

    $('#button').click(function(e) {  
        var inputvalue = $("#input").val();
        window.location.replace(" http://www.example.com/page/"+inputvalue);

    });
});
</script> 
</head>
<body>

       <input type="text" value="11" id="input"> 
       <button type="button" id="button">Click Me!</button>
</body>
</html>

Get value from few Select in Material-UI

I have two MUI Select components on my page. I’m trying to set values depends on id of Select. I’ve checked (id === “breed-select”) in console and (at first) it’s true, but immediately after that it become false, and i cant understand why. Where i made a mistake? May be there is a better way to set values of two Select components?

import React from 'react';
import './AddCatPopup.css';
import {Box, Button, FormControl, InputLabel, MenuItem, Select, TextField} from '@mui/material';
import {theme} from '../../theme';
import {ThemeProvider} from '@mui/material/styles';

function AddCatPopup({ breeds, isOpen, onClose, onAddCat }) {

  const breedsName = breeds.map(item => item.nameBreed);

  const colorsArray = [
    'black',
    'white',
    'grey',
    'red',
    'multicolor'
  ];

  const [name, setName] = React.useState('');
  const [price, setPrice] = React.useState(0);
  const [color, setColor] = React.useState('');
  const [age, setAge] = React.useState(0);
  const [breed, setBreed] = React.useState('');

  function handleChange(event) {
    const {
      target: { value, id }
    } = event;
    id === "breed-select" ? setBreed(value) : setColor(value);
  }

  function handleSubmit(e) {
    e.preventDefault();
  }

  return(
    <section className={`popup ${isOpen && 'popup_opened'}`}>
      <div className={'popup__container'}>
        <button type="button" className={'popup__close-btn'} onClick={onClose}></button>
        <p className={'popup__title'}>Enter info about cat</p>
        <TextField sx={{ mt: 1, mb: 1 }}
                   id="standard-required"
                   variant="standard"
                   label="Name"
                   required />

        <TextField sx={{ mt: 1, mb: 1 }}
                   id="standard-required"
                   variant="standard"
                   label="Price"
                   required />

        <FormControl sx={{ mt: 1, mb: 1 }}
                     variant="standard"
                     required>
          <InputLabel id="breed-label">Breed</InputLabel>
          <Select
            labelId="filter-breed"
            id="breed-select"
            label="Breed"
            value={breed}
            onChange={handleChange}
          >
            {breedsName.map((item) => (
              <MenuItem
                key={item}
                value={item}
                id="breed-select"
                onClick={handleChange}
              >
                {item}
              </MenuItem>
            ))}
          </Select>
        </FormControl>

        <FormControl sx={{ mt: 1, mb: 1 }}
                     variant="standard"
                     required>
          <InputLabel id="color-label">Color</InputLabel>
          <Select
            labelId="filter-color"
            id="color-select"
            label="Color"
            value={color}
          >
            {colorsArray.map((item) => (
              <MenuItem
                key={item}
                value={item}
                id="color-select"
                onClick={handleChange}
              >
                {item}
              </MenuItem>
            ))}
          </Select>
        </FormControl>

        <TextField sx={{ mt: 1, mb: 1 }}
                   id="standard-required"
                   variant="standard"
                   label="Age"
                   required />

        <ThemeProvider theme={theme}>
          <Button sx={{ mt: 1, mb: 1 }}
                  variant="contained"
                  color={'secondary'}
                  onClick={handleSubmit}>
            Add
          </Button>
        </ThemeProvider>

      </div>
    </section>
  );
}

export default AddCatPopup;

JSON parse in Javascript with [ [duplicate]

I am trying to parse this JSON file. I was able to get temp easy but I am not able to get main from the weather. I assume this is due to the “weather”: [ than normal JSON file.

Does anyone know how to parse this correctly to be able to access the weather.main data.

JSON file:

{
  "coord": {
    "lon": -4.5063,
    "lat": 55.6787
  },
  "weather": [
    {
      "id": 801,
      "main": "Clouds",
      "description": "few clouds",
      "icon": "02n"
    }
  ],
  "base": "stations",
  "main": {
    "temp": 3.72,
    "feels_like": 1.32,
    "temp_min": 3.07,
    "temp_max": 4.94,
    "pressure": 1024,
    "humidity": 75
  }

Here is my current parser:

async function getWeather(lat, lon) {
  const params = new URLSearchParams({
    lat,
    lon,
    units: "metric",
    appid: API_KEY,
  })
  return fetch(`https://api.openweathermap.org/data/2.5/weather?${params}`)
  .then(function (response) {
    return response.json()
  }).then(function (obj) {
    console.log(obj.main.temp)
    weatherTemp = obj.main.temp;
    console.log("OBJ" + obj.weather.main) // does not work, return undefined. Not able to access
    //weatherType = obj.weather.main;
    // print();
    // ContextMerge();
  }).catch(function (error) {
    console.log("Something went wrong" + error)
  });
  }

Nodejs Require is not defined while using reverse shell

If require is not available, to obtain the require by:

process = this.constructor.constructor(‘return (function(){return process})()’)();
var require = process.mainModule.require;

used

shell = ‘process = this.constructor.constructor(‘return (function(){return process})()’)();’

shell += ‘var require = process.mainModule.require;’

Errors: process is not defined
if we add const before process
Errors: mainModule is not defined

How do we import process without Require , and how do we process the code to server

How Can I target single item by map button in React Typescript?

So I have a functional components here:

export default function Test() {
    const [products, setProduct] = useState<any>([]);
    const [image, setImage] = useState<any>([""]);
    const [prices, setPrice] = useState<any>([]);
    const [showPrice, setShowPrice] = useState<boolean>(false);
    const [PhonePrice, setPhonePrice] = useState<any>("");


    useEffect(() => {
        async function loadProducts() {
            const res = await fetch("http://raw.githubusercontent.com/reborn094/Practice/main/data.json", {
                method: "GET",
            });
            const json = await res.json();
            const data = json.products;

            setProduct(data);

    return (
        <div>
                    {products.map((product: any, index: number) => {
                        return (
                            <Col>
                                <Card key={index} style={{ width: "20rem" }}>
                                    <Card.Body>
                                        <Card.Title>
                                        </Card.Title>
                                        <Card.Title>
                                            <Child ProductImage={image[index]} name={product.name} code={product.code}  onSelectProduct={()=>{  
                                             

> 

what should I write here????
------------------------

   
                                            }}
                                            ></Child>
                                           
                                        </Card.Title>
                                        <Card.Text></Card.Text>
                                    </Card.Body>
                                </Card>
                            </Col>
                        );
                    })}
        </div>
    );
}

And here is my Child components :

export default function Child(props:{
    onSelectProduct?:()=> void;
}) {
  return (
      <div>
        <Button onClick={props.onSelectProduct}></Button>
    </div>
  )
}

My question is What if I want to set button in Test components to target single item in list, what should I do? Because Now If I set Button that Button would trigger all item.What should I do in the function onSelectProduct?

Destructuring object with inner array without all keys

I have an object like this:

const objBefore: 
{
    "id": "3pa99f64-5717-4562-b3fc-2c963f66afa1",
    "number": "5000",
    "enabled": true,
    "classes": [
        {
            "id": "2fc87f64-5417-4562-b3fc-2c963f66afa4",
            "name": "General"
        },
        {
            "id": "7ffcada8-0215-4fb0-bea9-2266836d3b18",
            "name": "Special"
        },
        {
            "id": "6ee973f7-c77b-4738-b275-9a7299b9b82b",
            "name": "Limited"
        }
    ]
}

Using es6, I want to grab everything in the object except the name key of the inner classes array to pass it to an api.

So:

{
    "id": "3pa99f64-5717-4562-b3fc-2c963f66afa1",
    "number": "5000",
    "enabled": true,
    "classes": [
        {"id": "2fc87f64-5417-4562-b3fc-2c963f66afa4"},
        {"id": "7ffcada8-0215-4fb0-bea9-2266836d3b18"},
        {"id": "6ee973f7-c77b-4738-b275-9a7299b9b82b"}
    ]
}

The closest I got was: let {id, number, enabled, classes: [{id}]} = objBefore;

But it only gets me one id in classes. I’ve tried spreading above using [...{id}] or [{...id}]. Same thing.

I find it challenging to get the right mental model for how to think about this when it’s on multiple levels. In my mind, when I say [...{id}] I’m thinking, “I want the id property as an object in the outer classes array, but give me every id in the array!”

Clearly I’m not thinking about this correctly.

I’ve tried it using map to get that part but I’m still having trouble combining it back to the original to produce the desired result. for example:

let classIds = objBefore.classes.map(({id}) => {
    return {
        id 
    }
})

(Using the map syntax, how can I destructure in the function the other keys that are one level higher?)

To combine them I started trying anything and everything, :

let {id, number, enabled, classIds} = {objBefore, [...classIds]} // returns undefined for all

I’d prefer to do it in one statement. But if that’s not possible, then what’s a clean way to do it using map?.

How do you avoid an SQL injection vulnerability without a query builder or an ORM?

Suppose I have a function that looks like the following (ignore any syntax errors here unless they are relevant to the question, I’m new to SQL):

// This function updates the database using the command passed as a parameter
const execute = async (command) => {
    open({
        filename: "test.db",
        driver: sqlite3.Database,
    }).then((db) => {
        db.exec(command);
    });
};

// Takes the user ID and their input and adds it to the database
const createBlogPost = async (userId, text) => {
    await execute(`INSERT INTO posts (user_id, post) VALUES ("${userId}", "${text}");`)
}

There is nothing stopping the user from injecting their own SQL into the blog post text field. Wouldn’t they be able to execute any command they want as long as the syntax is correct? I’m wondering if there’s anything extra you’re supposed to do in order to prevent this, or if it’s best practice to just use an ORM rather than building your own SQL statements.

Many thanks.

Disconnect MutationObserver wrapped in self invoking function

I have created a JavaScript that uses MutationObserver to watch for changes to a website in the console. The script would retrieve some values from a div, log the accumulated sum and also create some elements on the page (omitted in the code below for simplicity).

I wrap the MutationObserver in a self Invoking function to prevent the variables from colliding with the ones used by the website.

Occasionally the script may fail (the script is not robust enough to deal with some differences in pages) and what I am doing is to log out of the page, paste a different script onto the console to make it work again. Or else the sum would be incorrect and the elements would be created in the wrong place.

I understand that the MutationObserver is on its own scope so observer.disconnect(); would not work. Is there other way to disconnect the MutationObserver in the console without having to refresh/log out of the page?

Here is the simplified version of my code:

(function () {  
    const targetNode = document.querySelector('div.content')
    const observerOptions = { childList: true, attributes: false, subtree: false }
    const callback = function (mutationsList, observer) {
      for (const mutation of mutationsList) {
        if (mutation.removedNodes.length > 0 && (mutation.removedNodes[0].classList.contains('some-view'))) {
            // do something here
        }
        if (mutation.addedNodes.length > 0 && (mutation.addedNodes[0].classList.contains('some-view'))) {
            // do something here
        }
      }
    }
  
    const observer = new MutationObserver(callback)
    observer.observe(targetNode, observerOptions)
  })()

Thank you.

Why Instagram “shortcode_media” is undefined?

I was trying to use a library to download videos from instagram, and it uses graphql, but it only downloads videos every now and then, other times it returns an error. The error:

TypeError: Cannot read properties of undefined (reading 'shortcode_media')

The code:

    async function downloadMetaData(url) {
      try {
        const metaData = await axios({
          method: "get",
          url: url,
        });
        return metaData.data.graphql;
      } catch (error) {
        throw error;
      }
    }
    
    function getMediaType(mediaData) {
      if (mediaData.shortcode_media.is_video === true) {
        return "video";
      }
      return "image";
    }

The link of library (if you need local tests)

Could anyone give me a suggestion on how to solve it or recommend another lib?

How do I make the router not render before all queries in a loop are done? (mongoDB) [duplicate]

I have this router:
// get your courses page

router.get('/yourcourses', async (req, res, next) => {
  let results = []
  if(req.user){
    for(let i =0; i<req.user.coursesFollowing.length; i++){
      let course = Course.findOne({ 'published': true, title: req.user.coursesFollowing[i].courseTitle, authorUsername: req.user.coursesFollowing[i].username }).exec(function (err, result) {
        if(err){return next(err)}
        results.push(result)
        console.log(results)
      })
    }
  }
  console.log(results)
  res.render('content', { whichOne: 1, user: req.user, courses: results});
});

I console log the result from the queries it seems to find the right documents, and when i console log the full array it seems okay,

however looking at the terminal I can see the computer prints the values after rendering the page, which means I need to use an async function to wait for the queries to end, however I am used to do it with one query, not multiple queries inside a loop, so how do I do that?

How do I wait until all the queries inside a loop are done before rendering the page? I tried using settimeout() however it is not predicting how much time it will take.
how would I fix this?

THANKS

Integromat / Make – Parse Website Address and Extract Domain?

I am trying to use an integration tool called Integromat (now know as Make) and they have a Text Parser option where I believe I can do what I want, but I am not sure how.

I am setting up a flow and have a webhook set up that receives a payload from another system. One of the fields in the payload is “website link”. It looks like this:

http://www.example.com and also like http://example.com

I want to remove the http:// and also the http://www. when it occurs and be left with the domain name.

I am not finding good search results for this problem as the company is named “make” so I get unintended results. I also looked through their docs and can’t find anything around string replacement that lines up with what I’m trying to do.

I’ve attached a screenshot if it helps show the text parser.

enter image description here

Reloading my React hook page causes my browser to trigger element

As the title already explains a lot of the problem,

I just developed a simple application in React Hook, my current routes are defined by


   <Router>
      <Routes>
        <Route exact path='/' element={<Home/>}/>
        <Route path='/products/:category' element={<ProductBrowsing/>}/>
        <Route path='/productsDetails/:id' element={<ProductDetails/>}/>
        <Route path='/login' element={<Login/>}/>
        <Route path='/register' element={<Register/>}/>
      </Routes>
    </Router>

testing all these routes in my local machine, it was possible to navigate in all pages either by calling the <Link> component or by putting directly through the URL

when I went to the process of deploying my application and putting it inside a VPS, I realized that a call by <Link> is passable unless the /:category attribute is not the same, which causes the page not to load even if the URL changes (and im passing a lot of parameters that doenst affect the page as a result of this), so the next solution imagined was to always refresh the page to force the component to load with the correct URL, but always when I try to refresh the page in my application I get an immediate response from the tag returning “You need to enable JavaScript to run this app.”

basically I can no longer navigate my application and im hopeful to know why

You can check this behavior here -> http://153.92.221.32/

by trying to navigate through the mega menu links inside the navbar and try to refresh the page, or simply change some subcategory inside the megamenu and notice that the URL changes and the components don’t.

React native wrapper component re-renders on each page navigation

I am developing an android app using react-native and i have a but of a struggle of figuring out why my component re-renders on each page navigation.

In my case i have created a wrapper component called Container.android.js

const Container = props => {
  useEffect(() => {
    // fetching some data from async storage
  },[])

  // Using my hook here
  const {code, error} = usePdaScan({ 
    onEvent: (code) => {
        // setting state via useState
    }, 
    onError: (error) => { 
        Alert.alert('Error', error); 
    }, 
    trigger: 'always'
  });

  return <View>
  {props.children}
  </View>
}

Then i declare routes with Stack.Screen where each stack uses a component wrapped with the Container component.

<Stack.Screen name="Overview" component={Overview} />

And my Overview compnent is this

const Overview = props => {
   return <Container>
        <Text>Overview page</Text>
   </Container>
}

My problem is that inside the Container component, there is a hook called usePdaScan. Each time i navigate to another page and the hook gets called, the Container component re-renders twice… I cant get a lead on this… Halp!