Category: javascript
Category Added in a WPeMatico Campaign
i need fix the setTimeout funcation discord.js
setTimeout when it is 24 hours (86400000) or more.. it doesn’t work ,why?
message.channel.send(`hello world`);
}, 86400000);
Note: The bot works 24/7
How can I change page text from the backend in Velo by Wix
How could I change text on the page from the backend using Velo by Wix? Is this possible? I want to do this since I want to display confidential information about the current user, and I don’t want to give the frontend access to a function that would return that info so I could do it from the frontend.
Thanks in advance!
json object as a variable (javascript) [duplicate]
how can I use the json object as a variable?
For example i want the age of sarah
function changeValue(jsonfile, object, value) {
const filepath = './' + jsonfile + '.json';
const data = JSON.parse(fs.readFileSync(filepath));
data.object = value;
fs.writeFileSync(filepath, JSON.stringify(object, null, 4));
console.log(data);
}
changeValue('file.json', data.users.sarah.age, '30');
//ReferenceError: data is not defined
file.json
{
"users": {
"adam": {
"age": "19",
"gender": "male"
},
"sarah": {
"age": "23",
"gender": "female"
},
}
}
Thanks in advance
JavaScript submit form
Hey Everyone and thank you for your time. I have a problem to submit a form in JS. Obviously my form has the value “null”, but i don’t can figure it out why. Can you help me, im new to JS.
HTML:
<form id="form">
<input type="text" id="username" placeholder="Username" required>
<input type="email" id="email" placeholder="Email" required>
<input type="submit" value="Register">
</form>
JS:
var form = document.getElementById('form')
form.addEventListener('submit',function(event){
event.preventDefault()
var username = document.getElementById("username").value
console.log(username)
var email = document.getElementById("email").value
console.log(email)
})
Error Massage:
Uncaught TypeError: Cannot read properties of null (reading ‘addEventListener’)
How do I make my splice method to return value after a certain index in a forloop and then reverse the array without using reverse function?
I am trying to check if an object in an array is same as the object and if they are the same then use splice method to extract that particular object and others after to another array and then reverse them without reverse function. Please help
function func()
{
for(var i = 0; i < array.length; i++)
{
if(array[i].key == object.key)
{
2ndarray.splice(0,0,array[i]);
break;
}
}
}
Fisheye effect D3js image slideshow works on rects/objects but not image files
My issue is that the animation works fine when the images have no content to them as below, but once they are loaded the interactions get pretty weird.
Here is a code snippet:
var data = ['https://cdn.britannica.com/60/8160-050-08CCEABC/German-shepherd.jpg', 'https://cdn.britannica.com/60/8160-050-08CCEABC/German-shepherd.jpg', 'https://cdn.britannica.com/60/8160-050-08CCEABC/German-shepherd.jpg', 'https://cdn.britannica.com/60/8160-050-08CCEABC/German-shepherd.jpg', 'https://cdn.britannica.com/60/8160-050-08CCEABC/German-shepherd.jpg'];
var w = window,
d = document,
e = d.documentElement,
g = d.getElementsByTagName('body')[0],
wid = 400
y = 400;
var svg = d3.select("body").append("svg")
.attr("width", wid)
.attr("height", "400")
.on('mousemove', () => {
let x = event.x-20;
d3.selectAll('.content')
.attr('x', (d,i) => fisheye(d,x))
})
.on('mouseleave', () => {
d3.selectAll('.content').transition().attr(
'x', (d,i) => xScale(i))
})
var chart = svg.append('g')
.classed('group', true)
let xScale = d3.scaleBand().domain(d3.range(5)).range([0,wid]).padding(0)
let rects = svg.selectAll('content')
.data(
d3.range(5)
//data //(uncomment this, and comment line above to try loading images)
)
rects.exit().remove();
rects.enter()
.append("svg:image")
.attr("xlink:href", d => d)
.attr("class","content")
.attr("y", 0)
.attr("x", (d, i) => xScale(i))
.attr("width", "300px")
.style("opacity",1)
.attr("stroke","white")
.style('fill', 'rgb(81, 170, 232)')
.attr("height", 400);
let distortion = 10;
function fisheye(_, a) {
let x = xScale(_),
left = x < a,
range = d3.extent(xScale.range()),
min = range[0],
max = range[1],
m = left ? a - min : max - a;
if (m === 0) m = max - min;
return (left ? -1 : 1) * m * (distortion + 1) / (distortion + (m / Math.abs(x - a)))+a;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
I’m trying to make something that looks like this:
https://www.nytimes.com/newsgraphics/2013/09/13/fashion-week-editors-picks/index.html
I would really appreciate some help on getting that snippet to work and if possible as smoothly as this website link! That was made by the Bosstock himself and I’m a d3 newbie so I’m quite out of my depth.
Node.js press Media_Play_Pause Key
So I`m finally trying to learn some javascript.
As a little exercise, I started to write a vs code extension.
I need to virtually press the media_play_pause key.
In Python I can just write:
import win32api
win32api.keybd_event(0xb3, 34)
I tried multiple different things but nothing worked so far.
The closest I got was:
var ks = require("node-key-sender");
ks.sendKey("@179");
But it just won`t work.
Sending many requests in chrome console, but wait in between
the UI of my product is not yet fully developed, therefore I often find myself manually sending out fetch requests from the Chrome devtools console. However, sometimes I have to send out requests in bulk, which makes me just loop through them:
request.forEach(function(req){
await fetch(url, req);
});
For some reason though, it seems like my server is not OK with this volume, and doesn’t properly execute all the requests. I thought that sleeping the thread in between the requests would help, but… how do I actually do that?
setTimeout or setInterval don’t seem like good approaches for this problem.
Thanks!
Force reset promise when re-activated
I’m attempting to have an async function that resets if it’s recalled. This function is linked to multiple buttons, and triggers a div acting as a notification overlay box.
I would like, when the callAlert() function is called again, it resets the timeout on clearAlert(). I attempted to add 1500 ms when the newAlert is called, but I’m assuming that when any of the buttons (which trigger callAlert()) is clicked, it’s already moved onto the clearAlert() promise. Either that, or I end up with a longer and longer wait time as it accumulates.
Any advise would be great.
let alertActive = false;
let alertCd = 0;
function newAlert(){
return new Promise((resolve,reject)=>{
setTimeout(()=>{
alert_pop.classList.remove("alert_pop");
alertActive=true;
alertCd = 1500
resolve();
} , 100);
});
}
function clearAlert(){
return new Promise((resolve,reject)=>{
setTimeout(()=>{
alert_pop.classList.add("alert_pop");
alert_string.innerHTML="";
resolve();
} , alertCd);
alertActive=false;
});
}
async function callAlert(){
await newAlert();
await clearAlert();
}
JavaScript user prompt 2d array lookup – Elf Name Generator
Started with what I thought was a simple idea for a class activity for our JavaScript unit, but falling foul best way to read a JavaScript 2D array based on a user input.
How can I get it to look up the users entry in the first index of the array and output the value in the second index? I need to tell it at some point which index to read and which to output, via similar syntax to [0][1] I imagine, but trial and error is getting me far.
Perhaps there is a better way??
Here is what I have so far, which just outputs the first array entry in its entirety – “A”,”Angelic”
var firstNames = [
["A","Angelic"],
["B","Blustery"],
........
["Y","Cheery"],
["Z","Dancy"]
];
var firstInitial = window.prompt("What is the first letter of your first name: ").toUpperCase();
let elfFirstName = firstNames.find(firstSearch);
function firstSearch(firstInitial) {
return firstInitial;
}
window.alert("Your Elf Name is " + elfFirstName);
</script>```
Thanks
Can I use object destructuring in express middleware
I have a simple function in a middleware that handles a scenario where a page cannot be found.
This function only requires the res
parameter to respond, it does not need the req
, res
and next
callback.
Is it okay to use Curley braces in the function – where I pass the parameter, so my code doesn’t need req
and next
?
I haven’t seen any examples like this, so unsure if there are issues.
function notFound ({ res }) {
res.sendStatus(404);
}
Lambda function as SQS Event handler doesn’t run a part of code and finishing successfully
I’m using SQS and NodeJS lambda (as SQS Event handler) for creating/updating events in Google Calendar.
The code is similar to this
...
export const handler = async (event) => {
const schemaEvent = getDataFromEvent(event)
console.log('schemaEvent', schemaEvent)
const { data } = await calendar.events.insert({
calendarId: CALENDAR_ID,
requestBody: schemaEvent,
sendUpdates: 'all',
})
console.log('data', data)
}
...
When SQS receives many events (for ex.: 30), for some of events i can’t see last console.log('Data', data)
and code after that doesn’t execute. But, if concurrency is set to 1 it works as expected.
What a reason of the problem can be?
Note:
BatchSize = 1
for handler- SQS type is
FIFO
- Dedupe is disabled
Logs ( RequestId: e1c8a24b-8052-544e-8e44-f868b56273d5
wasn’t processed till the end):
2021-12-02T22:56:15.211+02:00 START RequestId: 75dff3c9-26d5-5087-9110-a9ea13fba018 Version: $LATEST
2021-12-02T22:56:15.317+02:00 2021-12-02T20:56:15.299Z 75dff3c9-26d5-5087-9110-a9ea13fba018 INFO schemaEvent {... some data}
2021-12-02T22:56:16.176+02:00 2021-12-02T20:56:16.176Z 75dff3c9-26d5-5087-9110-a9ea13fba018 INFO data { ...some data }
2021-12-02T22:56:16.238+02:00 END RequestId: 75dff3c9-26d5-5087-9110-a9ea13fba018
2021-12-02T22:56:16.238+02:00 REPORT RequestId: 75dff3c9-26d5-5087-9110-a9ea13fba018 Duration: 1712.34 ms Billed Duration: 1713 ms Memory Size: 256 MB Max Memory Used: 164 MB
2021-12-02T22:56:16.512+02:00 START RequestId: e1c8a24b-8052-544e-8e44-f868b56273d5 Version: $LATEST
2021-12-02T22:56:16.717+02:00 2021-12-02T20:56:16.700Z e1c8a24b-8052-544e-8e44-f868b56273d5 INFO schemaEvent {...some data}
2021-12-02T22:56:18.225+02:00 END RequestId: e1c8a24b-8052-544e-8e44-f868b56273d5
2021-12-02T22:56:18.225+02:00 REPORT RequestId: e1c8a24b-8052-544e-8e44-f868b56273d5 Duration: 1710.32 ms Billed Duration: 1711 ms Memory Size: 256 MB Max Memory Used: 164 MB
...
My javascript function returns data.forEach is not a function [duplicate]
I’m trying to run this forEach to fill as null the positions of the array where the attributes have the value = 0
var dados ={aguardando: 314356, enviando: 6440, enviado: 23455, erro: 7716, lido: 98, …}
function createLotesChart4(dados){
var dataChart = {};
dataChart['masstotal'] =dados.aguardando + dados.enviando + dados.enviado + dados.lido + dados.respondido + dados.erro + dados.pausado + dados.blacklist;
dataChart['disparado'] = dados.enviado;
dataChart['lidos'] = dados.lido;
dataChart['respondidos'] = dados.respondido;
dataChart['soft_bounce'] = dados.erro;
dataChart['hard_bounce'] = dados.blacklist;
dataChart['processando'] = dados.aguardando + dados.enviando;
var dataChartJSON = JSON.stringify(dataChart);
dataChartJSONObject = JSON.parse(dataChartJSON);
//var = 0 ? null : var
dataChartJSONObject.forEach(function(element, index) {
if (element === 0) {
dataChartJSONObject[index] = null;
}
});
...
error presented on console:
Uncaught TypeError: dataChartJSONObject.forEach is not a function
at createLotesChart4 (gerencial:2805)
at Object.success (gerencial:2195)
at fire (jquery.js:3182)
at Object.fireWith [as resolveWith] (jquery.js:3312)
at done (jquery.js:8757)
at XMLHttpRequest.<anonymous> (jquery.js:9123)
How do i filter sitemap url with date modified to show urls for current date in app script?
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName(‘Sheet1’);
function getLinks(){
var xml = UrlFetchApp.fetch(‘https://www.*********.com/job_listing-sitemap.xml’).getContentText();
var xmlObj = XmlService.parse(xml);
var root = xmlObj.getRootElement();
var ns = XmlService.getNamespace(‘http://www.sitemaps.org/schemas/sitemap/0.9’);
var links = root.getChildren();
var linksArr = [];
for(var i = 0; i < links.length; i++){
linksArr.push([links[i].getChildren()[0].getText()]);
}
sheet.getRange(2, 1, linksArr.length, 1).setValues(linksArr);
}