When scraping the whole html, the desired tag wont come, seem likes the webpage is using some kind of JS script to dynamically load the html. So how to handle it?
Category: javascript
Category Added in a WPeMatico Campaign
react-map-gl + openstreetmap lookup
I am trying to get a simple polygon map to show using the lookup from nominatim.openstreetmap.org
however the react-map-gl plugin keeps saying Input data given to 'my-data' is not a valid GeoJSON object.
my map data is
function mapdata(){
// alert(e)
axios.get('https://nominatim.openstreetmap.org/lookup?osm_ids=R11689210,R11689151&polygon_geojson=1&bounded=0&format=geojson')
.then(response => {
console.log(JSON.stringify(response.data));
return(response.data)
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});
}
full code
import * as React from 'react';
import { Layer, Source } from 'react-map-gl';
import Map from 'react-map-gl';
import 'mapbox-gl/dist/mapbox-gl.css';
const axios = require('axios').default;
const layerStyle = {
'id': 'park-boundary',
'type': 'fill',
'source': 'national-park',
'paint': {
'fill-color': '#0000FF',
'fill-opacity': 0.5
},
'filter': ['==', '$type', 'Polygon']
};
function mapdata(){
// alert(e)
axios.get('https://nominatim.openstreetmap.org/lookup?osm_ids=R11689210,R11689151&polygon_geojson=1&bounded=0&format=geojson')
.then(response => {
console.log(JSON.stringify(response.data));
return(response.data)
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});
}
export default function Mapy({ items }) {
return <Map
initialViewState={{
longitude: -100,
latitude: 40,
zoom: 3.5
}}
style={{width: '100vw', height: '100vh'}}
mapStyle="mapbox://styles/mapbox/dark-v9"
mapboxAccessToken="APIKEY"
>
<Source id="my-data" type="geojson" data={mapdata()}>
<Layer {...layerStyle} />
</Source>
</Map>;
}
How do I not allow submission for empty fields from a child component? More explanation below
I have this sample codesandbox I made, though, in my original one there were already a lot of values. I only recreated the problem that I had.
Codesandbox: https://codesandbox.io/s/youthful-firefly-40mig3?file=/src/App.js
I have this in my App.js where I define some of my needed values and then pass it to 2 other components.
<div className="App">
{/* some codes here */}
<h1>App page</h1>
Initial Amount: 1000
<br />
Total Amount: {totalAmount}
<br />
----------------------------------------------------------
<h6>Passing the total amount and the second input here</h6>
<Second input2={input2} setInput2={setInput2} />
----------------------------------------------------------
<h6>Third here</h6>
<Third totalAmount={totalAmount} />
</div>
I have this Second.js where I compute the totalAmount. This is the problem that I encountered. The required is not being recognized here. I just wanted to stop the user from submitting the form if this field is empty. Are there other ways where it would not submit if a certain field is empty or just leave the input field to 1 if it is empty?
const Second = ({ input2, setInput2 }) => {
return (
<div>
Second here
<form>
<input
fullWidth
value={input2}
onChange={(e) => setInput2(e.target.value)}
required
/>
</form>
</div>
);
};
export default Second;
This is the Third.js where I passed down the totalAmount and added more values such as the name and age. In here the name and age are being recognized. This is also where I submit everything here.
const Third = ({ totalAmount }) => {
const [name, setName] = useState("");
const [age, setAge] = useState(0);
const handleSubmit = (e) => {
e.preventDefault();
try {
console.log(name, age, totalAmount);
} catch (err) {
console.log(err);
}
};
return (
<div>
Third here
<form onSubmit={handleSubmit}>
<label>Name</label>
<input
fullWidth
value={name}
onChange={(e) => setName(e.target.value)}
required
/>
<br /> <br />
<label>Age</label>
<input
fullWidth
value={age}
onChange={(e) => setAge(e.target.value)}
required
/>
<br /> <br />
<button type="submit">submit</button>
</form>
</div>
);
};
export default Third;
addEventListener(“click”, function) doesn’t work [duplicate]
I’m doing QR-code generator using HTML, CSS and javascript. When click on button, I want to add “active” to wrapper classList. When wrapper is active, then it has to show more space for QR code using css .wrapper .active {height : 500px};
But when I click on button, it changes to “wrapper active” just a blink then changes back to original “wrapper”. How can I make this work.
Here’s that QR-code generator tutorial file which I watch. It’s on 7:34. “https://www.youtube.com/watch?v=pv5K28zVepE”
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>QR Code Generator</title>
<link rel= "stylesheet" href= "style.css">
</head>
<body>
<div class= "wrapper">
<header>
<h1>QR Code Generator</h1>
<p>Paste a url or enter text to create QR code</p>
</header>
<form>
<input type= "text" placeholder= "Enter text or URL">
<button>Generate QR code</button>
</form>
<div class= "qr-code">
<img src= "qr-code.jpg" width= "170px" height= "170px" alt= "qr-code">
</div>
</div>
<script src= "script.js"></script>
</body>
</html>
const wrapper = document.querySelector(".wrapper"),
generateBtn = wrapper.querySelector("form button");
generateBtn.addEventListener("click", () => {
wrapper.classList.add('active');
});
Group drag and drop in react
I am making drag and drop functionality using react-beautiful-dnd.
Scenario:
When I drag and drop individual card from one group to another then it is working fine.
Issue:
When I try to drag and drop one group to another, I am getting error as
Cannot read properties of undefined (reading ‘taskIds’)
Expectation:
Drag and drop about to work for both individual cards from one group to another and also one group to another
Reorder of groups via drag and drop is not working and throwing the above mentioned error.
Working Sandbox:
Plaid: Plaid.create is stuck onLoading
I am integrating with Plaid using vanilla javascript. I am able to get the link_token in order to create the Plaid platform using Plaid.create({…}). However, I am running into this weird bug where Plaid.create({…}) is stuck on loading state without ever resolving into onSuccess. When handler.open() is initiated, the plaid interface comes out but both usernames and password are saying invalid credentials (i am guessing this is due to the missing onSuccess call). Here is the code snippet (there are no console errors, just the console message from onLoad): Can anybody help me figure this out? Thank you!
function syncUpWithPlaid(token) {
const handler = Plaid.create({
token,
onSuccess: (public_token, metadata) => {
console.log('success!', public_token)
fetch('http://localhost:8000/api/tracking/access-token', {
method: 'POST',
body: {
public_token: public_token,
accounts: metadata.accounts,
institution: metadata.institution,
link_session_id: metadata.link_session_id,
},
});
},
onLoad: () => {
console.log('loading') // for some reason it is stuck here
},
onExit: (err, metadata) => {
console.log('err', err);
},
onEvent: (eventName, metadata) => {
console.log('eventName', eventName)
console.log('metadata', metadata)
},
});
handler.open();
}
EthSwap AssertionError: expected ‘1000000000000000000000000’ to equal ‘999900000000000000000000’
I am trying to follow a tutorial where I’m creating a EthSwap app from scratch. I am writing a unit test where I’m trying to test the buyTokens() function.
I’m trying to check if the EthSwap balance has decreased after buying tokens.
This is the test function:
describe('buyTokens()', async () => {
let result
before(async () => {
//purchase tokens before each example
result = await ethSwap.buyTokens({from : investor, value: web3.utils.toWei('1','ether')})
})
it("Allows users to instantly purchase tokens from EthSwap for a fixed price", async () =>{
//check investor token balance after purchase
let investorBalance = await token.balanceOf(investor);
assert.equal(investorBalance.toString(), tokens('100'))
//check EthSwap balance after purchase
let ethSwapBalance
ethSwapBalance = await token.balanceOf(ethSwap.address)
assert.equal(ethSwapBalance.toString(), tokens('999900'))
})
})
After running truffle test it shows this: AssertionError: expected ‘1000000000000000000000000’ to equal ‘999900000000000000000000’
However the change in balance is reflected in the test results investorBalance, i.e., when I was running the following snippet, the test case was passing.
describe('buyTokens()', async () => {
let result
before(async () => {
//purchase tokens before each example
result = await ethSwap.buyTokens({from : investor, value: web3.utils.toWei('1','ether')})
})
it("Allows users to instantly purchase tokens from EthSwap for a fixed price", async () =>{
//check investor token balance after purchase
let investorBalance = await token.balanceOf(investor);
assert.equal(investorBalance.toString(), tokens('100'))
//check EthSwap balance after purchase
//let ethSwapBalance
//ethSwapBalance = await token.balanceOf(ethSwap.address)
//assert.equal(ethSwapBalance.toString(), tokens('999900'))
})
})
This is my EthSwap.sol
pragma solidity ^0.5.0;
import "./Token.sol";
contract EthSwap{
string public name = "EthSwap Instant Exchange";
Token public token;
uint public rate = 100;
constructor(Token _token) public{
token = _token;
}
function buyTokens()public payable{
//calculation of number of tokens
uint tokenAmount = msg.value * rate;
token.transfer(msg.sender, tokenAmount);
}
}
Token.sol:
pragma solidity ^0.5.0;
contract Token{
string public name = "Ray Token";
string public symbol = "RAY";
uint256 public totalSupply = 1000000000000000000000000;
uint8 public decimals = 18;
event Transfer(
address indexed _from,
address indexed _to,
uint256 _value
);
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _value
);
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
constructor() public{
balanceOf[msg.sender] = totalSupply;
}
function transfer(address _to, uint256 _value) public returns (bool success){
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] >= _value;
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender,_value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success){
require(_value <= balanceOf[_from]);
require(_value <= allowance[_from][msg.sender]);
balanceOf[_from] -= _value;
balanceOf[_to] -= _value;
allowance[_from][msg.sender] -= _value;
emit Transfer(_from, _to, _value);
return true;
}
}
How is the change reflected in the investorBalance but not in EthSwap balance?
The tutorial is using chai.
This is the entire EthSwap.test.js
const Token = artifacts.require('Token')
const EthSwap = artifacts.require('EthSwap')
require('chai')
.use(require('chai-as-promised'))
.should()
function tokens(n){
return web3.utils.toWei(n,'ether')
}
contract('EthSwap',([deployer,investor]) => {
let token,ethSwap
before(async() => {
token = await Token.new()
ethSwap = await EthSwap.new(token.address)
await token.transfer(ethSwap.address,tokens('1000000'))
})
describe('Token deployment',async() =>{
it('contract has a name', async() =>{
const name = await token.name()
assert.equal(name,'Ray Token')
})
})
describe('EthSwap deployment',async() =>{
it('contract has a name', async() =>{
const name = await ethSwap.name()
assert.equal(name,'EthSwap Instant Exchange')
})
it('contract has tokens', async() => {
let balance = await token.balanceOf(ethSwap.address)
assert.equal(balance.toString(), tokens('1000000'))
})
})
describe('buyTokens()', async () => {
let result
before(async () => {
//purchase tokens before each example
result = await ethSwap.buyTokens({from : investor, value: web3.utils.toWei('1','ether')})
})
it("Allows users to instantly purchase tokens from EthSwap for a fixed price", async () =>{
//check investor token balance after purchase
let investorBalance = await token.balanceOf(investor);
assert.equal(investorBalance.toString(), tokens('100'))
//check EthSwap balance after purchase
let ethSwapBalance
ethSwapBalance = await token.balanceOf(ethSwap.address)
assert.equal(ethSwapBalance.toString(), tokens('999900'))
})
})
})
Understand React-Redux Toolkit Syntax?
I’m new to react, redux and tyring to understand the redux-toolkit tutorial i follow. I have the slice as follows.
const initialState = {
count: 0,
};
export const counterSlice = createSlice({
name: "counter",
initialState,
reducers: {
increment: (state) => {
state.count += 1;
},
},
});
export const { increment } = counterSlice.actions;
export default counterSlice.reducer;
export const incrementTest = () => (dispatch) => {
dispatch(increment());
};
Then I use that incrementTest action as follows
<button onClick={() => dispatch(incrementTest())}> + </button>
I want to understand following.
In following fuction
export const incrementTest = () => (dispatch) => {
dispatch(increment());
};
we return a function which takes argument as dispatch then call that provided dispatch function with argement of another function increment which is defined above and exported.
However when we call this function we use dispatch(incrementTest()) providing incrementTest as a param to dispatch. I don’t understand this concept . Which concept in javascript should i further study to learn this ?
Also increment reducer take state as parameter ( and action also in some cases ). Who provide this (state,action) to this function as we call it as dispatch(incrementTest())
How to added hover to a div style
How can I use a:hover in inline CSS inside the HTML style attribute
like this but doesn’t work
<div
style={{
"&:hover": {
background: "#efefef"
},
}}
>
Why do ReactDOMServer and ReactDOM give the “root.hydrate is not a function” error
When creating an app using create-react-app I get the following error when trying to use hydrate instead of the default .render. Here is the src/index.js file’s contents.
import React from 'react';
import ReactDOMServer from 'react-dom/client';
import './index.css';
import App from './App';
const root = ReactDOMServer.createRoot(document.getElementById('root'));
root.hydrate(
<React.StrictMode>
<App />
</React.StrictMode>
);
Running the above code npm start produces the following error
Uncaught TypeError: root.hydrate is not a function
The error is not present if I change the .hydrate back to .render and I am not sure why this is happening.
Access document with dynamic keys returned by findOne mongoose API
I am trying to access the nested object dynamically, in the document returned by findOne. But I am receiving this error:
console.log(doc.$[category])
^
TypeError: Cannot read properties of undefined (reading 'chats')
at file:///C:/Users/lenovo/Desktop/commdash/backend/server.js:93:26
at processTicksAndRejections (node:internal/process/task_queues:96:5)
My code for findOne is:
mongoData.findOne( {_id: id, [category] :{$elemMatch:{name: name}}}).then(function (doc) {
console.log(doc.$[category])
});
My Schema is:
{
user : {
firstName: String,
lastName: String,
email: String,
userImage: {type: String, default: "https://www.business2community.com/wp-content/uploads/2017/08/blank-profile-picture-973460_640.png"}
},
avatar: {type: String, default: "https://www.business2community.com/wp-content/uploads/2017/08/blank-profile-picture-973460_640.png"},
chats: [{
name: String,
conversation: [
{
message: String,
timestamp: String,
user: String,
userImage: {type: String, default: avatar}
}
]
}],
groups:[ {
name: String,
conversation: [
{
message: String,
timestamp: String,
user: String,
userImage: {type: String, default: avatar}
}
]
}],
people: [{
id: String,
name: String,
relation : [{name: String}],
conversation: [
{
message: String,
timestamp: String,
user: String,
userImage: {type: String, default: avatar}
}
]
}
]
}
}
The dynamic variable category is either: people, groups, or chats.
When its only console.log(doc), it returns:
{
user: {
userImage: 'https://www.business2community.com/wp-content/uploads/2017/08/blank-profile-picture-973460_640.png',
firstName: 'xyz',
lastName: 'xyz',
email: '[email protected]'
},
_id: new ObjectId(""),
avatar: 'https://www.business2community.com/wp-content/uploads/2017/08/blank-profile-picture-973460_640.png',
chats: [
{
_id: new ObjectId(""),
name: 'Hello',
conversation: [Array]
},
{
_id: new ObjectId(""),
name: 'There',
conversation: [Array]
},
{
_id: new ObjectId(""),
name: 'up',
conversation: [Array]
}
],
groups: [],
people: [],
__v: 0
}
and when I try console.log(doc.chats), it returns:
[
{
_id: new ObjectId(""),
name: 'Hello',
conversation: [ [Object] ]
},
{
_id: new ObjectId(""),
name: 'There',
conversation: [ [Object] ]
},
{
_id: new ObjectId(""),
name: 'up',
conversation: [ [Object] ]
}
]
This is again wrong because what is wanted is a particular chats object with chats.name = name?
I don’t know what I am doing wrong.Please help.
Correct the mouse position when scaling p5.js
I’m making a 2D camera for my little game that runs in p5.js.
I’ve created the world and the camera, the camera moves by pressing the mouse button and dragging, and zooms by scrolling the mouse wheel.
In the class World there is a getter for the mouse position relative to the world, it works very well when the canvas scale is 1, but when zooming and the scale increases the position is not right. How do I fix the mouse position to be right even after changing the scale?
Link to the sketch: p5 editor
class Camera{
constructor({ x, y, width, height }){
// Positioned from top left just like a rectangle in p5
this.position = createVector(x, y);
// Receive the world 'width' and 'height'
this.width = width;
this.height = height;
// The 'zoom' scale
this.scale = 1;
this.maxZoom = 1;
this.minZoom = 3;
this.mouseIsDown = false;
}
get screenPostion(){
// get the position relative to the window 'width' and 'height'
return createVector(this.position.x + width/2, this.position.y + height/2);
}
zoom(num){
// Set the scale between the min and max zoom
this.scale = this.scale + (0.1 * num) > this.minZoom ? this.minZoom : this.scale + (0.1 * num) < this.maxZoom ? this.maxZoom : this.scale + (0.1 * num);
}
mouseDown(event){
// if(event.button == 2)
this.mouseIsDown = true;
}
mouseUp(event){
// if(event.button == 2)
this.mouseIsDown = false;
}
move(){
// Check if the mouse is down then moves the camera position based on current mouse position subtracted by the previous mouse position
if(this.mouseIsDown){
const x = mouseX - pmouseX;
const y = mouseY - pmouseY;
this.position.add(x, y);
}
}
mouseWheel(event){
if(!isNaN(event.delta) && event.delta > 0) this.zoom(-1);
else this.zoom(1);
}
update(){
this.move();
// Translates to the middle of the screen based on the camera position
translate(this.position.x + width/2, this.position.y + height/2);
// Sets the scale
scale(this.scale);
// Translates back to the orinal position
translate((this.position.x + width/2)*-1, (this.position.y + height/2)*-1);
// Translates to the camera relative screen position
translate(this.screenPostion.x - this.width/2, this.screenPostion.y - this.height/2);
}
}
class World{
constructor({ cellSize, collumns, rows }){
this.width = cellSize * collumns;
this.height = cellSize * rows;
this.createCamera();
}
createCamera(){
this.camera = new Camera({ x:0, y:0, width:this.width, height:this.height });
return this.camera;
}
update(){
this.camera.update();
this.showBorder();
}
get mouse(){
// Get the mouse position relative to the world based on the camera relative position to the screen
return createVector(Math.floor(mouseX - this.camera.screenPostion.x + this.width/2), Math.floor(mouseY - this.camera.screenPostion.y + this.height/2));
}
showBorder(){
noFill();
stroke(255);
rect(0, 0, this.width, this.height);
}
}
let world;
function setup(){
createCanvas(windowWidth, windowHeight);
// Prevent the context menu to open on right click
for (let element of document.getElementsByClassName("p5Canvas")) {
element.addEventListener("contextmenu", (e) => e.preventDefault());
}
world = new World({ cellSize:10, collumns:10, rows:10 });
}
function draw(){
background(56);
world.update();
updatePositionText();
}
function mousePressed(event){
world.camera.mouseDown(event);
}
function mouseReleased(event){
world.camera.mouseUp(event);
}
function mouseWheel(event) {
world.camera.mouseWheel(event);
}
function updatePositionText(){
document.getElementById("position-text").textContent = `Mouse position: X: ${world.mouse.x}, Y: ${world.mouse.y}`;
}
html, body {
margin: 0;
padding: 0;
}
canvas {
display: block;
}
#position-text{
font-family: sans-serif;
position: absolute;
bottom: 25px;
left: 25px;
font-size: 25px;
color: #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>
<div id="position-text"></div>
differnce between npm correlation-id and uuid?
May I know whats the difference between uuid and correlation-id npm packages? correlation-id internally using uuid package only..
In what scenario correlation-id is much better to use than uuid?
Javascript to access the X/Y value of svg transform translate
Is there any built-in javascript method currently exists that can access directly X or Y of svg transform =translate(x,y)?
For example a minimum sample below, I am working with a svg element
document.querySelectorAll('circle').forEach(
(a,i)=>{
const transformString= a.getAttribute('transform');
const valX = parseFloat(transformString.match(/(d+.d+)(?=,)|(d+)(?=,)/gm))+10;
a.setAttribute('transform',`${transformString.replace(/(d+.d+)(?=,)|(d+)(?=,)/gm,valX)}`)});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<script type="text/javascript" src="https://d3js.org/d3.v7.min.js"></script>
<body>
<svg xmlns="http://www.w3.org/2000/svg" height="400" width="450">
<circle cx="0" cy="5" r="5" transform="translate(10,20)"></circle>
<circle cx="0" cy="5" r="5" transform="translate(25,30)"></circle>
<circle cx="0" cy="5" r="5" transform="translate(17.5,32.5)"></circle>
<circle cx="0" cy="5" r="5" transform="translate(10, 50)"></circle>
</svg>
</body>
</html>
and this element contains few existing circles.

I want to grab each circle’s transform=translate(x,y) x value and change it with a custom function.
I am currently doing it as follows and I want to avoid writing a regex if there is a built-in (vanilla and /d3) method exists to directly access the x or y of transform=translate
document.querySelectorAll('circle').forEach(
(a,i)=>{
const transformString= a.getAttribute('transform');
//grab the X value with regex and change as desired
const valX = parseFloat(transformString.match(/(d+.d+)(?=,)|(d+)(?=,)/gm))+10;
//replace existing X with new X
a.setAttribute('transform',`${transformString.replace(/(d+.d+)(?=,)|(d+)(?=,)/gm,valX)}`)});
d3 equivalent
d3.selectAll('circle')
.attr('transform', function (d,i) {
const transformString= this.getAttribute('transform');
const valX = parseFloat(transformString.match(/(d+.d+)(?=,)|(d+)(?=,)/gm))+10;
return `${transformString.replace(/(d+.d+)(?=,)|(d+)(?=,)/gm,valX)}`
});
Is there a way to access an array inside of a variable, inside of a list of variables? [duplicate]
Sorry if this is not allowed to be asked. I am learning and trying to comprehend a lesson further than taught.
I can access porche, easily. If it was just assigned let’s say “red”. But I’m having an issue trying to pull the info from an array of colors for porche. This code only displays all colors. I want to just pull one color from the list.
let myCars = {
porche: ["red", "blue", "green"],
mazda: "white",
vw: "pink",
}
function getColor(colorProp) {
if (myCars.hasOwnProperty(colorProp)) {
return myCars[colorProp];
} else {
return ("No Vroom Vroom");
}
}
console.log(getColor("porche"));
I tried adding another param to my function but ultimately did not succeede. Just wondering if it’s something simple I’m not comprehending, again, I do apologize if this is an out-of-line question.