"Fake pagination and VueJS" - pagination

I would like (for the moment) to implement what I call a fake pagination.
I have a table that is populated with a bunch of data. I get the whole data set with AJAX but the table is big.
My question is : How can I implement someting to display the first 10 items of my table then if I click on page 2 it is going to take the item from 11 to 21 and so on...
<!-- component template -->
<script type="text/x-template" id="grid-template">
<table>
<thead>
<tr>
<th v-for="key in columns"
#click="sortBy(key)"
:class="{ active: sortKey == key }">
{{ key | capitalize }}
<span class="arrow" :class="sortOrders[key] > 0 ? 'asc' : 'dsc'">
</span>
</th>
</tr>
</thead>
<tbody>
<tr v-for="entry in filteredData">
<td v-for="key in columns">
{{entry[key]}}
</td>
</tr>
</tbody>
</table>
</script>
<!-- demo root element -->
<div id="demo">
<form id="search">
Search <input name="query" v-model="searchQuery">
</form>
<demo-grid
:data="gridData"
:columns="gridColumns"
:filter-key="searchQuery">
</demo-grid>
</div>
// register the grid component
Vue.component('demo-grid', {
template: '#grid-template',
props: {
data: Array,
columns: Array,
filterKey: String
},
data: function () {
var sortOrders = {}
this.columns.forEach(function (key) {
sortOrders[key] = 1
})
return {
sortKey: '',
sortOrders: sortOrders
}
},
computed: {
filteredData: function () {
var sortKey = this.sortKey
var filterKey = this.filterKey && this.filterKey.toLowerCase()
var order = this.sortOrders[sortKey] || 1
var data = this.data
if (filterKey) {
data = data.filter(function (row) {
return Object.keys(row).some(function (key) {
return String(row[key]).toLowerCase().indexOf(filterKey) > -1
})
})
}
if (sortKey) {
data = data.slice().sort(function (a, b) {
a = a[sortKey]
b = b[sortKey]
return (a === b ? 0 : a > b ? 1 : -1) * order
})
}
return data
}
},
filters: {
capitalize: function (str) {
return str.charAt(0).toUpperCase() + str.slice(1)
}
},
methods: {
sortBy: function (key) {
this.sortKey = key
this.sortOrders[key] = this.sortOrders[key] * -1
}
}
})
// bootstrap the demo
var demo = new Vue({
el: '#demo',
data: {
searchQuery: '',
gridColumns: ['name', 'power'],
gridData: [
{ name: 'Chuck Norris', power: Infinity },
{ name: 'Bruce Lee', power: 9000 },
{ name: 'Jackie Chan', power: 7000 },
{ name: 'Jet Li', power: 8000 },
{ name: 'Jet Li', power: 8000 },
{ name: 'Jet Li', power: 8000 },
{ name: 'Jet Li', power: 8000 }, { name: 'Jet Li', power: 8000 }, { name: 'Jet Li', power: 8000 }, { name: 'Jet Li', power: 8000 }, { name: 'Jet Li', power: 8000 }, { name: 'Jet Li', power: 8000 }, { name: 'Jet Li', power: 8000 }, { name: 'Jet Li', power: 8000 }, { name: 'Jet Li', power: 8000 }, { name: 'Jet Li', power: 8000 }, { name: 'Jet Li', power: 8000 }, { name: 'Jet Li', power: 8000 }, { name: 'Jet Li', power: 8000 }, { name: 'Jet Li', power: 8000 }, { name: 'Jet Li', power: 8000 }, { name: 'Jet Li', power: 8000 }, { name: 'Jet Li', power: 8000 }, { name: 'Jet Li', power: 8000 }, { name: 'Jet Li', power: 8000 }, { name: 'Jet Li', power: 8000 }, { name: 'Jet Li', power: 8000 }, { name: 'Jet Li', power: 8000 }, { name: 'Jet Li', power: 8000 }, { name: 'Jet Li', power: 8000 }, { name: 'Jet Li', power: 8000 }, { name: 'Jet Li', power: 8000 }, { name: 'Jet Li', power: 8000 }, { name: 'Jet Li', power: 8000 }, { name: 'Jet Li', power: 8000 }, { name: 'Jet Li', power: 8000 }, { name: 'Jet Li', power: 8000 }, { name: 'Jet Li', power: 8000 }, { name: 'Jet Li', power: 8000 }, { name: 'Jet Li', power: 8000 },
]
}
})
https://jsfiddle.net/r89fy3vn/
Thank you

I would probably create a numeric property called page to pass to the component (first page = 0, etc.), and then change the component template to
<tr v-for="entry in filteredData.slice(page*10, 10)">
There's certainly some refinement to do with error checking the bounds of the page variable, etc., but this should be a good start.

Related

Trying to disable a button but an error popped up

I am making a help command, but I want to disable it when the embed title is the same as the button label. Except this error pops out:
C:\Users\admin\OneDrive\Documents\VSCode\JS\Discord
Bots\Testing3.JS\node_modules\discord.js\src\rest\RequestHandler.js:350
throw new DiscordAPIError(data, res.status, request);
^
DiscordAPIError: Invalid Form Body components[0]: The specified
component type is invalid in this context components[1]: The specified
component type is invalid in this context
at RequestHandler.execute (C:\Users\admin\OneDrive\Documents\VSCode\JS\Discord
Bots\Testing3.JS\node_modules\discord.js\src\rest\RequestHandler.js:350:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (C:\Users\admin\OneDrive\Documents\VSCode\JS\Discord
Bots\Testing3.JS\node_modules\discord.js\src\rest\RequestHandler.js:51:14)
at async MessageManager.edit (C:\Users\admin\OneDrive\Documents\VSCode\JS\Discord
Bots\Testing3.JS\node_modules\discord.js\src\managers\MessageManager.js:132:15)
{ method: 'patch', path:
'/channels/956427421073158194/messages/965228940685897748', code:
50035, httpStatus: 400, requestData: {
json: {
content: undefined,
tts: false,
nonce: undefined,
embeds: [
{
title: 'Economy',
type: 'rich',
description: null,
url: null,
timestamp: null,
color: null,
fields: [ [Object], [Object], [Object], [Object] ],
thumbnail: null,
image: null,
author: null,
footer: null
}
],
components: [
{
custom_id: 'econ',
disabled: true,
emoji: { animated: false, name: '💵', id: null },
label: 'Economy',
style: 1,
type: 2,
url: null
},
{
custom_id: 'info',
disabled: false,
emoji: { animated: false, name: '📃', id: null },
label: 'Info',
style: 2,
type: 2,
url: null
}
],
username: undefined,
avatar_url: undefined,
allowed_mentions: undefined,
flags: 0,
message_reference: undefined,
attachments: undefined,
sticker_ids: undefined
},
files: [] } }
Code:
if (cmd === "help") {
const econ = new Discord.MessageButton()
.setCustomId('econ')
.setEmoji('💵')
.setLabel('Economy')
.setStyle('PRIMARY')
const info = new Discord.MessageButton()
.setCustomId('info')
.setEmoji('📃')
.setLabel('Info')
.setStyle('SECONDARY')
const row = new Discord.MessageActionRow().addComponents([econ, info]);
let helpMsg = await message.channel.send({
embeds: [
{
title: "Economy",
fields: [
{
name: `\`${cPrefix}bal | balance [user]\``,
value: 'Displays your balance or a user\'s balance.'
},
{
name: `\`${cPrefix}dep | deposit <amount>\``,
value: 'Deposits a specified amount of cash to your bank.'
},
{
name: `\`${cPrefix}with | withdraw <amount>\``,
value: 'Withdraws a specified amount of cash to your wallet.'
},
{
name: `\`${cPrefix}addcoins <user> <amount>\``,
value: 'Adds a specified amount of cash to a user. (Administrator)'
}
]
}
],
components: [row]
});
const collector = helpMsg.createMessageComponentCollector({
componentType: 'BUTTON',
time: 60000
});
collector.on('collect', async (b) => {
if (b.user.id === message.author.id) {
if (b.customId === 'econ') {
helpMsg.edit({
embeds: [
{
title: "Economy",
fields: [
{
name: `\`${cPrefix}bal | balance [user]\``,
value: 'Displays your balance or a user\'s balance.'
},
{
name: `\`${cPrefix}dep | deposit <amount>\``,
value: 'Deposits a specified amount of cash to your bank.'
},
{
name: `\`${cPrefix}with | withdraw <amount>\``,
value: 'Withdraws a specified amount of cash to your wallet.'
},
{
name: `\`${cPrefix}addcoins <user> <amount>\``,
value: 'Adds a specified amount of cash to a user. (Administrator)'
}
]
},
],
components: [row.components[0].setDisabled(true), row.components[1].setDisabled(false)]
});
}
if (b.customId === 'info') {
helpMsg.edit({
embeds: [
{
title: "Info",
fields: [
{
name: `${cPrefix}info <user|server> <user: user>`,
value: 'Displays an info of the server or a user'
},
{
name: `${cPrefix}ping`,
value: 'Displays the current client ping and the database connection'
},
{
name: `${cPrefix}help`,
value: 'Umm... You used this command'
},
]
}
],
components: [row.components[0].setDisabled(false), row.components[1].setDisabled(true)]
})
}
} else {
b.reply({ content: 'These buttons are not for you.', ephemeral: true })
}
});
collector.on('end', async () => {
helpMsg.edit({ components: [row.components[0].setDisabled(true), row.components[1].setDisabled(true)] })
});
}
Is there anything wrong in this code?
You can create a new MessageActionRow and set everything to disabled. This code is from my bot's help command (discord.js v13.6.0):
let btnraw = new Discord.MessageActionRow().addComponents(
[
new Discord.MessageButton().setCustomId("home").setStyle("SUCCESS").setLabel("Home"),
new Discord.MessageButton().setCustomId("general").setStyle("PRIMARY").setLabel("General"),
new Discord.MessageButton().setCustomId("info").setStyle("PRIMARY").setLabel("Information"),
new Discord.MessageButton().setCustomId("mod").setStyle("PRIMARY").setLabel("Moderation"),
new Discord.MessageButton().setCustomId("fun").setStyle("PRIMARY").setLabel("Fun"),
]
);
let dbtnraw = new Discord.MessageActionRow().addComponents(
[
new Discord.MessageButton().setCustomId("d_home").setStyle("SUCCESS").setLabel("Home").setDisabled(true),
new Discord.MessageButton().setCustomId("d_general").setStyle("PRIMARY").setLabel("General").setDisabled(true),
new Discord.MessageButton().setCustomId("d_info").setStyle("PRIMARY").setLabel("Information").setDisabled(true),
new Discord.MessageButton().setCustomId("d_mod").setStyle("PRIMARY").setLabel("Moderation").setDisabled(true),
new Discord.MessageButton().setCustomId("d_fun").setStyle("PRIMARY").setLabel("Fun").setDisabled(true),
]
);
Then you can edit the message to replace the original row like this:
helpMsg.edit({components: [d_btnraw]});

How to pick out an array in a JSON response from spotify web API

I need to assign the genre field to a new array but I am not sure how to only get that field, or how to call that field
var SpotifyWebApi = require('spotify-web-api-node');
var spotifyApi = new SpotifyWebApi();
spotifyApi.setAccessToken('-----');
spotifyApi.searchArtists('artist:queen')
.then(function(data) {
console.log('Search tracks by "queen" in the artist name', data.body.artists.items);
}, function(err) {
console.log('Something went wrong!', err);
});
This is the terminal when calling it.
I only want the first response.
PS C:\Users\g\Documents\js> node spotifyTest
Search tracks by "queen" in the artist name [ { external_urls:
{ spotify: 'https://open.spotify.com/artist/1dfeR4HaWDbWqFHLkxsg1d' },
followers: { href: null, total: 19579534 },
genres: [ 'glam rock', 'rock' ],
href: 'https://api.spotify.com/v1/artists/1dfeR4HaWDbWqFHLkxsg1d',
id: '1dfeR4HaWDbWqFHLkxsg1d',
images: [ [Object], [Object], [Object], [Object] ],
name: 'Queen',
popularity: 90,
type: 'artist',
uri: 'spotify:artist:1dfeR4HaWDbWqFHLkxsg1d' },
{ external_urls:
{ spotify: 'https://open.spotify.com/artist/3nViOFa3kZW8OMSNOzwr98' },
followers: { href: null, total: 1087117 },
genres: [ 'deep pop r&b', 'pop', 'r&b' ],
href: 'https://api.spotify.com/v1/artists/3nViOFa3kZW8OMSNOzwr98',
id: '3nViOFa3kZW8OMSNOzwr98',
images: [ [Object], [Object], [Object] ],
name: 'Queen Naija',
popularity: 68,
type: 'artist',
uri: 'spotify:artist:3nViOFa3kZW8OMSNOzwr98' } ]
You can access a field in a JSON object using the dot notation. Here's an example of replacing the genres of the first response with a new array.
let responseItems = [
{ external_urls: { spotify: 'https://open.spotify.com/artist/1dfeR4HaWDbWqFHLkxsg1d' },
followers: { href: null, total: 19579534 },
genres: [ 'glam rock', 'rock' ],
href: 'https://api.spotify.com/v1/artists/1dfeR4HaWDbWqFHLkxsg1d',
id: '1dfeR4HaWDbWqFHLkxsg1d',
images: [ [Object], [Object], [Object], [Object] ],
name: 'Queen',
popularity: 90,
type: 'artist',
uri: 'spotify:artist:1dfeR4HaWDbWqFHLkxsg1d'
},
{
external_urls: { spotify: 'https://open.spotify.com/artist/3nViOFa3kZW8OMSNOzwr98' },
followers: { href: null, total: 1087117 },
genres: [ 'deep pop r&b', 'pop', 'r&b' ],
href: 'https://api.spotify.com/v1/artists/3nViOFa3kZW8OMSNOzwr98',
id: '3nViOFa3kZW8OMSNOzwr98',
images: [ [Object], [Object], [Object] ],
name: 'Queen Naija',
popularity: 68,
type: 'artist',
uri: 'spotify:artist:3nViOFa3kZW8OMSNOzwr98'
}
];
let firstResponse = responseItems[0];
console.log(JSON.stringify(firstResponse.genres, null, 2));
let newGenres = [ 'rock', 'jazz' ];
firstResponse.genres = newGenres;
console.log(JSON.stringify(firstResponse.genres, null, 2));
This should show the following in the console:
[
"glam rock",
"rock"
]
[
"rock",
"jazz"
]

How to get mac address of a Linux and Unix system using Nodejs

lib.mac = function () {
var macAddress = undefined;
Object.keys(ifaces).forEach(function (ifname) {
var alias = 0;
ifaces[ifname].forEach(function (iface) {
if ('IPv4' !== iface.family || iface.internal != false) {
// skip over internal (i.e. 127.0.0.1) and non-ipv4 addresses
return;
}
if (alias >= 1) {
// this single interface has multiple ipv4 addresses
macAddress = iface.mac;
} else {
// this interface has only one ipv4 adress
macAddress = iface.mac;
}
++alias;
});
});
return macAddress;
}
Above is my code for windows system, and I don't know how to get mac-address for Linux and Unix system.
If you do not want to use a third-party service you can use os module
require("os").networkInterfaces()
{ lo:
[ { address: '127.0.0.1',
netmask: '255.0.0.0',
family: 'IPv4',
mac: '00:00:00:00:00:00',
internal: true,
cidr: '127.0.0.1/8' },
{ address: '::1',
netmask: 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff',
family: 'IPv6',
mac: '00:00:00:00:00:00',
scopeid: 0,
internal: true,
cidr: '::1/128' } ],
enp0s31f6:
[ { address: '172.22.100.113',
netmask: '255.255.255.0',
family: 'IPv4',
mac: '8c:16:45:f0:8f:51',
internal: false,
cidr: '172.22.100.113/24' },
{ address: 'fe80:fe23:adaa:583d:123c',
netmask: 'ffff:ffff:ffff:ffff::',
family: 'IPv6',
mac: '8c:16:45:f0:8f:51',
scopeid: 2,
internal: false,
cidr: 'fe80::4dd7:aeee:583d:7c7c/64' } ],
...
You can use this lib getmac.
Eg.:
// Fetch the computer's mac address
require('getmac').getMac(function(err, macAddress){
if (err) throw err
console.log(macAddress)
});
Or just using the os module:
require("os").networkInterfaces();
{ lo:
[ { address: '127.0.0.1',
netmask: '255.0.0.0',
family: 'IPv4',
mac: '00:00:00:00:00:00',
internal: true,
cidr: '127.0.0.1/8' },
{ address: '::1',
netmask: 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff',
family: 'IPv6',
mac: '00:00:00:00:00:00',
scopeid: 0,
internal: true,
cidr: '::1/128' } ],
enp2s0:
[ { address: '192.168.1.10',
netmask: '255.255.254.0',
family: 'IPv4',
mac: '94:de:80:f0:ef:ef',
internal: false,
cidr: '192.168.4.144/23' },
{ address: 'fe80::ca45:44ac:89f4:85',
netmask: 'ffff:ffff:ffff:ffff::',
family: 'IPv6',
mac: '94:de:80:f0:ef:ef',
scopeid: 2,
internal: false,
cidr: 'fe80::ca45:44ac:89f4:85/64' }
],
}
https://nodejs.org/api/os.html#os_os_networkinterfaces
https://www.npmjs.com/package/getmac
Hope this helps!

fs.writeFileSync - write JSON to file always writes a empty object

i create a json-object and want to write this down to a json-file, but the object is always empty (?)
fs.writeFileSync(__dirname + '/myNewFile.json', JSON.stringify(myObjects));
the content of the written file is now []
fs.writeFileSync(__dirname + '/myNewFile.json', JSON.stringify({bla: myObjects}));
the content of the file is now {"bla":[]}
I doublecheck myObjects and it is not empty.. it is a array with some objects in it.
why is that? what am I doing wrong?
EDIT:
this is the content of myObjects:
[ struct: { id: 'struct',
name: 'Struktur',
icon: 'fa fa-bullseye',
properties: [] },
mp: { id: 'mp',
name: 'Messpunkt',
icon: 'fa fa-circle',
properties: [] },
'356899e5-d8b0-41aa-b7cd-de2135c5a3db': { id: '356899e5-d8b0-41aa-b7cd-de2135c5a3db',
name: 'Untermessung',
icon: 'fa fa-tachometer',
properties: [] },
'8d824cfd-584f-40e9-b9fa-78d7fedcc727': { id: '8d824cfd-584f-40e9-b9fa-78d7fedcc727',
name: 'Kommune',
icon: 'fa fa-thumb-tack',
properties: [] },
'2609b2ac-77aa-42f2-af22-d49fcfc6f0f0': { id: '2609b2ac-77aa-42f2-af22-d49fcfc6f0f0',
name: 'Bereiche',
icon: 'fa fa-circle',
properties: [] },
'a4ac2e52-da95-412f-b431-499f2eff64da': { id: 'a4ac2e52-da95-412f-b431-499f2eff64da',
name: 'Gebäude',
icon: 'fa fa-industry',
properties: [ [Object], [Object] ] } ]

get svg code in highchart directive with angular js

in normal highchart i get svg code with code like this
var chart = $('#container').highcharts()
svg = chart.getSVG();
So, how can i get svg code with this highchart directive in angular js???
i try like normal code but i didn't get svg code.
i use this directive for my highchart
https://github.com/rootux/angular-highcharts-directive
and this my code in controller.js
$scope.chartLogisticGIGR = {
options: {
tooltip: {
shared: true
}
},
xAxis: { // Primary xAxis
categories: $scope.nameMonths,
title: {
text: 'Month'
},
labels: {
enabled: true
},
min:0
},
yAxis: [{ // Primary yAxis
title: {
text: 'GI / GR in IDR'
},
labels: {
formatter: function () {
return Highcharts.numberFormat(this.value / 1000000,'0') + ' mil';
}
}
}, { // Secondary yAxis
title: {
text: 'Balance'
},
labels: {
formatter: function () {
return Highcharts.numberFormat(this.value / 1000000,'0') + ' mil';
}
},
}],
series: [{
name: 'AGP - Goods Receipt',
type: 'column',
stacking: 'normal',
stack: '1',
data: $scope.dataLogisticGIGR_AGP_GR,
color: $rootScope.getColor('AGP Ext'),
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}: {point.y:,.0f}</span><br/>'
}
},{
name: 'AGP - Goods Issue',
type: 'column',
stacking: 'normal',
stack: '1',
data: $scope.dataLogisticGIGR_AGP_GI,
color: $rootScope.getColor('AGP Int'),
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}: {point.y:,.0f}</span><br/>'
}
},{
name: 'AGP - Balance',
type: 'spline',
data: $scope.dataLogisticGIGR_AGP_Balance,
color: $rootScope.getColor('AI 2'),
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}: {point.y:,.0f}</span><br/>'
}
},{
name: 'AI - Goods Receipt',
type: 'column',
stacking: 'normal',
stack: '3',
data: $scope.dataLogisticGIGR_AI_GR,
color: $rootScope.getColor('AI'),
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}: {point.y:,.0f}</span><br/>'
}
},{
name: 'AI - Goods Issue',
type: 'column',
stacking: 'normal',
stack: '3',
data: $scope.dataLogisticGIGR_AI_GI,
color: $rootScope.getColor('AP 2'),
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}: {point.y:,.0f}</span><br/>'
}
},{
name: 'AI - Balance',
type: 'spline',
data: $scope.dataLogisticGIGR_AI_Balance,
color: $rootScope.getColor('AP'),
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}: {point.y:,.0f}</span><br/>'
}
}],
title: {
text: ''
},
loading: false
};
in this is my code in directive highchart
'use strict';
angular.module('chartsExample.directives',[])
.directive('chart', function () {
return {
restrict: 'E',
template: '<div></div>',
scope: {
chartData: "=value"
},
transclude:true,
replace: true,
link: function (scope, element, attrs) {
var chartsDefaults = {
chart: {
renderTo: element[0],
type: attrs.type || null,
height: attrs.height || null,
width: attrs.width || null
}
};
//Update when charts data changes
scope.$watch(function() { return scope.chartData; }, function(value) {
if(!value) return;
// We need deep copy in order to NOT override original chart object.
// This allows us to override chart data member and still the keep
// our original renderTo will be the same
var newSettings = {};
angular.extend(newSettings, chartsDefaults, scope.chartData);
var chart = new Highcharts.Chart(newSettings);
});
}
};
});
Thank's....

Resources