Do I do this:
function multiply(num1,num2) {
let result = num1 * num2;
return result;
}
Or do I do this:
function multiply(num1,num2) {
return num1 * num2;
}
And is there a speed difference between them or more memory efficiency?
Blancer.com Tutorials and projects
Freelance Projects, Design and Programming Tutorials
Category Added in a WPeMatico Campaign
Do I do this:
function multiply(num1,num2) {
let result = num1 * num2;
return result;
}
Or do I do this:
function multiply(num1,num2) {
return num1 * num2;
}
And is there a speed difference between them or more memory efficiency?
I am facing an issue with handling errors in my app. This is what my back-end is set up to send.
exports.getTVEvent = async (req, res) => {
try {
let response = await axios.get(``)
if (response.data.tvevent === null) throw new Error("No Channel found")
return res.status(200).send(response.data.tvevent)
} catch (err) {
return res.status(404).send(err.message)
}
}
When I look back at the front-end of the app all I get is 404 Not Found and not the actual error message of No Channel Found
When I look at the body of the response this is what I get. My code below is a fetch hook I use throughout the app.
const getData = async () => {
setIsPending(true);
try {
const res = await fetch(`http://localhost:3000/${url}`, {signal: controller.signal})
console.log(res)
if (!res.ok) throw new Error(res.statusText)
const json = await res.json();
setIsPending(false)
setError(null);
setData(json);
} catch (err: unknown) {
if (err instanceof Error) {
if (err.name === "AbortError") {
console.log("Fetch was aborted.")
} else {
console.log(err)
setIsPending(false)
setError('Error received from server: ' + err.message)
console.log(err.message)
}
}
}
}
getData();
I am not sure as to what I am doing wrong and why the front-end is not able to receive the back-end message. I have also tried to send the message within an object too return res.status(404).send({error: err.message})
if anyone has any ideas?
I am using this API: “https://rickandmortyapi.com/api/character/?page=2&name=rick”
With javascript I have to get the values of the characters of Rick & Morty with fetch:
The response.json() when I look for the character ”Rick” returns this:
But in the return, I want only to get the first character in the array (In the image the yellow square)
const fetch = require ('node-fetch');
function searchCharacter(){
fetch(`https://rickandmortyapi.com/api/character/?name=rick`)
.then( (response) => {
let array = response.json();
return array;
})
.then ( (body) => {
console.log(body);
})
}
searchCharacter();
I’m working through the Fullstack Open MOOC course from the University of Helsinki and I’m currently stuck on exercise 1.3
I have a collection of objects that contain a course name and the number of exercises for that associated course. I need to pass down these objects into the Content component so that each course name and exercises render on the page. I’ve coded it up like so:
const Part = (props) => {
console.log("propsPart: ", props)
return(
<>
<p>{props.name} {props.exercises}</p>
</>
)
}
const Content = (props) => {
console.log("propsContent: ", props)
return(
<>
<Part {...props}/>
<Part {...props}/>
<Part {...props}/>
</>
)
}
const App = () => {
const course = 'Half Stack application development'
const part1 = {
name: 'Fundamentals of React',
exercises: 10
}
const part2 = {
name: 'Using props to pass data',
exercises: 7
}
const part3 = {
name: 'State of a component',
exercises: 14
}
return (
<div>
<Header course={course}/>
<Content {...part1} />
</div>
)
}
I don’t understand how to pass in multiple objects into the Content component. Can someone tell me what’s missing from the Content component and how to structure it so it accepts multiple props?
I am trying to add an image to firebase and while the image is uploading to my storage it is not uploading to my database. How can I fix this. This is the code I have for that section
for (let i = 0; i < filess.length; i++) {
storage.ref(refUUID + '/' + filess[i].name).put(filess[i]).then(() => {
storage.ref(refUUID + '/' + filess[i].name).getDownloadURL().then(function (url) {
database.ref(listingType + '/' + refUUID + '/Description/Images/Image' + (i + 1)).set({
Link: url,
name: 'Image' + (i + 1)
})
});
});
}
We are trying to map an array of numbers to sound and are following the approach mentioned in this ‘A Tale of 2 Clocks’ article to schedule oscillator nodes to play in the future. Each oscillator node exponentially ramps to a frequency value corresponding to the data in a fixed duration (this.pointSonificationLength). However, there’s a clicking noise as each node stops, as referenced in this article by Chris Wilson. The example here talks about smoothly stopping a single oscillator. However, we are unable to directly use this approach to smoothen the transition between one oscillator node to the other.
To clarify some of the values, pointTime refers to the node’s number in the order starting from 0, i.e. as the nodes were scheduled, they’d have pointTime = 0, 1, 2, and so forth. this.pointSonificationLength is the constant used to indicate how long the node should play for.
The first general approach was to decrease the gain at the end of the node so the change is almost imperceptible, as was documented in the article above. We tried implementing both methods, including setTargetAtTime and a combination of exponentialRampToValueAtTime and setValueAtTime, but neither worked to remove the click.
We were able to remove the click by changing some of our reasoning, and we scheduled for the gain to start transitioning to 0 at 100ms before the node ends.
However, when we scheduled more than one node, there was now a pause between each node. If we changed the function to start transitioning at 10ms, the gap was removed, but there was still a quiet click.
Our next approach was to have each node fade in as well as fade out. We added in this.delay as a constant to be the amount of time each transition in and out takes.
Below is where we’re currently at in the method to schedule an oscillator node for a given time with a given data point. The actual node scheduling is contained in another method inside the class.
private scheduleOscillatorNode(dataPoint: number, pointTime: number) {
let osc = this.audioCtx.createOscillator()
let amp = this.audioCtx.createGain()
osc.frequency.value = this.previousFrequencyOfset
osc.frequency.exponentialRampToValueAtTime(dataPoint, pointTime + this.pointSonificationLength)
osc.onended = () => this.handleOnEnded()
osc.connect(amp).connect(this.audioCtx.destination)
let nodeStart = pointTime + this.delay * this.numNode;
amp.gain.setValueAtTime(0.00001, nodeStart);
amp.gain.exponentialRampToValueAtTime(1, nodeStart + this.delay);
amp.gain.setValueAtTime(1, nodeStart + this.delay + this.pointSonificationLength);
amp.gain.exponentialRampToValueAtTime(0.00001, nodeStart + this.delay * 2 + this.pointSonificationLength);
osc.start(nodeStart)
osc.stop(nodeStart + this.delay * 2 + this.pointSonificationLength)
this.numNode++;
this.audioQueue.enqueue(osc)
// code to keep track of playback
}
We notice that there is a slight difference between the values we calculate manually and the values we see when we log the time values using the console.log statements, but the difference was too small to potentially be perceivable. As a result, we believe that this may not be causing the clicking noise, since the difference shouldn’t be perceivable if it’s so small. For example, instead of ending at 6.7 seconds, the node would end at 6.699999999999999 seconds, or if the node was meant to end at 5.6 seconds, it would actually end at 5.6000000000000005 seconds.
Is there a way to account for these delays and schedule nodes such that the transition occurs smoothly? Alternatively, is there a different approach that we need to use to make these transitions smooth? Any suggestions and pointers to code samples or other helpful resources would be of great help!
On the RSS site Feedly, clicking an article defaults to opening an on-page preview of the article. In order to open the full article in a new tab, the user must ctrl+click. I’m trying to write a simple userscript to automatically open a clicked article in a new tab, but I’m not experienced with combining JS and HTML.
This is an example of the outer HTML for one article:
<article id="fLHFtwryZugkTI3NC4UrLqmHQcckXfXbVh1XRHy9YeE=_17e8e258822:19cca6e:c8b06589_main" class="entry entry--selected entry--unread u5 density-24" data-alternate-link="https://www.theguardian.com/science/2022/jan/24/james-webb-space-telescope-station-a-million-miles-from-earth"
data-navigation="inline" data-inlineentryid="fLHFtwryZugkTI3NC4UrLqmHQcckXfXbVh1XRHy9YeE=_17e8e258822:19cca6e:c8b06589" data-u="5">
<div class="visual-container">
<div class="visual" style="background-image: url("https://lh3.googleusercontent.com/b4TTLa9CuY9dHVaGhVo4pjMIBcuVDJvreIiCjB-X3ier6g_MQmyF7ivmfXu0gsyN0w6JAQMVJ_Oy4q5gol3MYsRN7QsW8zVayHHWYhZn=s347");"></div>
<div class="visual-overlay"></div>
</div>
<div class="content"><a class="link entry__title" href="https://www.theguardian.com/science/2022/jan/24/james-webb-space-telescope-station-a-million-miles-from-earth" target="_blank" rel="noopener noreferrer">James Webb Space Telescope takes up station a million miles from Earth</a>
<div
class="EntryToolbar dark"><button aria-label="Read Later" class="EntryReadLaterButton EntryReadLaterButton--dark button-icon-only" type="button"><span class="button__icon-wrapper"><svg width="24" height="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" class="icon icon-white"><path d="M16 2.929H8a2.5 2.5 0 0 0-2.5 2.5v16l.007.084a.5.5 0 0 0 .723.36l5.777-2.998 5.762 2.997a.5.5 0 0 0 .731-.443v-16a2.5 2.5 0 0 0-2.5-2.5Zm0 1 .144.006A1.5 1.5 0 0 1 17.5 5.43v15.176l-5.261-2.737-.09-.036a.5.5 0 0 0-.371.036L6.5 20.606V5.429a1.5 1.5 0 0 1 1.5-1.5h8Z" fill="currentColor" fill-rule="nonzero"></path></svg></span></button>
<div
class="fx tag-button"><button aria-label="Save to Board" class="tag-button__button EntryToolbar__tag-button EntryToolbar__tag-button--dark tag-button__button--dark button-icon-only" type="button"><span class="button__icon-wrapper"><svg width="24" height="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" class="icon icon-white"><g fill="currentColor" fill-rule="nonzero"><path d="M11.48 2.78a.5.5 0 0 1 .85-.08l.047.08 2.797 5.687 6.256.918a.5.5 0 0 1 .333.788l-.056.065-2.47 2.413a.5.5 0 0 1-.757-.646l.059-.069 1.746-1.709-5.516-.808a.5.5 0 0 1-.324-.191l-.052-.083-2.465-5.012-2.464 5.012a.5.5 0 0 1-.282.25l-.094.024-5.517.808 3.993 3.904a.5.5 0 0 1 .15.345l-.007.097-.942 5.511 4.93-2.602a.5.5 0 0 1 .627.133l.049.076a.5.5 0 0 1-.133.626l-.076.05-5.827 3.075a.5.5 0 0 1-.734-.446l.008-.08 1.068-6.253-4.527-4.425a.5.5 0 0 1 .194-.833l.083-.02 6.255-.918 2.798-5.688Z"></path><path d="M17 13.5a.5.5 0 0 1 .492.41l.008.09v6a.5.5 0 0 1-.992.09L16.5 20v-6a.5.5 0 0 1 .5-.5Z"></path><path d="M20 16.5a.5.5 0 0 1 .09.992L20 17.5h-6a.5.5 0 0 1-.09-.992L14 16.5h6Z"></path></g></svg></span></button></div>
<button
aria-label="Mark as Read" class="EntryMarkAsReadButton EntryMarkAsReadButton--dark button-icon-only" type="button"><span class="button__icon-wrapper"><svg width="24" height="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" class="icon icon-white"><path d="M20.215 5.65a.5.5 0 0 1 .77.63l-.057.07-11.786 12a.5.5 0 0 1-.643.06l-.07-.06-5.357-5.454a.5.5 0 0 1 .645-.76l.068.06 5 5.09L20.216 5.65Z" fill="currentColor" fill-rule="nonzero"></path></svg></span></button>
<button
aria-label="Mark as Read and Hide" class="EntryHideButton EntryHideButton--dark button-icon-only" type="button"><span class="button__icon-wrapper"><svg width="24" height="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" class="icon icon-white"><g fill="currentColor" fill-rule="nonzero"><path d="M4.79 4.79a.5.5 0 0 1 .637-.059l.07.058L19.21 18.504a.5.5 0 0 1-.638.765l-.07-.058L4.79 5.496a.5.5 0 0 1 0-.707Z"></path><path d="M18.504 4.79a.5.5 0 0 1 .765.637l-.058.07L5.496 19.21a.5.5 0 0 1-.765-.638l.058-.07L18.504 4.79Z"></path></g></svg></span></button>
</div>
<div class="metadata EntryMetadata">
<div class="EntryMetadataBasic__source-info"><span class="EntryEngagement EntryEngagement--no-icon" title="metric showing how popular this article is">24</span><a class="link entry__source" href="https://www.theguardian.com/uk">The Guardian</a> / <span class="EntryMetadataAgo ago lessThanAnHour"
title="Published: Mon, 24 Jan 2022 22:03:21 GMT
Received: Mon, 24 Jan 2022 22:12:11 GMT"> 25min</span></div>
</div>
<div class="summary"> $10bn observatory manoeuvred into position at four times the orbit of the moon, with first images expected in June The world’s largest and most powerful telescope has reached its final destination – an observation post one million miles away from
Earth. Nasa’s $10bn James Webb Space Telescope launched on Christmas Day last year from French Guiana on a quest to behold the dawn of the universe. Due</div>
</div>
</article>
and this is the userscript (JS) I have so far.
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
inputs[i].addEventListener("click", function(e) {
e.preventDefault;
var dest = inputs[i].attr("data-alternate-link");
window.open(dest, '_blank');
});
}
Can anyone help me troubleshoot this code?
I just want to throw this out there to see what more experienced coders think…
I am working on my second Full Stack application, a ToDo App (don’t judge me). And again I find myself struggling to choose which approach to go with for getting user input into the Back End DB.
On one extreme, I could do Create/Update calls with every user keystroke.
On the other extreme, I could only do the Create/Update/Delete calls to the Back End when the user clicks an “Update” button, or when logging out.
I know there is no one right way to do this, and there are many different approaches between the two extremes I listed above.
I’m just looking to start a discussion so we all can learn what the more experienced developers think. Is there a “Common Practice” for this kind of thing?
I thank you all in advance for your thoughts.
Every time I run the following function, I expect it to output the different paths embedded in my composer.json file and then perform this recursively for each package. However, it just gives me the same result over and over again. Please what am I missing here?
const packageComposer = async (node) => {
node = node ? __dirname : node;
let composer = fs.readFileSync(node + '/composer.json', 'utf8');
let dependencies = Object.keys(JSON.parse(composer).require);
console.log(node + '/composer.json');
dependencies.forEach(key => {
let dependency = key.split('/');
let dir = node + '/vendor/' + dependency[0] + '/' + dependency[1];
if (fs.existsSync(dir)) {
packageComposer(dir);
}
});
}
I am doing a News Search Engine, using React + JS and I have some problems extracting information. Let’s first of all check out the main components of my app.
Here I obtain the sections of the most viewed news of the last 7 days in the NY Times (https://developer.nytimes.com/docs/most-popular-product/1/overview I am using this API). So this is my getSections()
service:
export default function getSections () {
const URL= `https://api.nytimes.com/svc/mostpopular/v2/viewed/7.json?api-key=${API_KEY}`;
return fetch(URL)
.then(res=>res.json())
.then(response=> {
const { data = [] } = response;
if(Array.isArray(data)){
const {results} = response;
console.log(results);
const sections = results.map(result=>{
const { section } = result;
return section;
});
return sections;
}
})
};
And, later, I want to obtain the news filtered by section. In order to do that, I have other service implemented: getNewsFilteredBySection()
export default async function getNewsFilteredBySection (sectionSearched="") {
const URL= `https://api.nytimes.com/svc/mostpopular/v2/viewed/7.json?api-key=${API_KEY}`;
return fetch(URL)
.then(res=>res.json())
.then(response=> {
const { data = [] } = response;
if(Array.isArray(data)){
const {results} = response;
const filteredResults = results.filter(obj => {
return obj.section === sectionSearched;
});
console.log(filteredResults);
return filteredResults;
}
})
};
And I need a helper, to extract the attributes I exactly want from filteredResults
. That is my getNewsAttributes()
:
export function getNewsAttributes (filteredResultsJSON=[]) {
const newsAttributes = JSON.parse(filteredResultsJSON).map(filteredResultJSON=>{
const { title, abstract, url } = filteredResultJSON;
console.log(title, abstract, url);
return {title, abstract, url};
});
return newsAttributes;
};
I would like you to show my components structure. My App
component:
function App() {
const [section, setSection] = useState([]);
useEffect(() => {
getSections().then(sections=>setSection(sections));
}, [])
return (
<div>
<Navbar/>
<ListOfSections section={section}></ListOfSections>
</div>
);
}
export default App;
Here my ListOfSections
component:
export default function ListOfSections ({section}) {
const sectionFiltered = section.filter(onlyUnique);
return (
<div className="container_list_sections mt-4 ml-4">
{
sectionFiltered.map((section)=>
<Section
section={section}
// TODO: Create a generator of unique id and send it to section component
/>
)
}
</div>
)
};
Here my Section
component:
export default function Section ({section}) {
function showEvent (e) {
console.log("pasa por aquí");
const sectionSearched = e.target.innerText;
const filteredResults = getNewsFilteredBySection(sectionSearched);
console.log(`filteredResults:" ${filteredResults}`);
const newsAttributes = getNewsAttributes(filteredResults);
console.log(`newsAttributes ${newsAttributes}`)
const {title, abstract, url} = newsAttributes;
console.log (title, abstract, url);
}
return (
<div className="animate__animated animate__fadeIn animate__slower">
<h3 className="section-container mr-4 mb-4 pointer"
onClick={showEvent}
>{section}</h3>
</div>
)
};
And here my News
component, still not working properly:
export default function News ({section}) {
return (
<div>
<h3 className="section-container mr-4 mb-4 pointer">{section}</h3>
</div>
)
};
So, my problem is:
·The last console.log
of the Section
component which console shows is the next one: console.log(filteredResults:" ${filteredResults}
); showing in console
filteredResults:” [object Promise]. No further lines of that method are shown (I have
several console.log) so I might have some errors but I dont know where. My goal is to extract the following information from the object:
const {title, abstract, url} = newsAttributes;` to be able to render news with that props. Any idea where am I committing errors? Thanks a lot 🙂
/**
* @param {number} x
* @return {boolean}
*/
var isPalindrome = function(x) {
let a, b, c = 0;
a = x%10;
x=x-a;
b= x/10;
c= b%10;
let d = b-c;
let f = d/10;
let g = (a*100) + (c*10) + f;
if (g==x && x>0)
return "true";
else
return "false";
};
when the number is negative its not saying false, it says true instead. But i added x>0 condition. What’s the problem? And btw my code also doesn’t look good maybe it’s not a good way to solve the palindrome problem. And also i am not so sure if its working with numbers with more than 3 digits.
I have my code here :
// ...
run: (client,message,args) =>{
let member = message.member
console.log(member.presence) // null
if(!member.presence) return message.say(`${n} - I cannot access **${member.nickname || member.user.tag}**'s presence.`)
if(!member.presence.activities[0]) return message.reply(`${n} - No activity detected from `${member.user.tag} !``)
message.reply('Informations logged on the console.')
console.log(member.presence)
}
I keep having my bot sending this :
After having checked if other people got the same issue I only saw people who didn’t activated the following check boxes :
The thing is I already did and no matter how many times I rerun my bot, member.presence
keeps being null and I can’t understand why.
How do I get the function computerChoice()
to run when I click on the strawberryButton
which has an addEventListener? At the moment nothing happens when I click on strawberryButton
<div class="fruits">
<div class="strawberry">
<img class="strawberry-button" src="strawberry1.png" height=250px></div>
<div class="orange">
<img class="orange-button" src="orange.png" height=250px width=250px></div>
<div class="pineapple">
<img class="pineapple-button" src="pineapple.png" height=250px width=250px></div>
<div class="pear">
<img class="pear-button" src="pear.png" height=250px width=250px></div>
</div>
my JS
// Initialize everything to zero
let score = 0;
let rounds = 0;
const strawberryButton = document.querySelector(".strawberry-button");
const orangeButton = document.querySelector(".orange-button");
const pearButton = document.querySelector(".pear-button");
const pineappleButton = document.querySelector(".pineapple-button");
const score_div = document.querySelector(".score");
const userChoice_div = document.querySelector(".user-choice");
const computerChoice_div = document.querySelector(".computer-choice");
function computerChoice(){
const fruitSelection = ["orange", "strawberry", "pear", "pineapple"];
const pickFruit = fruitSelection[Math.floor(Math.random() * 4)];
return pickFruit;
}
strawberryButton.addEventListener('click', computerChoice)
I am trying to find the factorial of an integer using a function with the following constraint
1<=N<=10
Below is my code but when I execute it I am receiving NaN! Can you please explain and show me where is my mistake. Much appreciated!
const factorial = function (n) {
if (n >= 1 && n <= 10) {
return n * factorial(n - 1);
}
};
console.log(factorial(5));
I am trying to fire up a legacy React v14 project and all I did was refactor a bit the index.js
file, the root level index.js
file to look like this:
import React from "react";
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import { createStore, applyMiddleware } from "redux";
import { Router, Route, IndexRoute, browserHistory } from "react-router";
import App from "./components/app";
import reducers from "./reducers";
const createStoreWithMiddleware = applyMiddleware()(createStore);
ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>
<Router history={browserHistory}>
<Route path='/' component={App}></Route>
</Router>
</Provider>,
document.querySelector(".container")
);
And as a result I get an error in console that says:
Uncaught TypeError: Cannot read properties of undefined (reading
‘func’)