I have an empty array. I called an api and pushed the data from the api into my empty array and want to remove duplicates. the new Set syntax doesn’t work because the array I’m trying to filter with doesn’t physically hold anything. All the data got pushed into it. Not sure how to go about this.
Category: javascript
Category Added in a WPeMatico Campaign
puppeteer.launch not loading
I am trying to open a page using puppeteer headless. However, puppeteer.launch is taking extremely long and the process isn’t able to finish. Code:
const puppeteer = require("puppeteer");
async function getVisual() {
try {
const URL =
"https://www.bannerbear.com/blog/ways-to-speed-up-puppeteer-screenshots/";
const browser = await puppeteer.launch((headless = true), {
ignoreDefaultArgs: ["--disable-extensions"],
timeout: 3000,
});
const page = await browser.newPage();
console.log("hi");
await page.goto(url);
await page.screenshot({ path: "screenshot.png" });
await page.pdf({ path: "page.pdf" });
await browser.close();
} catch (error) {
console.error(error);
}
}
getVisual();
Webpack entry point keeps giving me: Error: EACCES: permission denied, open ‘/home/user/webpack-demo/webpack.config.js’
I am new to webpack and trying to learn how to use it to implement javascript code. I am trying to implement the tutorial on the webpack getting started page here:https://webpack.js.org/guides/getting-started/#using-a-configuration
but I keep getting the above error every time I try to implement the program. I am running Ubuntu ver. 2004.4.4.0 for Windows 10. This is the message in full:
[webpack-cli] Failed to load '/home/redaja/webpack-demo/webpack.config.js' config
[webpack-cli] Error: EACCES: permission denied, open '/home/redaja/webpack-demo/webpack.config.js'
at Object.openSync (node:fs:585:3)
at Object.readFileSync (node:fs:453:35)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1122:18)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Module.require (node:internal/modules/cjs/loader:1005:19)
at require (node:internal/modules/cjs/helpers:102:18)
at WebpackCLI.tryRequireThenImport (/home/redaja/webpack-demo/node_modules/webpack-cli/lib/webpack-cli.js:244:16)
at loadConfigByPath (/home/redaja/webpack-demo/node_modules/webpack-cli/lib/webpack-cli.js:1712:30)
at /home/redaja/webpack-demo/node_modules/webpack-cli/lib/webpack-cli.js:1767:11 {
errno: -13,
syscall: 'open',
code: 'EACCES',
path: '/home/redaja/webpack-demo/webpack.config.js'
} ```
consoling out django context in console
why am I getting output in console as {{request.num}} without the actual number?
This is my code:
def test(request):
number = 4
context = {"num": number}
javascript
var number = "{{request.num}}";
console.log(number)
Select A Button By Class jQuery
I am trying to have a button that, when clicked, will have some jQuery code linked to it. See the general layout below. However, there will be a variable number of rows on the table. All the buttons should have the same action but applied to its parent element. How can I achieve this?
Thanks
td {
border: 1px solid black;
padding: 10px;
}
<table>
<tr>
<td>Info</td>
<td><button class="remove">Remove row</button></td>
</tr>
<tr>
<td>Info</td>
<td><button class="remove">Remove row</button></td>
</tr>
<tr>
<td>Info</td>
<td><button class="remove">Remove row</button></td>
</tr>
</table>
async Function returns Promise { }, [duplicate]
so im trying to get some data to the client side, but it is arriving empty, since everytime i try to get the data returned from the fetch its giving Promise { }.
Also, this async map function is inside of another async function called default, if that helps.
async function default(){
const result = last10Matches.map(async (match) => {
const matchurl = `https://api.pubg.com/shards/${playerPlatform}/matches/${match.id}`;
const matchresponse = await fetch(matchurl, options);
const matchdata = await matchresponse.json();
matchdata.included.forEach((player) => {
if (
player.type == 'participant' &&
player.attributes.stats.name == playerName
) {
playerRecentStats.push({
kills: player.attributes.stats.kills,
dmgDone: player.attributes.stats.damageDealt,
knocks: player.attributes.stats.DBNOs,
date: matchdata.data.attributes.createdAt,
});
}
});
// console.log(playerRecentStats); // This does log the correct data here.
return playerRecentStats;
});
console.log(result); // This here returns Promise { <pending> }
/*
// i Also tried this below. with an empty result whatsoever.
async () => {
console.log(await result);
};
*/
}
Thanks in advance
PIXI Logic is Skewed from the Actual Visuals
I am pretty new to JavaScript and PIXI. I am making a little game that requires the player to navigate and grab a key (move onto the same space as the key). This takes them to the next level. My problem is that whenever a new level is generated, it somehow uses the x and y coordinates for the key of the previous level to skew the logic. Because of this, the first level works fine, but every level afterwards is messed up.
The levels get skewed up and to the left by the respective values of the previous key. I have a 2d array in the background which holds values of where and where not the player can (holds values for things like walls, turrets, and the key). I randomly generate the key coordinates and for example set grid[9][12] = 3; for the key space. The next level visually looks perfect, with the walls and key generating, and the player being in the top left. However because of the skew, the top left of the visuals is really at [max_X – 9][max_Y – 12] and the player can go off screen to invisibly access the rest of the maze. So I can then phase through walls because the logic has the walls in a different place than the visuals, and the actual key space usually ends up off screen.
Here is my code that generates a new goal (key) object
function createGoal(scene) {
while (true) {
let x = getRandomInt(APP_WIDTH);
let y = getRandomInt(APP_HEIGHT);
//if space is not already occupied, populate
if (grid[x][y] == 0) {
console.log(x);
console.log(y);
goal = null;
goal = new Goal(TILE_WIDTH, x, y);
scene.addChild(goal);
grid[x][y] = 3;
break;
}
}
}
And here is the grid initialization:
const grid = new Array(APP_WIDTH);
for (let i = 0; i < APP_WIDTH; i++) {
grid[i] = new Array(APP_HEIGHT);
for (let j = 0; j < APP_HEIGHT; j++) {
grid[i][j] = 0;
}
}
Any help would be greatly appreciated.
Transform array of Strings into Object
Given the following values:
const values = ['name1|engine1|color1', 'name2|engine2|color2', 'name3|engine3|color3']
I would like to create an array for the values โโof the same position, like this:
cars = {
names: ['name1', 'name2', 'name3'],
engines: ['engine1', 'engine2', 'engine3'],
colors: ['color1', 'color2', 'color3'],
...other properties
}
I tried to do it this way:
values.reduce((acc, value) => {
const [name, engine, color] = value.split('|')
acc.names.push(name)
acc.engines.push(engine)
acc.colors.push(color)
return acc
}, {})
The problem is that acc.name, acc.engine and acc.color don’t exist yet, and it gives an error on push. What would be a way to do this cleanly, taking into account that they will have other properties?
Dat.GUI check box not unchecking on chrome [Version 101.0.4951.41 (Official Build) (64-bit)]
I am currently working on a dat.gui menu for my THREE.JS project.
Here is my project: https://codesandbox.io/s/ray-test-km2wru?file=/src/World.js:5581-5741
You will see that clicking the checkbox should change the equation for the plane as seen on lines 144. I am noticing that checkbox, when clicked, doesn’t uncheck on chrome. However, when tested in firefox, the checkbox will unclick and switch the value of planeSpecs.waveXY to false.
_createPlane() {
// Dat.GUI controllers
let planeSpecs = {
scaler: 1,
speed: 1,
waveXY: true
};
let planeMat = new THREE.MeshStandardMaterial({
color: 0x6d6e6d,
side: THREE.DoubleSide,
wireframe: true
});
// Creates a single plane with wireframe
let planeGeo = new THREE.PlaneGeometry(25, 25, 200, 200);
var plane = new THREE.Mesh(planeGeo, planeMat);
const planeFolder = this._GUI.addFolder("Plane");
// These scales work
planeFolder.add(planeSpecs, "scaler", 1, 10);
planeFolder.add(planeSpecs, "speed", 0.1, 25);
// This checkbox code doesn't work:
const waveXYController = this._GUI
.add(planeSpecs, "waveXY")
.listen()
.onChange((newValue) => {
console.log(newValue);
});
planeFolder.open();
plane.position.y -= 3;
plane.rotation.set(Math.PI / 2, 0, 0);
// Animation for the plane
plane.tick = (delta, elapsedTime) => {
const { position } = planeGeo.attributes;
for (let i = 0; i < position.count; i++) {
let x = position.getX(i);
let y = position.getY(i);
let z = position.getZ(i);
// Change the equation based on checkbox boolean
z = planeSpecs.waveXY
? Math.sin(
Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)) +
elapsedTime * planeSpecs.speed
) * planeSpecs.scaler
: Math.sin(x + elapsedTime * planeSpecs.speed) * planeSpecs.scaler;
position.setXYZ(i, x, y, z);
}
position.needsUpdate = true;
};
return plane;
}
From what I have researched, they way I added the dat.gui seems to be correct: https://www.nowherenearithaca.com/2015/07/datgui-easy-way-to-allow-users-to.html
I did make a forum post on the Three.JS forums, but after figuring out this is a browser issue I made a post here instead: https://discourse.threejs.org/t/dat-gui-checkbox-not-working-on-chrome/37642/2
Uable to install Phyton3
I am trying to install phyton3 with the tips from this link: https://github.com/sherlock-project/sherlock#installation
olebravn@cloudshell:~$ python3 -m pip install -r requirements.txt
ERROR: Could not open requirements file: [Errno 2] No such file or directory: ‘requirements.txt’
olebravn@cloudshell:~$
I tried installing phyton3 on the website: https://shell.cloud.google.com/?pli=1&show=ide%252terminal
It did not work does anyone know what the problem may be?
Thx ๐
I’ve create this simple JS dice game where I run 2 dices
I want to hear suggestions on how to improve this code, there’s probably a way that I can call the same function to get 2 different results? When I tried that, I got 2 dices printing the same result. Any other suggestion on how to make this look better would be nice.
I already figured out how to do it by using only the dice1 and dice2 since a function is not required for that and printing it to the console, now I want to use 2 functions because I want to do this silly ASCII art thing.
Is there a way that instead of calling
diceSpin();
diceSpin2();
I just call a diceSpin(dice1, dice2) and get the same output?
const diceResult = Math.floor(Math.random() * 6) + 1;
const diceResult2 = Math.floor(Math.random() * 6) + 1;
console.log("Dice 1: " + diceResult + " Dice 2: " + diceResult2)
function diceSpin() {
if (diceResult === 1) {
console.log(" .......")
console.log("| |")
console.log("| o |")
console.log("| |")
console.log(" ''''''' ")
} else if (diceResult === 2) {
console.log(" .......")
console.log("| |")
console.log("| o o |")
console.log("| |")
console.log(" ''''''' ")
} else if (diceResult === 3) {
console.log(" .......")
console.log("| |")
console.log("| o o o |")
console.log("| |")
console.log(" ''''''' ")
} else if (diceResult === 4) {
console.log(" .......")
console.log("| o o |")
console.log("| |")
console.log("| o o |")
console.log(" ''''''' ")
} else if (diceResult === 5) {
console.log(" .......")
console.log("| o o |")
console.log("| o |")
console.log("| o o |")
console.log(" ''''''' ")
} else {
console.log(" .......")
console.log("| o o o |")
console.log("| o o o |")
console.log("| o o o |")
console.log(" ''''''' ")
}
}
function diceSpin2() {
if (diceResult2 === 1) {
console.log(" .......")
console.log("| |")
console.log("| o |")
console.log("| |")
console.log(" ''''''' ")
} else if (diceResult2 === 2) {
console.log(" .......")
console.log("| |")
console.log("| o o |")
console.log("| |")
console.log(" ''''''' ")
} else if (diceResult2 === 3) {
console.log(" .......")
console.log("| |")
console.log("| o o o |")
console.log("| |")
console.log(" ''''''' ")
} else if (diceResult2 === 4) {
console.log(" .......")
console.log("| o o |")
console.log("| |")
console.log("| o o |")
console.log(" ''''''' ")
} else if (diceResult2 === 5) {
console.log(" .......")
console.log("| o o |")
console.log("| o |")
console.log("| o o |")
console.log(" ''''''' ")
} else {
console.log(" .......")
console.log("| o o o |")
console.log("| o o o |")
console.log("| o o o |")
console.log(" ''''''' ")
}
}
diceSpin();
diceSpin2();
if (diceResult > diceResult2) {
console.log("Dice 1 wins!")
} else if (diceResult < diceResult2) {
console.log("Dice 2 wins!")
} else {
console.log("Draw!")
}
Error Message: Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component
I get a blankpage when I try to run my app and nothing is being rendered.
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:
- You might have mismatching versions of React and the renderer (such as React DOM)
- You might be breaking the Rules of Hooks
- You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
import React,{ useState} from 'react';
import styled from 'styled-components'
import MenuIcon from '@material-ui/icons/Menu';
import CloseIcon from '@material-ui/icons/Close';
function Header() {
const [burgerState,setBurgerState] = useState(false);
return (
<Container>
<a href='#'>
<img src='/images/logo.svg' alt=''/>
</a>
<MenuGroup>
<div>Model S</div>
<div>Model X</div>
<div>Model Y</div>
</MenuGroup>
<RightMenu>
<a href='#'>Shop</a>
<a href='#'>Tesla Account</a>
<MenuIconContainer onClick={ () => setBurgerState(true)} >
<MenuIcon/>
</MenuIconContainer>
</RightMenu>
<BurgerNav status={burgerState}>
<CloseContainer>
<Close onClick={ () => setBurgerState(false)} />
</CloseContainer>
<li><a href='#'>Model S</a></li>
<li><a href='#'>Model Y</a></li>
<li><a href='#'>Existing inventory</a></li>
<li><a href='#'>Used inventory</a></li>
<li><a href='#'>Trade-in</a></li>
<li><a href='#'>Cybertruck</a></li>
<li><a href='#'>Roadster</a></li>
<li><a href='#'>Semi</a></li>
<li><a href='#'>Charging</a></li>
</BurgerNav >
</Container>
)
}
export default Header;
const Container = styled.div`
display: flex;
min-height: 60px;
align-items: center;
justify-content: space-between;
padding: 0 20px;
position: fixed;
top: 0;
left: 0;
right: 0;
z-index: 10;
`;
const MenuGroup = styled.div`
display: flex;
text-transform: uppercase;
div {
font-weight: 600;
padding: 0 10px;
cursor: pointer;
}
@media(max-width: 760px) {
display: none;
}
`;
const RightMenu = styled.div`
display: flex;
a {
font-weight: 600;
text-transform: uppercase;
padding-right: 20px;
}
`;
const MenuIconContainer = styled.div`
display:flex;
align-iems:center;
cursor:pointer;
`;
const CloseContainer = styled.div`
display: flex;
justify-content: flex-end;
`
const Close = styled(CloseIcon)`
`;
const BurgerNav = styled.div`
position: fixed;
width: 300px;
background: white;
top: 0;
right: 0;
bottom: 0;
padding: 20px;
list-style: none;
transform: ${props => props.status ? 'translateX(0)' : 'translateX(100%)'};
transition: transform 0.2s ease-in;
li {
padding: 15px 0;
border-bottom: 1px solid rgba(0, 0, 0, .2);
a {
font-weight: 600;
}
}
`
JavaScript: How to do an event listener with current functions?
My understanding of an event handler is that it allows the event handler that takes an existing function and allows you to do something with it like a click or some kind of event
What I am trying to do is when the = button is pressed on my calculator it uses the calculation function and takes the if-else statements and applies it to the = sign. For example, if the user clicks 1 + 1 the = sign should add them together and give the answer.
/*********************
Setting up varlaibles*
**********************/
let result;
let num1;
let num2;
/*****************************************
Function for numbers to display on screen*
******************************************/
function buttonPress(numbers) {
let input = document.querySelector('.answer').innerText.split('n').join('')+numbers
let display = document.querySelector('.answer').innerHTML = input
console.log(`${typeof display} ${display}`)
if (display.length >= 21) {
for (let i = 0; i < display.length; i++) {
document.querySelector('.answer').style.marginTop = -i + "px";
}
}
}
/***********************************
Function for calculation of numbers*
************************************/
function calculation(buttonPress){
result = document.querySelector(".answer");
if(numbers == "/"){
numbers + numbers;
}
else if(numbers == "x"){
numbers - numbers
}
else if(numbers == "+"){
numbers - numbers
}
else if(numbers == "-"){
numbers - numbers
}
else if(numbers == "%"){
numbers - numbers
}
buttonPress()
}
The outcome should be with addEventListener that if the user uses operators to with the numbers the = sign should give the answer.
React Native: onViewableItemsChanged: check last item is visible on screen
in my react-native app I’m using onViewableItemsChanged prop on FlatList in order to see if the last item of FlatList is visible on screen,.
To do that I want to compare changed item indexes with the ammount of items in FlatList, however messages.length is always zero even though it’s not, I think I’m getting the length of messages array on mount which is zero.
How would you go about this problem?
const onViewRef = React.useRef((viewableItems)=> {
//This always returns 0 so how can I ccheck if last item is on screen
console.log('messagesTotal:',messages.length);
console.log('changedItems:',viewableItems.changed[0].index);
setValue(viewableItems.changed[0].index);
});
<FlatList ref={flatListRef} onViewableItemsChanged={onViewRef.current}>
Why secound if in checking for mines don t work
link for code :https://github.com/LazyAsek/Mineswapper
in function checking for mines secound if statement returns error and i don t know how to fix it