How to get javascript value of html data with Jsoup in Java

I’ve been using Jsoup for a long time. I need to get values of a wheather conditions.

That’s the link i’m work on : https://www.mgm.gov.tr/tahmin/il-ve-ilceler.aspx?il=ANKARA&ilce=

The problem here: I can’t directly access the values I want.

As you can see at below i need to access values which is showing in picture.enter image description here

The question is how can i access the data generated by javascript in html ?

How to write array elements to a rangelist using Google Apps Script?

I have this rangelist as the destination and a row of values that should be written to the destination.
I was thinking of iterating through the row of data and also through th rangelist and set value along the way, but I can’t find a way to iterate through the elements in the row of data.
Here’s the piece of code I’m working on:

let data = [];
  for (let i = 0; i < values.length; i++) {
    if (values[i][0] == ref && values[i][4] == variac) {
      data.push(values[i])
    }
  }
  const destRng = [
    "B5", "D5", "G5", "I5", "M5",
    "B7", "H7",
    "B9",
    "C12", "C14", "C16", "C18", "C20", "C22", "C24",
    "B27", "E27", "H27", "L27",
    "B29",
    "B32", "E32", "H32", "L32",
    "B34", "E34", "H34", "L34",
    "B36", "E36",
    "B40", "F40", "J40",
    "B42",
    "B44", "F44", "J44",
    "B46", "F46", "J46",
    "B48", "F48", "J48",
    "B50",
    "D53",
    "D55",
    "B58", "D58", "G58", "I58", "L58",
    "B61", "E61", "G61", "J61",
    "B65", "G65"
  ]

  Logger.log('Data: ' + data)

  const rngList = sheetCadProd.getRangeList(destRng).getRanges();
  for (let n = 0; n < data.length; n++) {
    for (let i = 0; i < rngList.length; i++) {
      let dado = data[n] 
      rngList[i].setValue(dado)//It sets the first value throughout the rngList
    }
  }
}

Now, this is getting the first element of data and writing it to all destination cells. How can I go through these data elements?

Thank you!

Why is a function I expect to be shaken from a tree still there on a create-react-app build?

Similar to Tree shaking create-react-app? but more of how to validate and fix.

So I have a created a library of react hooks. In there I added an example to help me understand how tree-shaking would work.

import { useClock, useDeepState } from '@trajano/react-hooks';
export function App(): JSX.Element {
  useClock();
  useDeepState("foo");
  return <div>Hello world</div>
}

However, there’s a function called useAsyncSetEffect that I added in my library code base, but tracing through the code for useClock and useDeepState I don’t hit that function at all, but when I look at the generated files I see a reference to useAsyncSetEffect.

Not really sure what’s causing it, the library isn’t large so the size is just a K gzipped, but I am curious as to why it is being included.

POST http://localhost:7500/api/users/posts 400 (Bad Request)

So I am trying to save some data into a mongodb data base using axios
I created a form to fill then when i click on save the data must be saved.

this is my try:

import auction1 from '../../Images/auction1.png'
import {useState} from 'react';
import './HomeScreen.css'
import {Button, Modal } from 'react-bootstrap';
import axios from 'axios';

const HomeScreen = ()=>{

    const [show, setShow] = useState(false);
    const handleClose = () => setShow(false);
    const handleShow = () => setShow(true);

    
    const [name, setName] = useState("");
    const [price, setPrice] = useState(null);
    const [deadline, setDeadLine] = useState("");
    const [description, setDescription] = useState("");

    const [img, setImg] = useState("");

    const [imgMessage, setImgMessage] = useState(null);
    const [error, setError] = useState(false);


    const handleSubmit = async(e)=>{

        e.preventDefault();

        try{
            const config = {
                headers: {
                    "Content-Type": "application/json",
                }
            }

            const {data} = await axios.post("http://localhost:7500/api/users/posts",
            {name, img, deadline, price, description}, 
            config
            );

            console.log(data);

        }catch(error){
            console.log(error.response.data.message);
        }
    };


    const postDetails = (pic)=>{

        if(!pic){
            return setImgMessage('Please select a picture');
        }

        setImgMessage(null);

        if(pic.type === 'images/jpeg' || pic.type==='image/png'){
            const data = new FormData();
            data.append('file', pic);
            data.append('upload_preset', 'battta');
            data.append('cloud_name', 'ChkounZed');
            fetch("https://api.cloudinary.com/v1_1/ChkounZed/upload", {
                method: 'post',
                body: data
            })
            .then((res)=> res.json())
            .then((data)=> {
                console.log(data);
                setImg(data.url.toString())
            })
            .catch((error)=>{
                console.log(error);
            });
        }else{
            return setImgMessage('Please select a picture');
        }
    };


    
    return(
        <div className="container bg">
            <img src ={auction1} className='landing-image' />
            <div style={{marginLeft:460}}> 
                <Button variant="primary" onClick={handleShow}>
                    Create Post
                </Button>
            </div> 
            <Modal show={show} onHide={handleClose}>
                <form onSubmit={handleSubmit}>
                    <Modal.Header closeButton>
                        <Modal.Title>Create Post</Modal.Title>
                    </Modal.Header>
                    <Modal.Body>
                        <form >
                            <div className="form-group">
                                <label>Post Name:</label>
                                <input type="text" className="form-control" placeholder="Enter Name"
                                value={name} onChange={(e)=> setName(e.target.value)}/>
                            </div>

                            <div className="form-group">
                                <label>Post Images:</label>
                                <input type="file" className="form-control" multiple onChange="readURL(this)" accept="Image/*" 
                                onChange={(e)=> postDetails(e.target.files[0])}/>
                            </div>

                            <div>
                                <label>Price:</label>
                                <input type="number" className="form-control" placeholder="TND"
                                value={price} onChange={(e)=> setPrice(e.target.value)}/>
                            </div>
                            <div>
                                <label>DeadLine:</label>
                                <input type="datetime-local" className="form-control"
                                value={deadline} onChange={(e)=> setDeadLine(e.target.value)}/>
                            </div>
                            <div>
                                <label>Description:</label>
                                <textarea className="form-control" rows="3"
                                value={description} onChange={(e)=> setDescription(e.target.value)}/>
                            </div>
                        </form>
                    </Modal.Body>
                    <Modal.Footer>
                        <button type="submit" className="btn btn-primary" data-bs-dismiss="modal" onClick={handleClose} >
                            Save Post
                        </button>
                        <button type="submit" className="btn btn-secondary" data-bs-dismiss="modal" onClick={handleClose}>
                            Close
                        </button>
                    </Modal.Footer>
                </form>
            </Modal>
        </div>
    )

};

export default HomeScreen;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

that was my react component and the problem is that i keep getting a message that says the post already exists.

this is my postController from the backend side:

const Post = require("../Models/postModel");
const asyncHandler = require("express-async-handler");


const savePost = asyncHandler(async(req,res)=>{

    const {name, deadline, price, description, image} = req.body;
 

    const postExists = await Post.findOne({image});
    
    if(postExists){
        res.status(400);
        throw new Error('Post Already Exists');
    }

    const post = await Post.create({
        name,
        deadline,
        price,
        description,
        image
    });

    if(post){
        res.status(201).json({
            _id: post._id,
            name: post.name, 
            price: post.price, 
            image: post.image,
            deadline: post.deadline,
            description: post.description
        });
    }else{
        res.status(400);
        throw new Error('Error');
    }
});

module.exports = {savePost};

I would be so grateful if you can give me hand of this and by the way i wanna make my post unique using the images and still did not know how

JS password generator is only generating special characters

I’ve been working on a password generator website project and recently tried running the JS to check for any bugs. I noticed that it only generates and pushes out special characters from the special character list into the HTML text area. Could someone help me resolve this issue?

Generator code in question (without two of the trigger functions that just run the generators an increased number of times and the needed arrays):

var UpperGenVariable;
var LowerGenVariable;
var NumGenVariable;
var SpecialGenVariable;

function Basic () {
    for (var i = 1; i <= 4; i++) {
       let FUNNY = Math.floor(Math.random(1,4));

       if (FUNNY = 1) {
           UppercaseGenerate();
       } else if (FUNNY = 2) {
           LowercaseGenerate();
       } else if (FUNNY = 3) {
           NumGenerate();
       } else (FUNNY >= 4); {
           SpecialGenerate();
       }
    }
};

let passwordGen = document.getElementById("PasswordDisplay")

function UppercaseGenerate() {
    var Upperfiltered = [];
    UppergenVariable = Math.floor(Math.random() * LetterIDList.length);
    for (var i = 0; i < LetterIDList.length; i++) {
        if (LetterIDList[i] == UpperGenVariable) {
            UpperFiltered.push(UppercaseList[i]);
        }
    };
    console.log(UpperFiltered);
    passwordGen.value += UpperFiltered
};

function LowercaseGenerate() {
    var LowerFiltered = [];
    LowerGenVariable = Math.floor(Math.random() * LetterIDList.length);
    for (var i = 0; i < LetterIDList.length; i ++) {
        if (LetterIDList[i] == LowerGenVariable) {
            LowerFiltered.push(LowercasList[i]);
        }
    };
    console.log(LowerFiltered);
    passwordGen.value += LowerFiltered
};

function Numgenerate() {
    var NumFiltered = [];
    NumGenVariable = Math.floor(Math.random() * NumIDList.length);
    for (var i = 0; i < NumIDList.length; i++) {
        if (NumIDList[i] == NumGenVariable) {
            NumFiltered.push(NumList[i]);
        }
    };
    console.log(NumFiltered);
    passwordGen.value += NumFiltered
};

function SpecialGenerate() {
    var SpecialFiltered = [];
    SpecialGenVariable = Math.floor(Math.random() * SpecialIDList.length);
    for (var i = 0; i < SpecialIDList.length; i++) {
        if (SpecialIDList[i] == SpecialGenVariable) {
            SpecialFiltered.push(SpecialCharList[i]);
        }
    };
    console.log(SpecialFiltered);
    passwordGen.value += SpecialFiltered
};

React brokes up if builds as NPM package

I want to create an NPM package. The code I use is working – I tested it inside another project. But when I try to separate this code from my the project everything brokes up with error

Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app

Here’s package.json

{
  "name": "some-name",
  "version": "0.0.1",
  "main": "dist/index.js",
  "types": "dist/index.d.ts",
  "peerDependencies": {
    "react": "^17.0.2",
    "react-dom": "^17.0.2"
  },
  "dependencies": {
    "@types/react": "^17.0.38",
    "@types/react-dom": "^17.0.11",
    "typescript": "^4.5.5"
  }
}

And the code of the package:

import { VFC, useMemo } from 'react';

export const someHOC = (Component: VFC) => {
    useMemo(() => [], []);

    return Component;
};

I build this code with tsc without any flags.


And for some reason I can’t use this package:

import React from 'react';
import ReactDOM from 'react-dom';
import { someHOC } from 'some-name';

const Some = someHOC(() => <div>asdasd1</div>);

ReactDOM.render(
    <Some/>,
    document.querySelector('#root'),
);

Could you please explain me where am I wrong?

Not able to call a method from InfoWindow in react js

I am trying to call a method on click of an element. The HTML is stored in a variable. It looks like below:

var cont = '<div class="infocontent" onClick="clickPoly('+index +')" style="width:100px;" >View More</div>';

const clickPoly = (index) => {
   var square = coordinates[index];
  
   if(square != undefined){
      square.dispatchEvent('click');
   }
}

clickPoly() should be called onclick of html above. But when I click on “View More”, it shows “clickPoly is not defined”.

Basically, I am showing multiple polygons on google map and on hover of each polygon I am showing infowindow. In infoWindow I need to show “View More” button and show relevant content.

You can see full code here

Google Maps API: Getting County FIPS Code

I’m trying to use JS to turn data from the Google Maps API from ZIP codes to county FIPS codes. I’m currently working on some other code that gets addresses from ZIP codes, but I can’t figure out how to get the FIPS code instead of the county name. Code is below; any help is appreciated.

// JS to turn ZIP codes into counties

<script language="javascript" src="https://maps.google.com/maps/api/js?key=AIzaSyBImpoY2A1QEcLqS5RXVV87eVM1TOg9iRM&sensor=false"></script>

<form>
zip: <input type="text" name="zip" value="46032"> <a href="#" onclick="getLocation()">Get Address</a>
</form>

<script language="javascript">
  function getLocation(){
    getAddressInfoByZip(document.forms[0].zip.value);
  }

  function response(obj){
    console.log(obj);
  }

  function getAddressInfoByZip(zip){
    if(zip.length >= 5 && typeof google != 'undefined'){
      var addr = {};
      var geocoder = new google.maps.Geocoder();
      geocoder.geocode({ 'address': zip }, function(results, status){
        if (status == google.maps.GeocoderStatus.OK){
          if (results.length >= 1) {
      for (var ii = 0; ii < results[0].address_components.length; ii++){
        var street_number = route = street = city = state = zipcode = country = formatted_address = '';
        var types = results[0].address_components[ii].types.join(",");
        if (types == "street_number"){
          addr.street_number = results[0].address_components[ii].long_name;
        }
        if (types == "route" || types == "point_of_interest,establishment"){
          addr.route = results[0].address_components[ii].long_name;
        }
        if (types == "sublocality,political" || types == "locality,political" || types == "neighborhood,political" || types == "administrative_area_level_3,political"){
          addr.city = (city == '' || types == "locality,political") ? results[0].address_components[ii].long_name : city;
        }
        if (types == "administrative_area_level_1,political"){
          addr.state = results[0].address_components[ii].short_name;
        }
        if (types == "postal_code" || types == "postal_code_prefix,postal_code"){
          addr.zipcode = results[0].address_components[ii].long_name;
        }
// County data line
        if (types == "administrative_area_level_2,political"){
          addr.county = results[0].address_components[ii].long_name;
         }
        if (types == "country,political"){
          addr.country = results[0].address_components[ii].long_name;
        }
      }
      addr.success = true;
      for (name in addr){
          console.log('### google maps api ### ' + name + ': ' + addr[name] );
      }
      response(addr);
          } else {
            response({success:false});
          }
        } else {
          response({success:false});
        }
      });
    } else {
      response({success:false});
    }
  }

</script>

“super() call outside constructor” eslint REACT JS

I’m practicing in React JS. I made the elementary counter through a class.

import React from 'react';

class ClassCounter extends React.Component {
construct(){
  super();
  this.state = {
    count: 0
  }
}
  incriment() {
    this.setState({this.state.count + 1})
  }

  decrement() {
    this.setState({this.state.count - 1})
  }
  render() {
  return (  
  <div>
    <h2>{this.count}</h2>
    <button type="button" onClick={this.incriment}>Incriment</button>
    <button type="button" onClick={this.decrement}>Decrement</button>
  </div>
)
}
}

Everything seems to be working. But my project has ESlint.
And it throws the following errors

  1. appears before super() – “super() call outside constructor of a subclass eslint”
  2. appears after this {this.state.count + 1} – “Expected “:”.ts(1005)” (I think this error comes out of the first one.)

Here is .json

{
    "env": {
        "browser": true,
        "es2021": true
    },
    "extends": [
        "plugin:react/recommended",
        "airbnb"
    ],
    "parserOptions": {
        "ecmaFeatures": {
            "jsx": true 
        },
        "ecmaVersion": "latest",     
        "sourceType": "module"
    },
    "plugins": [
        "react"
    ],
    "rules": {
    }
}

I have already read literaly everything, the only hope is your help guys.

JS error when defining a prototype method – V[a].exec is not a function [duplicate]

I defined the following method. But before I want to call method somewhere, I’m getting a Jquery error.

Object.prototype.getType = function () {
    return (typeof this.valueOf());
};

Console:

jquery.min.js:2 Uncaught TypeError: V[g].exec is not a function
    at ga.tokenize (jquery.min.js:2:19325)
    at ga.select (jquery.min.js:2:22349)
    at Function.ga (jquery.min.js:2:7308)
    at Function.a.find (jquery-migrate.min.js:2:1675)
    at r.fn.init.find (jquery.min.js:2:24958)
    at a.fn.init.r.fn.init (jquery.min.js:2:25448)
    at new a.fn.init (jquery-migrate.min.js:2:1276)
    at r (jquery.min.js:2:601)
    at jstree.min.js:2:247
    at jstree.min.js:2:165

Having trouble scraping a particular element on a website using Puppeteer

I am trying to scrape the key features part of the website with the URL of: “https://www.alpinestars.com/products/stella-missile-v2-1-piece-suit-1” using puppeteer – however, whenever I try to use a selector that works on the chrome console for the website the output for my code is always an empty array or object. For example both (document.querySelector(“#key features > p”) and (document.getElementById(‘key features’) both return as empty arrays or objects when I output it through my code but work via chrome console.

I have attached my code below:

const puppeteer = require('puppeteer');

async function getDescripData(url) {
    const browser = await puppeteer.launch({headless: true});
    const page = await browser.newPage();
    await page.goto(url);
    const descripFeatures = await page.evaluate(() => {
        const tds = Array.from(document.getElementById('key features'))
        console.log(tds)
        return tds.map(td => td.innerText)
    });
   console.log(descripFeatures)
    await browser.close();
    return {
        features: descripFeatures
    }
}

How should I go about overcoming this issue?

Thanks in advance!

Unsure of correct type and using ‘any’ causes compile error due to type-safety

I have this in my Landing.tsx:

<Pless handleClose={this.hidePless} showPless={this.state.showPlessPrompt} />

hidePless = () => {
this.setState({ showPlessPrompt: false });
};

In my Pless.tsx I have:

interface Props {
    handleClose: any;
    showPless: boolean;
}

export class Pless extends React.Component<Props> {
    constructor(props: Props) {
        super(props);
    }
    ...
}

When I run my application I get this:

Failed to compile.
C:/Users/…/Paperless.tsx
(6,18): Type declaration of ‘any’ loses type-safety. Consider replacing it with a more precise type.

Most likely a silly question but what should the type be?

Is there a way to scope styles without changing class attribute for a React component?

I have a react component that returns another React component similar to shown below:

// Sample Code

import React from 'react';
import Component from "./Component";
import "./styles1.css";
import "./styles2.css";
import "./styles3.css";
export default function Sample(props) {
  return <Component />;
}

Two out of the three CSS files come from a NPM package. This component is rendered in other non-react pages. So I call ReactDOM.render on this component wherever I am rendering.

The issues with this approach are:

  1. Styles in other pages where this component is rendered will cascade into the React component causing the React component to appear not as intended.
  2. When this component is used to do whatever its intended to do, I call ReactDOM.unmountComponentAtNode(document.getElementById(idSelector)). When this happens the styles are still in the <head> causing other elements in the consuming pages to be distorted.

I have tried the following approaches:

  1. Using this package react-scoped-css (https://github.com/gaoxiaoliangz/react-scoped-css) along with Webpack that adds a randomly hash to the <Component/> causing the CSS to be locally scoped. This won’t solve the cascading styles issue from consuming pages.
  2. Find the style tags by XPath (document.evaluate), and do delete the element from the document. But this will remove styles completely so when I want to render the component again the styles are gone.

It is important to mention that the 2 stylesheets coming from the NPM package are extremely large and minfied so it is not viable change the class names in the Component to use something like CSS Modules, CSS-in-JS or similar approaches. Are there any other approaches that will let me approach this problem without changing the class names? This has been really hard because most of the questions suggest to use CSS modules, CSS-in-JS, etc. for this which will require major re-work of the code.

The Component mentioned here is a extremely large codebase that has a lot of class names (roughly ~10K LOC).

How to attach data type to Cypress.as alias function

I have an object out of which I create an alias named userId

cy.wrap(response.id).as('userId');

When referencing userId its type is JQuery<HTMLElement>

cy.get('@userId').then(userId => // userId type is JQuery<HTMLElement> });

How does one define the alias type when defining the alias?

Intention is to have it as a number directly instead of default JQuery<HTMLElement>