Category: javascript
Category Added in a WPeMatico Campaign
How to efficiently make multiple api calls from an array in node js
I have the following snippet of code to make multiple api calls
var userdetails:any=[]
for(var i=0;i<userids.length;i++)
{
userdetails.push(await this.getUserData(authToken,userid[i]))
}
Implementation of get userdetails function is as follows
async getUserData(authtoken,userid) {
return new Promise((resolve, reject) => {
const url = `https://***********/***/users?id=userid`;
const requestOptions = {
url,
method: 'GET',
headers: {
'Authorization': authtoken,
}
};
request(requestOptions, (err, response, body) => {
let errorMessage = 'Error in getting data';
if (err) {
return reject(err);
}
if (!response) {
return reject({
message: errorMessage
});
}
if (response.statusCode === 200) {
try {
body = JSON.parse(body);
} catch (err) {
reject({ message: errorMessage });
}
if (isArray(body)) {
let newArray: any = [];
body.forEach(element => {
newArray.push({
userId:element["userId"],
username:element["username"],
});
});
return resolve(newArray);
} else {
return resolve(body);
}
}
if (response.statusCode >= 400) {
return reject({
message: errorMessage
});
}
});
});
}
The above code works just fine and returns all the data. But there is a performance glitch in it and it is taking lot of time to return the data as the number of userid’s increase. I am already using async await approach. What can I do to tune the performance of this code?
code coverage results doesn’t reflect results of unit test cases written for electron js code
I am able to write test cases for electron.js POC code but their results are not reflecting on nyc code coverage results. As per my understanding, code coverage HTML results files should reflect the covered test cases, but it’s not happening. I have tried to find a solution on google, but no luck so far. I didn’t get much about the code coverage for electron code on google, Badly stuck with this task. I am desperately looking out for the solution. Hence, I thought to raise my doubt in this forum.
Any suggestion or input would be highly appreciated & great help to me! Thanks for reading .
**Github code link:**
https://github.com/sajid983356/pocElectronCodeCoverage
**main.js**
const { app, BrowserWindow, ipcMain } = require('electron');
let mainWindow;
function createWindow() {
mainWindow = new BrowserWindow({ width: 800, height: 600 });
mainWindow.loadFile('index.html');
mainWindow.on('closed', function () {
mainWindow = null;
});
}
app.on('ready', createWindow);
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', function () {
if (mainWindow === null) {
createWindow();
}
});
ipcMain.on('greet-me', (event, args) => {
console.log("step 1")
event.sender.send('greeting', args + ' Jane');
});
**renderer.js**
const { ipcRenderer } = require('electron');
const greetButton = document.getElementById('greetButton');
const greetElement = document.getElementById('greet');
greetButton.addEventListener('click', () => {
ipcRenderer.send('greet-me', 'Hello');
});
ipcRenderer.on('greeting', (event, args) => {
greetElement.innerText = args;
});
**test/spec.js**
const electron = require('electron');
const Application = require('spectron').Application;
const expect = require('chai').expect;
describe('Spectorn example', function () {
this.timeout(20000); //10 seconds
global.app = null;
//starts the application before all the test in this block
before(() => {
//create the electron app
app = new Application({
path: electron,
args: ['.']
});
//start the electron app
return app.start().then(() => {
app.client.waitUntilWindowLoaded();
app.browserWindow.show();
return app;
});
});
//stop th electron application after all the test
after(() => {
if (app && app.isRunning()) {
return app.stop();
}
});
it('should open the browserwindow', () => {
return app.client
.waitUntilWindowLoaded()
.browserWindow.isVisible()
.then(res => {
console.log('visible: ', res);
expect(res).to.be.equal(true);
})
.browserWindow.isFocused()
.then(res => {
console.log('isFocused: ', res);
expect(res).to.be.equal(true);
})
.browserWindow.isMinimized()
.then(res => {
console.log('isMinimized: ', res);
expect(res).to.be.equal(false);
})
.browserWindow.isDevToolsOpened()
.then(res => {
console.log('isDevToolsOpened: ', res);
expect(res).to.be.equal(false);
});
});
it('should open the browserwindow with correct size', () => {
return app.client
.waitUntilWindowLoaded()
.browserWindow.getBounds()
.then(res => {
expect(res.width).to.be.equal(800);
expect(res.height).to.be.equal(600);
});
});
it('should communicate with main process and renderer process', async () => {
const results = await app.client.waitUntilWindowLoaded();
const text = await app.client.getText('#greet');
expect(text).to.equal('');
await app.client.click('#greetButton');
const greetText = await app.client.getText('#greet');
expect(greetText).to.equal('Hello Jane');
return results;
});
});
**package.json**
{
"name": "electron-quick-start",
"version": "1.0.0",
"description": "A minimal Electron application",
"main": "main.js",
"scripts": {
"start": "electron .",
"test": "mocha",
"coverage": "nyc npm run test"
},
"repository": "https://github.com/electron/electron-quick-start",
"keywords": [
"Electron",
"quick",
"start",
"tutorial",
"demo"
],
"author": "GitHub",
"license": "CC0-1.0",
"devDependencies": {
"chai": "^4.2.0",
"electron": "^3.0.4",
"mocha": "^5.2.0",
"spectron": "^5.0.0"
},
"dependencies": {
"nyc": "^15.1.0"
}
}
**index.html**
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Testing</title>
</head>
<body>
<button id="greetButton">Greet Me</button>
<p id="greet"></p>
<script>
// You can also require other files to run in this process
require('./renderer.js')
</script>
</body>
</html>
**.nycrc.json**
{
"all": true,
"check-coverage": false,
"branches": 100,
"lines": 100,
"functions": 85,
"statements": 10,
"report-dir": "./coverage",
"reporter": [
"cobertura",
"html",
"lcov",
"text"
],
"include": [
"*.js"
]
}
**PFA for the references:**
how to show the intro image only once
I have svg and img introduction before proceed to the main page. how I show this introduction only once? here is my code:
<div class="preload">
<div class="intro">
<img src="svg/toreriha_text_animated.svg">
<img class="bground" src="/img/background.png">
</div>
</div>
<script type="text/javascript">
setTimeout(function() {
//After 9000 milliseconds, fade out the intro. The animation duration is 500 ms.
$(".intro").fadeOut(500);
}, 9000);
</script>
The chart does not appear although no error message in console (chart.js)
I am publishing the bar chart using JSON data and AJAX. The chart does not appear although no error showed in console. I am confused what is the problem because I was able to build another chart using the same way. Is there anyone can give me some clue please?
This is my codes in HTML file:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Getting Started with Chart JS with www.chartjs3.com</title>
<style>
* {
margin: 0;
padding: 0;
font-family: sans-serif;
}
.chartMenu {
width: 100vw;
height: 70px;
background: #1A1A1A;
color: rgba(255, 26, 104, 1);
}
.chartMenu p {
padding: 10px;
font-size: 20px;
}
.chartCard {
width: 100vw;
height: calc(100vh - 40px);
background: rgba(255, 26, 104, 0.2);
display: flex;
align-items: center;
justify-content: center;
}
.chartBox {
width: 700px;
padding: 20px;
border-radius: 20px;
border: solid 3px rgba(255, 26, 104, 1);
background: white;
}
</style>
</head>
<body>
<div class="chartMenu">
<p>WWW.CHARTJS3.COM (Chart JS 3.6.0)</p>
</div>
<div class="chartCard">
<div class="chartBox">
<canvas id="myChart"></canvas>
</div>
</div>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
//Ajax Block
const xmlhttp = new XMLHttpRequest(); //exchange data with a web server
const url ='http://localhost/test/total.json';
//send a request to a server
xmlhttp.open('GET',url,true);
xmlhttp.send();
xmlhttp.onreadystatechange = function(){
if(this.readyState ==4 && this.status == 200){ //is ready and connection is success
var datapoints=JSON.parse(this.responseText); //parse:make data becomes readable in JavaScript
const male =datapoints.data.gender.male;
const female = datapoints.data.gender.female;
//setup
const data = {
labels: ['male','female'],
datasets: [{
label: 'Male',
data: male,
backgroundColor: ['rgba(255, 26, 104, 0.2)'],
borderColor: ['rgba(255, 26, 104, 1)'],
borderWidth: 1
}
,
{
label: 'Female',
data:female,
backgroundColor: ['rgba(54, 162, 235, 0.2)'],
borderColor: ['rgba(54, 162, 235, 1)'],
borderWidth: 1
}
]
};
// config
const config = {
type: 'bar',
data,
options: {
scales: {
y: {
beginAtZero: true
}
}
}
};
// render init block
const myChart = new Chart(
document.getElementById('myChart'),
config
);
}
}
</script>
</body>
</html>
This is the JSON file:
{
"data": {
"date": [
"2021-11-01",
"2021-12-31"
],
"gender": {
"male": 76,
"female": 144
},
"glasses": {
"true": 108,
"false": 112
},
"beard": {
"true": 40,
"false": 180
},
"ageGroup": {
"child": [],
"adult": 162,
"senior": 58
}
},
"success": true,
"message": ""
}
Error code 1 when installing npm packages
After playing around with nodeJs I have come back to my Craft CMS websites to work on other projects.
On executing “gulp dev”, I was met by this error
Error: Node Sass does not yet support your current environment: OS X 64-bit with Unsupported runtime (93)
For more information on which environments are supported please see:
https://github.com/sass/node-sass/releases/tag/v4.14.1
at module.exports (/Users/michaelbutler/Sites/aleck-website/node_modules/gulp-sass/node_modules/node-sass/lib/binding.js:13:13)
at Object.<anonymous> (/Users/michaelbutler/Sites/aleck-website/node_modules/gulp-sass/node_modules/node-sass/lib/index.js:14:35)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Module._compile (/Users/michaelbutler/Sites/aleck-website/node_modules/pirates/lib/index.js:99:24)
at Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Object.newLoader [as .js] (/Users/michaelbutler/Sites/aleck-website/node_modules/pirates/lib/index.js:104:7)
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)
In attempting to resolve this, I removed node_modules, package.lock, and ran npm install. I have also tried npm cache clean –force as seen here How to solve npm install error “npm ERR! code 1”.
This has led to the following error:
npm ERR! code 1
npm ERR! path /Users/michaelbutler/Sites/cardtwister-website/node_modules/favicons/node_modules/sharp
npm ERR! command failed
npm ERR! command sh -c (node install/libvips && node install/dll-copy && prebuild-install) || (node-gyp rebuild && node install/dll-copy)
npm ERR! TOUCH Release/obj.target/libvips-cpp.stamp
npm ERR! CXX(target) Release/obj.target/sharp/src/common.o
npm ERR! info sharp Using cached /Users/michaelbutler/.npm/_libvips/libvips-8.8.1-darwin-x64.tar.gz
npm ERR! gyp info it worked if it ends with ok
npm ERR! gyp info using [email protected]
npm ERR! gyp info using [email protected] | darwin | x64
npm ERR! (node:1501) [DEP0150] DeprecationWarning: Setting process.config is deprecated. In the future the property will be read-only.
npm ERR! (Use `node --trace-deprecation ...` to show where the warning was created)
npm ERR! gyp info spawn /usr/bin/python2
npm ERR! gyp info spawn args [
npm ERR! gyp info spawn args '/Users/michaelbutler/Sites/cardtwister-website/node_modules/node-gyp/gyp/gyp_main.py',
npm ERR! gyp info spawn args 'binding.gyp',
npm ERR! gyp info spawn args '-f',
npm ERR! gyp info spawn args 'make',
npm ERR! gyp info spawn args '-I',
npm ERR! gyp info spawn args '/Users/michaelbutler/Sites/cardtwister-website/node_modules/favicons/node_modules/sharp/build/config.gypi',
npm ERR! gyp info spawn args '-I',
npm ERR! gyp info spawn args '/Users/michaelbutler/Sites/cardtwister-website/node_modules/node-gyp/addon.gypi',
npm ERR! gyp info spawn args '-I',
npm ERR! gyp info spawn args '/Users/michaelbutler/.node-gyp/16.13.1/include/node/common.gypi',
npm ERR! gyp info spawn args '-Dlibrary=shared_library',
npm ERR! gyp info spawn args '-Dvisibility=default',
npm ERR! gyp info spawn args '-Dnode_root_dir=/Users/michaelbutler/.node-gyp/16.13.1',
npm ERR! gyp info spawn args '-Dnode_gyp_dir=/Users/michaelbutler/Sites/cardtwister-website/node_modules/node-gyp',
npm ERR! gyp info spawn args '-Dnode_lib_file=/Users/michaelbutler/.node-gyp/16.13.1/<(target_arch)/node.lib',
npm ERR! gyp info spawn args '-Dmodule_root_dir=/Users/michaelbutler/Sites/cardtwister-website/node_modules/favicons/node_modules/sharp',
npm ERR! gyp info spawn args '-Dnode_engine=v8',
npm ERR! gyp info spawn args '--depth=.',
npm ERR! gyp info spawn args '--no-parallel',
npm ERR! gyp info spawn args '--generator-output',
npm ERR! gyp info spawn args 'build',
npm ERR! gyp info spawn args '-Goutput_dir=.'
npm ERR! gyp info spawn args ]
npm ERR! gyp info spawn make
npm ERR! gyp info spawn args [ 'BUILDTYPE=Release', '-C', 'build' ]
npm ERR! In file included from ../src/common.cc:22:
npm ERR! In file included from /Users/michaelbutler/.node-gyp/16.13.1/include/node/node.h:63:
npm ERR! In file included from /Users/michaelbutler/.node-gyp/16.13.1/include/node/v8.h:30:
npm ERR! /Users/michaelbutler/.node-gyp/16.13.1/include/node/v8-internal.h:492:38: error: no template named 'remove_cv_t' in namespace 'std'; did you mean 'remove_cv'?
npm ERR! !std::is_same<Data, std::remove_cv_t<T>>::value>::Perform(data);
npm ERR! ~~~~~^~~~~~~~~~~
npm ERR! remove_cv
npm ERR! /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/type_traits:710:50: note: 'remove_cv' declared here
npm ERR! template <class _Tp> struct _LIBCPP_TEMPLATE_VIS remove_cv
npm ERR! ^
npm ERR! 1 error generated.
npm ERR! make: *** [Release/obj.target/sharp/src/common.o] Error 1
npm ERR! gyp ERR! build error
npm ERR! gyp ERR! stack Error: `make` failed with exit code: 2
npm ERR! gyp ERR! stack at ChildProcess.onExit (/Users/michaelbutler/Sites/cardtwister-website/node_modules/node-gyp/lib/build.js:262:23)
npm ERR! gyp ERR! stack at ChildProcess.emit (node:events:390:28)
npm ERR! gyp ERR! stack at Process.ChildProcess._handle.onexit (node:internal/child_process:290:12)
npm ERR! gyp ERR! System Darwin 20.6.0
npm ERR! gyp ERR! command "/usr/local/bin/node" "/Users/michaelbutler/Sites/cardtwister-website/node_modules/.bin/node-gyp" "rebuild"
npm ERR! gyp ERR! cwd /Users/michaelbutler/Sites/cardtwister-website/node_modules/favicons/node_modules/sharp
npm ERR! gyp ERR! node -v v16.13.1
npm ERR! gyp ERR! node-gyp -v v3.8.0
npm ERR! gyp ERR! not ok
npm ERR! A complete log of this run can be found in:
npm ERR! /Users/michaelbutler/.npm/_logs/2021-12-07T11_44_09_876Z-debug.log
Note, the errors are shown in example 1 and example 2 are in different repositories as this error is happening with every project, I thought it best to show the two different steps.
Not sure if these errors are related. From searching online, I found that the following part of the error
npm ERR! code 1
Is from a conflict with node versions. As I result, I have tried brew install node@14 to step down versions, but brew link did not seem to work / did not resolve this error.
Any advise would be greatly appreciated.
I have also tried reinstalling the packages one at a time, which didn’t prevent me from installing at any point, but seemed to give a bunch of random errors on running “gulp dev” that were unclear to me.
Here is my package.json, as this will likely be required
{
"name": "doodle-craft-puppy",
"version": "0.1.0",
"homepage": "https://[email protected]/doodledevelopers/doodle-craft-puppy.git",
"repository": {
"type": "git",
"url": "https://[email protected]/doodledevelopers/doodle-craft-puppy.git"
},
"babel": {
"presets": [
[
"@babel/preset-env",
{
"targets": {
"browsers": [
"last 2 versions",
"Explorer 10"
]
}
}
]
]
},
"eslintConfig": {
"env": {
"browser": true,
"es6": true
},
"parserOptions": {
"sourceType": "module"
}
},
"browserslist": [
"last 1 version",
"> 1%"
],
"description": "Doodle's Project Scaffold for craft",
"author": "doodle",
"main": "gulpfile.js",
"license": "MIT",
"paths": {
"src": {
"scss": "./src/scss/**/*.scss",
"images": "./src/images/",
"fonts": "./src/fonts/*",
"svgs": "./src/icons/svg/**/*.svg",
"templates": "./templates/**/*.{html,twig}",
"js": [
"./src/js/app.js"
]
},
"build": {
"base": "./web/",
"css": "./web/build/css/",
"images": "./web/build/images/",
"fonts": "./web/build/fonts/",
"svgs": "./web/build/icons/svg/",
"js": "./web/build/js/"
},
"favicon": {
"src": "./src/favicons/favicon.png",
"dest": "./web/favicons/",
"path": "/img/site/"
},
"craftConfig": "./config/"
},
"urls": {
"live": "http://card-twister.com/",
"local": "http://cardtwister-website:8888/"
},
"devDependencies": {
"@babel/cli": "^7.14.8",
"@babel/core": "^7.14.8",
"@babel/preset-env": "^7.14.9",
"@babel/register": "^7.14.5",
"babel-eslint": "^10.1.0",
"babelify": "^10.0.0",
"barba.js": "^1.0.0",
"body-scroll-lock": "^2.6.4",
"browser-sync": "^2.27.5",
"browserify": "^16.5.2",
"browserslist": "^4.16.7",
"del": "^4.1.1",
"domready": "^1.0.8",
"fancy-log": "^1.3.2",
"gulp": "^4.0.2",
"gulp-autoprefixer": "^6.1.0",
"gulp-babel": "^8.0.0",
"gulp-better-rollup": "^4.0.1",
"gulp-cached": "^1.1.1",
"gulp-cheerio": "^0.6.3",
"gulp-concat": "^2.6.1",
"gulp-cssnano": "^2.1.3",
"gulp-eslint": "^5.0.0",
"gulp-favicons": "^2.4.0",
"gulp-flatten": "^0.4.0",
"gulp-if": "^2.0.2",
"gulp-imagemin": "^6.2.0",
"gulp-load-plugins": "^1.5.0",
"gulp-plumber": "^1.1.0",
"gulp-postcss": "^8.0.0",
"gulp-purgecss": "^1.2.0",
"gulp-rename": "^1.4.0",
"gulp-replace": "^1.1.3",
"gulp-sass": "^4.1.1",
"gulp-size": "^3.0.0",
"gulp-sourcemaps": "^2.2.1",
"gulp-svg-symbols": "^3.2.0",
"gulp-svgstore": "^7.0.0",
"gulp-tap": "1.0.1",
"gulp-uglify": "^3.0.2",
"gulp-util": "^3.0.8",
"regenerator-runtime": "^0.13.9",
"smooth-scroll": "github:cferdinandi/smooth-scroll",
"svgxuse": "^1.2.6",
"vinyl-buffer": "^1.0.1",
"vinyl-source-stream": "^2.0.0",
"waypoints": "^4.0.1"
},
"dependencies": {
"browser-update": "^3.3.30",
"intersection-observer": "^0.7.0",
"inuitcss": "^6.0.0",
"jquery": "^3.6.0",
"menuspy": "^1.3.0",
"sass-rem": "^2.0.1",
"sftp-sync-deploy": "^0.7.1",
"vanilla-lazyload": "^16.1.0"
}
}
javascript reposition overflow table scroll position
I am drawing a table using a function after data is received from a GET request.
After I draw the table, I want to hold the scroll position relative to the previous table that was there before (all tables have overflow:auto;
).
The way I overcome this problem is as follows:
- listen to the scroll
- store the scroll position in sessionStorage
- After the new table is drawn, I use
.scrolLeft = sessionStorage.getItem('PosY')
This works fine as it does what I want it to do, but I get the following from Chrome Dev.
[Violation] Forced reflow while executing JavaScript took 51ms
I understand why I get this from Chrome Dev. but I want to know if there is another way to do this that will not give me this [Violation]
I have looked into listening to the DOM and repositioning upon changes, but this gives the same [Violation]
Any suggestions would be much appreciated, especially if there is some simple CSS.
No jQuery OR other Libraries, please.
Is there any way that React component still keep the value from previous render?
I have a parent component, that render one child component several time. This child component is used in many different components. I need to have an array in this child component that keeps all the previous renders of the component, then get access to the largest text passed to it.
import TextComponent from '../../text'
const ParentComponent = ()=>{
// ... some code here and get some data from API
const text = getTextFromAPI()
return (
<>
<ARandomComponent/>
<AnotherRandomComponent/>
<TextComponent text={text}/>
</>)
}
In the TextComponent
I need to know what text each element received, and return the largest text. I thought maybe I can have an array inside TextComponent
but of course with each render, component has fresh data and I know this is by design.
Is there any way to active this? To store a value in the TextComponent
that other renders from different places still have access to that value
How to pass DotNetObjectReference to JS DOM-event
I am trying to utilise JS drag & drop in Blazor, which works fine in general but I want to set a custom drag image during the ondragstart
event. In general my code looks like this:
<div class="some-draggable-container"
draggable="true"
ondragstart="Element.dragStartHandler(event, '@(ImageSrcBase64)')" >
</div>
Element.dragStartHandler = function(event, imgSrcBase64) {
var img = new Image();
img.src = imgSrcBase64;
event.dataTransfer.setDragImage(img, 0, 0);
}
The problem occurring to me is that I need to call a .Net function after setting the drag image and I cannot find a way to pass the needed DotNetObjectReference
through to the JS part.
Simply passing the newly created objectRef into the JS event call leads to an Unexpected end of input
error.
ondragstart="Element.dragStartHandler(event, '@(ImageSrcBase64)', @(DotNetObjectReference.Create(this)))"
Also using the JsonSerializer
does not do the trick. It surely does serialise the object and JS is able to deserialise it, but as expected the DotNet.invokeMethod()
methods are not present.
ondragstart="Element.dragStartHandler(event, '@(ImageSrcBase64)', @(JsonSerializer.Serialize(DotNetObjectReference.Create(this))))"
Utilising the Blazor event and handling it fully in .Net does not offer the ability to set the drag image because the passed DragEventArgs
are not fully compliant to the JS one.
Passing the event args through IJSRuntime
into a JS function leads to errors because it’s just not the same thing as the native JS event, so at least the setDragImage()
Method is missing.
Is there any way to make this work? I don’t want to juggle around with JS-to-static-.Net calls and guids or that kind of workaround.
Close the alert div only after clicking the X button a number of times
<div class="alert">
<span id="button" class="closebtn" onclick="this.parentElement.style.display='none';">×</span>
This is an alert box.
</div>
I tried using the alert function but I learned that you can’t manipulate it so I created an alert div but I don’t know how to achieve the title.
Jumpy CSS transition in sidebar links text while toggle transition is running
When collapsing, the text adapts to the width of the sidebar progressively which causes a jumpy transition
Example:
As you can see the text Collapse sidebar
appears in two lines instead of a single line of text.
Desired result:
I would like to know if there is any mechanism to show the text only when it fits 100% in the sidebar and it is not cut in two lines.
I need is the text to appear only after the transition of the collapse has finished.
What I’ve tried:
-Increasing/decreasing the transition time (too radical, works if I delete the transition but somehow has to be smooth so it’s not a valid solution)
.sidebar{
position: fixed;
top: 0;
left: 0;
height: 100%;
width: 290px;
background: #193D4C;
z-index: 100;
transition: all 0.5s ease;
}
-Using backface-visibility
property. Did not work.
-Using Bootstrap 5 event type shown.bs.collapse
like this:
var myCollapsible = document.getElementById('sidebar')
myCollapsible.addEventListener('shown.bs.collapse', function () {
alert("it works!"); //This never gets fired
})
I’ve been looking for a similar question for a long time but I didn’t find anything
How will i filter sitemap urls by last modification date of today in google app script?
with the code below am able to retrieve a site’s sitemap urls and last modification dates. the problem is that there are over 600 urls retrieved, how will i filter in the script to only show urls with the last modification date of today, removing urls with old dates?
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName(‘Sheet1’);
//Create function that fires when menu item clicked.
function getLinks() {
var xml = UrlFetchApp.fetch(‘https://example.com/blog_listing-sitemap.xml’).getContentText();
var xml = XmlService.parse(xml);
var root = xml.getRootElement();
var ns = XmlService.getNamespace(‘http://www.sitemaps.org/schemas/sitemap/0.9’);
//Get list of sitemap urls
var sitemaps = root.getChildren();//sitemap
//for each sitemap URL
for (i = 0; i < sitemaps.length; i++) {
//Get child elements of sitemap element
var sitemap = sitemaps[i].getChildren();
//For each child element of sitemap element
for (a = 0; a < sitemap.length; a++) {
var element = sitemap[a];
//Find loc element for sitemap URL
if (element.getName() === 'loc') {
// xml = loadXML(element.getText());
appendRows(xml.getRootElement().getChildren());
}
else if (root.getName() === 'urlset') {//if sitemap is url sitemap.
appendRows(root.getChildren());
}
}
}
}
function appendRows(items) {
var urls = [];
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); //to write rows
//var filtered = data.filter(function (row) {
// return row[1].getFullYear() === 2016;
// });
for (var i = 0; i < items.length; i++) {
var children = items[i].getChildren();
var row = [];
for (var a = 0; a < children.length; a++) {
var child = children[a];
if (child.getChildren().length === 0) {
row.push(child.getText());
// row.filter(items)
}
}
urls.push(row);
}
//write rows to sheet
sheet.getRange(sheet.getLastRow() + 1, 1, urls.length, urls[0].length).setValues(urls);
}
Create a computed JSON array in JS with multiple variables
First off, apologies if this is normally a simple thing, but I’m not particularly experienced in JS. I’m trying to make some graphs in Plotly.js for a work site that currently holds raw JSON. We have a JSON in the format:
stuff = [{"name": "shark", "location": "somewhere", "number":10},
{"name": "shark", "location": "somewhereelse", "number":50},
{"name": "shark", "location": "somewhere", "number":25},
{"name": "turtle", "location": "anotherplace", "number":1},
{"name": "elephant", "location": "greatplace", "number":50},
{"name": "elephant", "location": "greatplace", "number":75}
And I need the result to look like:
computed = [{"name":"shark", "location":"somewhere", "number":35},
{"name":"shark", "location":"somewhereelse", "number":50},
{"name":"turtle", "location":"anotherplace", "number":1},
{"name":"elephant", "location":"greatplace", "number":125}
Where all names are grouped by location and all numbers in that group are summed. It is then this computed JSON that I’ll be using to graph with Plotly.js with some functions I have already built.
I think I can simplify the problem as:
forEach((item) => {
x.push(item['location']
y.push(y += stuff.number where stuff.location === x[-1])
}
But this also means I’ll get the same number of rows as in stuff, just computed and graphed. I’m afraid I can’t figure it out any further.
Any help would be muchly appreciated.
Everytime I test my attributes are undefined?
I want to create a class Deck that gets two attributes id and remaining. I use the Deck of Cards API to get the information of a deck but every time I create a Deck I keep getting id and remaining as undefined and I don’t understand why because the JSON value is good and when I print it I got something but my attributes are undefined.
class Deck {
constructor(numberOfDeck, jokersEnabled) {
let url;
if (jokersEnabled) {
url = "https://www.deckofcardsapi.com/api/deck/new/shuffle/?deck_count=" + numberOfDeck + "&jokers_enabled=true";
} else {
url = "https://www.deckofcardsapi.com/api/deck/new/shuffle/?deck_count=" + numberOfDeck;
}
console.log(url);
fetch(url).then(res => res.json()).then(value => {
this.id = value.deck_id;
this.remaining = value.remaining;
}).catch(function(err) {
console.log(err);
});
}
}
let deck = new Deck(1, true);
console.log(deck.id + " " + deck.remaining);
How to join javascript array elements without forloop
I have from a mongoose query result:
{
"store": [
{
"items": [
"A1",
"A2"
]
},
{
"items": [
"A3",
"A4"
]
},
{
"items": [
"B1",
"B2"
]
},
{
"items": [
"B3",
"B4"
]
},
{
"items": [
"C8",
"C9",
"C10"
]
}
]
}
I need this: [“A1″,”A2″,”A3″,”A4″,”B1″,”B2″,”B3″,”B4″,”C8″,”C9”,C10]
Is there any way to do this without using foreach loop, as my array will be so long and it will be time consuming.