Posts

Showing posts with the label Recent Questions - Stack Overflow

How to extract items from a subarray and push them to the main array

I'm doing a type speed test and, for this, I'll need to get a random item from an array, split every letter, push it to a new one and re-do this several times. But, every time I split the string from the first array, returns to my new array a subarray, instead of just letters. How can I extract everything from the subarrays and put into my main array? var Pokemon = ["Bulbasaur","Ivysaur","Venusaur","Charmander","Charmeleon","Charizard","Squirtle","Wartortle","Blastoise","Caterpie","Metapod","Butterfree","Weedle","Kakuna","Beedrill","Pidgey","Pidgeotto","Pidgeot","Rattata","Raticate","Spearow","Fearow","Ekans","Arbok","Pikachu","Raichu","Sandshrew","Sandslash","Nidoran","Nidorina",...

Trying to pull text from one field and put it into a button text Trying to pull text from one field and put it into a button text

I have a page that I can use merge fields from a CMS to dynamically adjust content; however, this functionality doesn't work with button text. Therefore, I need to use a normal text field and then take the value from that field and push it to the button text. I thought this would work, but something it's not working right. Can anyone help me figure out what I am doing wrong? <div id="ctatext" class="ctabutton">Request Pricing</div> <input type="submit" value="Get Started" data-wait="Please wait..." id="ctabutton" class="_2-0-yellow-btn-2 request w-button"> <script> $(document).ready(function () { let btntext = $('.ctabutton').text(); $('input._2-0-yellow-btn-2 request w-button').val(btntext); }); </script> from Stackoverflow

react js useState array is empty in first time click in the console log react js useState array is empty in first time click in the console log

Image
Please check my below code. I try to check the console log value, but in the first button click, the array is empty. After the second click the array will be loaded correctly. Please check this: sample The above sample can be found on Google. I console log the value as below Why is the array empty in the first click? Another question is, I need to print the value in the first click. How can I do it? Do you know any alternative method? from Stackoverflow

Javascript return undefined for an internal function Javascript return undefined for an internal function

I am doing an easy leetcode questions where we add one to a number whose digits are stored in an array. My logic works well but the returned value is undefined. Console gives the correct answer. Why? And how do I fix it? var plusOne = function(digits) { addNumber(digits.length - 1, 1, digits) function addNumber(index, value, digitsArr) { let sum = digitsArr[index] + value if(sum > 9) { let onesDigit = parseInt(sum.toString().charAt(1)) digitsArr[index] = onesDigit let twosDigit = parseInt(sum.toString().charAt(0)) addNumber(index-1, twosDigit, digitsArr) } else { digitsArr[index] = sum console.log(digitsArr) return digitsArr } } }; console.log(plusOne([1,2,9])) from Stackoverflow

Refresh page after clicking button (ok / cancel) Refresh page after clicking button (ok / cancel)

i could use some help. I want the page to refresh when someone clicks 'ok' or 'cancel' Help is appreciated, thanks alot. This is the code: Button <button class="center" type="submit" style="border: 0; background: transparent"> <img src="Playbutton.png" width="800" height="400" alt="submit" onclick="clicked();" /> </button> Javascript <script type="text/javascript"> function clicked() { if (confirm('You just clicked the button, click ok or cancel to refresh.')) { yourformelement.submit(); location.reload(); } else { return false; } } </script> from Stackoverflow

Trying to add a mp3 sound to a pressed button Trying to add a mp3 sound to a pressed button

I am as green as with Javascript but I am just wanting the page below to change the photo (which it does) update the text (which it does) and play the song of the bird once the bird name is pressed. I have it playing one song with the use of the "Play" button, then I tried to move parts of that in to each function, no joy. I have tried to an another getelementbyid (audio) but that didn't work, I am stuck when trying to have it run from within each function. I hope that is kind of clear and thanks for any help in advance. <html> <head> </head> <body> <p> <h2>Click the button to change the bird image.</h2> </p> <img id="myImg" src="http://www.outgrabe.net/bird04.jpg" width="207" height="198"> <p id="p1">Rose Robin by JJ Harrison (CC-by-SA)</p> <BR></BR> <button onclick="myFunction_1()">Pardalote<...

TypeError: dispatch is not a function React and Redux TypeError: dispatch is not a function React and Redux

I get an error when I delete some lead(item). It deletes from the database but not from UI and gives this error dispatch is not a function. //lead.js from /action export const deleteLead = (id) => { return (dispatch) => { axios .delete(`/api/leads/${id}/`) .then((res) => { dispatch({ type: DELETE_LEAD, payload: id, }); }) .catch((err) => console.log(err)); }; }; //Frontend file import { getLeads, deleteLead } from "../../actions/leads"; <button onClick={deleteLead(lead.id)} className="btn btn-danger btn-sm"> Delete </button> from Stackoverflow

How do you center a rectangle in javaScript? Having the X and Y position of the rectangle being the center of the rectangle How do you center a rectangle in javaScript? Having the X and Y position of the rectangle being the center of the rectangle

How do you center a rectangle in javaScript? Having the X and Y position of the rectangle being the center of the rectangle. This is a rough idea for my code. var cxt = canvas.getContext("2d"); var canvas = var canvas = document.getElementById("myCanvas"); function createSprite(x,y,width,height) { this.x=x; this.y=y; this.width=width; this.height=height; this.display(){ cxt.beginPath(); cxt.rect(this.x,this.y,this.width,this.height); cxt.fill(); cxt.stroke(); } } from Stackoverflow

Best way to make file buffer accessible outside a callback function in Javascript for large files? Best way to make file buffer accessible outside a callback function in Javascript for large files?

I am new to JS, and I need to load a file1, decompress a part of it to file2, and then make that decompressed file2 available to user's download--all completely browser-side (no Node.js etc.). For decompression I have: let fb; const decB = document.querySelector('button[id="dec"]') const inputB = document.querySelector('input[type="file"]') input.addEventListener('change', function(e) { const r = new FileReader() r.onload = function () { const archive = new Uint8Array(r.result, start, length) try { fb = pako.inflate(archive); } catch (err) { console.log(err); } } r.readAsArrayBuffer(input.files[0]) }, false) decB.addEventListener("click", function(e) { try { const t = new TextDecoder().decode(fb) console.log(t) } catch(err) { console.log(err) } }, false) I want to be able to access the contents of the resu...

d3.js force directed tree matrix d3.js force directed tree matrix

In previous applications, I have adapted standalone trees into a "matrix" format that uses rows and columns to display many small hierarchical relationships in one visual. See: D3.js v5 - Swarm Tree - How to iteratively center swarms around tree nodes For the next project, I was attempting the same thing but with "force-directed-trees." Hit a roadblock though after I followed the identical procedure as above and no errors were thrown in the process. Snippet: var margins = {top:100, bottom:300, left:100, right:100}; var height = 600; var width = 900; var totalWidth = width+margins.left+margins.right; var totalHeight = height+margins.top+margins.bottom; var svg = d3.select('body') .append('svg') .attr('width', totalWidth) .attr('height', totalHeight); var graphGroup = svg.append('g') .attr('transform', "translate("+margins.left+","+margins.top+")"); var data = [ {name:"Comp...

Ignore errors returned from API calls nodeJS Ignore errors returned from API calls nodeJS

I have a NodeJS script which is making thousands of REST API GET calls to SharePoint to retrieve all folders and files recursively. A problem I have encountered is once in a while I am receiving ECONNRESET errors and 404 Not Found for some folders with unsupported characters. This causes my code to stop and I lose my progress in retrieving all the files and folders. Is there something I can do to prevent these errors from stopping my code and just have it ignore the error and continue onto the next folder? I thought catching the error and console logging it would suffice but this still ends the execution of the code. Thanks //Imports and Declarations const prompt = require("prompt-sync")({ sigint: true }); const { getCreds, pullFromSharePoint } = require('./helper'); const sprequest = require('sp-request'); var path = require('path'); let creds = getCreds(); let spr = sprequest.create(creds) let SPUrl = 'url to sharepoint site'; let files = [...

JS Upload file to HTML File Element preserving the effects of a regular click JS Upload file to HTML File Element preserving the effects of a regular click

How can I use javascript to upload an image to a specific HTML file element (for example, the dropzone on images.google.com)? I have tried doing fileElement.files = [myFile]; But that just uploads my file to the specific HTML file element, without triggering the normal effect of uploading to that file element (for example, triggering the actual google search of the image) from Stackoverflow

Is it possible to implement a two-way weak map in JavaScript? Is it possible to implement a two-way weak map in JavaScript?

Is it possible to make something like a WeakMap that is two way (get a value by its key, or get a key by its value)? The usage would look like this (in TypeScript syntax to better illustrate): class TwoWayWeakMap { // What goes here? } class SomeClass {} const map = new TwoWayWeakMap<SomeClass, number>() const o = new SomeClass map.set(o, 42) console.log(map.get(o)) // logs "42" console.log(map.keyFrom(42)) // logs "SomeClass {}" (the `o` object) At any point later, if o is no longer referenced except inside the TwoWayWeakMap , then the SomeClass object that o was pointing to could be collected. from Stackoverflow

Why changing variable equal to a HTML collection changes the original values of the collection? Why changing variable equal to a HTML collection changes the original values of the collection?

There's a different behaviour that I see that I can't really understand exactly why this happens. Originally, after making a variable equal to another, it will only copy the value of one variable to another, but if I change the value of a variable after that, the other variable won't be affected, right? As in: let a = 3 let b = 5 b = a //here the variable b, that was 5 will become the same as the variable a, becoming 3. a = 10 //now, if I change the value in a to 10, b will still have the value of 3. That's pretty basic JavaScript, I know. But knowing that, I can't understand why it's different when it comes to HTMLcollection. Here is the situation: const allLi = document.getElementsByTagName('li'); for (let xis of allLi) { xis.classList.toggle('highlight'); } Here I got a HTMLcollection and assigned it to the variable allLi, and then I used a for of loop to modify it, thus changing the original values in the HTMLcollection, that reefe...

Matrix array algorithm logic in javascript Matrix array algorithm logic in javascript

Need some help in solving this algorithm in javascript. How to write solution considering time complexity. Considering the maximum key value is 3. input1 = [{0: "small"},{0: "large"}] output1 = [ 'small.', 'large.'] ----------------------------------------- input2 = [ {0: "small"},{0: "large"}, {1: "red"} ] output2 = ['small.red', 'large.red'] ----------------------------------------- input3 = [{0: "small"},{0: "large"}, {1: "red"}, {2:"cake"} ] output3 = ['small.red.cake', 'large.red.cake'} ----------------------------------------- input4 = [{0: "small"},{0: "large"}, {1: "red"}, {1: "orange"}, {2: "cake"} ] output4 = ['small.red.cake', 'large.red.cake', 'small.orange.cake', 'large.orange.cake'} ------------------------------------------ input5 = [ {0: "small...

How to find what period of given timespans is currently How to find what period of given timespans is currently

I've been given 6 hour-and-minute timestamps which define a period of time, lets call them 1 trough 6. (example: 03:13, 05:22, 12:54, 16:55, 20:23, 22:14) For example: 1st period starts at 03:13 and lasts until 05:22 -1 minute, and so on Naturally, at the end, periods must cover all 24 hours in a day so the sixth period (which starts at 22:14) will last until 03:13 What is the best/most optimal way to write a function that can tell what period of time we are currently in? Here is my try (which doesn't work and is suboptimal): function currentPeriod(hrs, mins, now) { // hrs is an array of integers and they define only hours (3, 5, 12,...) // mins is an array of integers and they define minutes (13, 22, 54,...) // now is a JavaScript Date if(now.getHours() > 0 && now.getHours() < hrs[0]) { return 6; } else if(now.getHours() == hrs[0] && now.getMinutes() < mins[0]) { return 6; } else if(now.getHours() == ...

map values in an array to values in another array in Javascript map values in an array to values in another array in Javascript

please I have 2 arrays in the following format const images = ["image1", "image2", "image3", "image4"] const items = [{quantity: 1}, {quantity: 2}, {quantity: 4}, {quantity: 1}] I need the final output to be like below const newArray = [ { image: "image1", quantity: 1 }, { image: "image2", quantity: 2 }, { image: "image3", quantity: 4 }, { image: "image4", quantity: 1 }, ] from Stackoverflow

I am having trouble with this ajax timer it is not doing what I expect and does not execute I am having trouble with this ajax timer it is not doing what I expect and does not execute

Ok i am back to this not executing I have in php head the following https://deniserose.000webhostapp.com/fetch_sql.php <head> <title>Audio Stream</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> I have in java script which i am loading at end of the php file <script src = 'js/fetch_updater.js'></script> now this never seems to get run // Start Clock refresh // uses new new Ajax.PeriodicalUpdater( // in main fetch file to trigger the auto update of the page. // Written by Denise Rose var gUpdateDiv="...

Photoshop, script to find a layer that contains a word in its layer's name Photoshop, script to find a layer that contains a word in its layer's name

hope you guys can help me. I need a script that can find a layers name, for example if i have this layers: Wood 123 Canvas Wood 456 Specular Wood 789 Lights And i would like to find the layer that contains Canvas. And maybe, if its possible, change the layer's name color to green. I found also this code i tried: try { (ref1 = new ActionReference()).putName(stringIDToTypeID('layer'),"Canvas"); // replace Canvas with your layer name (desc1 = new ActionDescriptor()).putReference(stringIDToTypeID('null'), ref1) executeAction(stringIDToTypeID('select'), desc1, DialogModes.NO); } catch (e) { alert("Sorry, this layername does not exists"); } This works great but only if the layer's name is exactly "Canvas".. and that's the problem from Stackoverflow

How do I format ReactJs date picker to look normal? How do I format ReactJs date picker to look normal?

import React, { useState } from "react"; import DatePicker from "react-datepicker"; function GenericCalendarRange() { const [startDate, setStartDate] = useState(null); const [endDate, setEndDate] = useState(null); return ( <> <h4 className="datepicker__title"> From </h4> <DatePicker selected={startDate} onChange={(date) => setStartDate(date)} selectsStart startDate={startDate} endDate={endDate} /> <h4 className="datepicker__title"> To </h4> <DatePicker selected={endDate} onChange={(date) => setEndDate(date)} selectsEnd startDate={startDate} endDate={endDate} minDate={startDate} /> </> ); } export default GenericCalen...