I am searching for a value of yes in the field hhead of an object returned from server:
Object.keys(this.data).forEach(key => {
if (this.data[key].hhead === 'yes') {
console.log('Yes '+(this.data[key].hhead === 'yes'))
this.snackBar.open('This household already have ' + this.data[key].far + ' ' + this.data[key].lar + ' (id: ' + this.data[key].iid + ' ) as a head of household', 'Close', {
panelClass: 'error'
});
}
else {
console.log('No '+(this.data[key].hhead === 'no'))
if (data['age'] <= 17 && data['age'] < this.maxAge && (selectedFr == "Head Of Household")) {
let message = 'This individual is not the oldest in his family to be the head of household. Do you want to complete this action ?';
this.openDialog(message, updateType, ind_id, newSts, newMs, newFr, newHH, oldHH, missingData);
}
}
});
The problem with this script is that both if and else are true. So both scripts will run.
The reason is that, at the first condition, once it finds a yes value, the condition turn true.
And the second, once it finds no it will run.
The array is like:
So what I need is if an array only contains no in all rows, to run the else part. And if it found at least yes to run the first condition.
I think you are trying to attack the problem from the wrong angle. You have to scan the collection first and then run your code:
var mached = this.data.every(t => t.hhead == 'yes'); //this will print true
Object.keys(this.data).forEach(key => {
if (mached) {
console.log('Yes '+(this.data[key].hhead === 'yes'))
this.snackBar.open('This household already have ' + this.data[key].far + ' ' + this.data[key].lar + ' (id: ' + this.data[key].iid + ' ) as a head of household', 'Close', {
panelClass: 'error'
});
} else {
console.log('No '+(this.data[key].hhead === 'no'))
if (data['age'] <= 17 && data['age'] < this.maxAge && (selectedFr == "Head Of Household")) {
let message = 'This individual is not the oldest in his family to be the head of household. Do you want to complete this action ?';
this.openDialog(message, updateType, ind_id, newSts, newMs, newFr, newHH, oldHH, missingData);
}
}
});
Related
I'm trying to code a bot command using discord.js and Minecraft-server-util but my code is not using the const I defined and is saying it does not exist. If you spot any other problems you can correct me on them.
client.on('message', message => {
if (message.content === `${prefix}javaserverstatus`) {
const args = message.content.slice(prefix.length).trim().split(' '); // this is where args is defined.
if (!args.length) {
return message.channel.send(`You didn't provide a server, ${message.author}!`); // checks if args exist
}
if (args.length > 1) {
return message.channel.send(`Wrong input! EG. play.hypixel.net, ${message.author}`); // checks if there are only 1 arguments
}
}
const util = require('minecraft-server-util');
var serverinfo = null
util.status(args) // This code is giving an error saying args does not exist.
.then((response) => {
console.log(response);
serverinfo = response;
const embed = new Discord.MessageEmbed()
.setTitle('play.hypixel.net Server Status')
.setColor(0xff0000)
.setDescription('IP: ' + response.host + '\n' + 'Port: ' + response.port + '\n' + 'Version: ' + response.version + '\n' + 'Online Players: ' + response.onlinePlayers.toString() + '\n' + 'Max Players: ' + response.maxPlayers.toString() + '\n');
message.channel.send(embed);
})
.catch((error) => {
console.error(error);
});
});
The error is due to the scope that you've defined args in.
args is defined in your first if statement when it should be defined a line above.
const args = message.content.slice(prefix.length).trim().split(' ');
if (message.content === `${prefix}javaserverstatus`) {
// this is where args is defined.
if (!args.length) {
return message.channel.send(`You didn't provide a server, ${message.author}!`); // checks if args exist
}
if (args.length > 1) {
return message.channel.send(`Wrong input! EG. play.hypixel.net, ${message.author}`); // checks if there are only 1 arguments
}
}
You've defined args in a if statement. You need to put it out of there.
client.on('message', (message) => {
const args = message.content.slice(prefix.length).trim().split(' ') // this is where args is defined.
if (message.content === `${prefix}javaserverstatus`) {
if (!args.length) {
return message.channel.send(`You didn't provide a server, ${message.author}!`) // checks if args exist
}
if (args.length > 1) {
return message.channel.send(`Wrong input! EG. play.hypixel.net, ${message.author}`) // checks if there are only 1 arguments
}
}
const util = require('minecraft-server-util')
var serverinfo = null
util
.status(args) // This code is giving an error saying args does not exist.
.then((response) => {
console.log(response)
serverinfo = response
const embed = new Discord.MessageEmbed()
.setTitle('play.hypixel.net Server Status')
.setColor(0xff0000)
.setDescription('IP: ' + response.host + '\n' + 'Port: ' + response.port + '\n' + 'Version: ' + response.version + '\n' + 'Online Players: ' + response.onlinePlayers.toString() + '\n' + 'Max Players: ' + response.maxPlayers.toString() + '\n')
message.channel.send(embed)
})
.catch((error) => {
console.error(error)
})
})
If this isn't working, pls send me the command you sent in the discord chat.
I try get value from ionic storage, but it's doesn't work here. Why GET2 execute before storage.get ? My brain is broken, help please.
public storageGet(key: string){
var uid = 0;
this.storage.get(key).then((val) => {
console.log('GET1: ' + key + ': ' + val);
if (val != null) { uid = val;}
});
console.log('GET2: ' + key + ': ' + uid);
return uid;
}
Return:
GET2: uid: 0
GET1: uid: 1
You need to understand how promise works.
This code is asynchronous, all lines in the then callback will be execute, but you can't decide when.
The console.log("GET2") is executed strictly after the storage.get, this part is synchronous.
I am developing an application with local notifications with values coming from the database. However, it is repeating the notification with the same value countless times until changing to another.
Example:
1st - "The invoice of house #1 will expire"
2nd - "The invoice of house #1 will expire"
3rd - "The invoice of house #2 will expire"
Any idea what that might be and how to fix it?
calculateDif(idHouse, dateBill) {
let billDate= moment(dateBill);
var MyDate = new Date();
var MyDateString;
MyDateString = MyDate.getFullYear() + '-' + ('0' + (MyDate.getMonth()+1)).slice(-2)
+ '-' + ('0' + MyDate.getDate()).slice(-2);
let warningDate= billDate.diff(MyDateString, 'days');
if (warningDate <= 5) {
this.localNotifications.schedule({
id: 1,
text: 'The invoice of house ' idHouse + ' will expire',
sound: null,
data: { secret: 1 }
});
}
}
I think the problem is in the function that execute calculateDif();
You can also create an array of your articles that you have already notified, for example notifiedHouses = []
and check if the id is already notified using .some
calculateDif(idHouse, dateBill) {
let billDate= moment(dateBill);
var MyDate = new Date();
var MyDateString;
MyDateString = MyDate.getFullYear() + '-' + ('0' + (MyDate.getMonth()+1)).slice(-2)
+ '-' + ('0' + MyDate.getDate()).slice(-2);
let warningDate= billDate.diff(MyDateString, 'days');
if (warningDate <= 5 && !this.notifiedHouses.some( item => item.idHouse === idHouse )) {
this.localNotifications.schedule({
id: 1,
text: 'The invoice of house ' idHouse + ' will expire',
sound: null,
data: { secret: 1 }
});
const house = {idHouse: idHouse}
this.notifiedHouses.push(house);
}
}
I have my angularjs project, in this I have this code block, which is fired depending upon the dropdown selection. In this code the if and else part is mostly similar, I want to refactor the code so that the code is not repeated.
if (1 === $scope.form.type) {
response = $scope.resource.searchItemSalesInfo(params.get, params.post,function(response, headers) {
angular.forEach(response, function(row, id) {
response[id].prod_info = row.alias + ' (' + row.final_product_id + ') ';
});
$scope.totalCount = headers('x-total-count');
});
} else {
response = $scope.resource.searchOrderSalesInfo(params.get, params.post,function(response, headers) {
angular.forEach(response, function(row, id) {
response[id].prod_info = row.alias + ' (' + row.final_product_id + ') ';
});
$scope.totalCount = headers('x-total-count');
});
}
I tried to take the common functionality out in the below manner, but then the code does not works, and it breaks the functionality.
$scope.callresource = function(resourcename){
response = $scope.resource.resourcename(params.get, params.post,function(response, headers) {
angular.forEach(response, function(row, id) {
response[id].prod_info = row.alias + ' (' + row.final_product_id + ') ';
});
$scope.totalCount = headers('x-total-count');
});
}
if (1 === $scope.form.type) {
$scope.callresource(searchItemSalesInfo);
} else {
$scope.callresource(searchOrderSalesInfo);
}
Alternatively to my other reply, you could pass a reference to the function that you want to be executed in $scope.callresource ... in other words a callback function
I believe this is the more scalable approach.
$scope.callresource = function(resourceCallbackFunction){
response = resourceCallbackFunction(params.get, params.post,function(response, headers) {
angular.forEach(response, function(row, id) {
response[id].prod_info = row.alias + ' (' + row.final_product_id + ') ';
});
$scope.totalCount = headers('x-total-count');
});
}
if (1 === $scope.form.type) {
$scope.callresource($scope.resource.searchItemSalesInfo);
} else {
$scope.callresource($scope.resource.searchOrderSalesInfo);
}
You can't call the function using this syntax $scope.resource.resourcename because this syntax is telling JS to execute a function called resourcename.
Instead, try using the bracket notation:
$scope.resource[resourcename](..)
Also, when invoking the $scope.callresource function, pass the arguments as strings, because searchItemSalesInfo and searchOrderSalesInfo currently JS is trying to find them as variables.
$scope.callresource('searchItemSalesInfo');
Your code would look like this:
$scope.callresource = function(resourcename){
response = $scope.resource[resourcename](params.get, params.post,function(response, headers) {
angular.forEach(response, function(row, id) {
response[id].prod_info = row.alias + ' (' + row.final_product_id + ') ';
});
$scope.totalCount = headers('x-total-count');
});
}
if (1 === $scope.form.type) {
$scope.callresource('searchItemSalesInfo');
} else {
$scope.callresource('searchOrderSalesInfo');
}
I'm retrieving data with http.get.
This provides me with an array of objects like below:
[{
"id”:12345,
"resource_state":2,
"external_id”:”abscdgrft”,
"upload_id”:1234567,
"athlete":{
"id”:123456,
"resource_state":2,
"firstname”:”testname”,
"lastname”:”testlastname”,
"profile_medium”:”image/athlete/medium.png",
"profile":"image/athlete/large.png",
"city”:”testcity”,
"state”:”teststate”,
…
},
"name”:”test name“,
"distance":87223.1,
"moving_time":11026,
"elapsed_time":11173,
"total_elevation_gain":682.3,
…
}]
I would like to combine all those object based on the athlete.firstname + athlete.lastname.
So for example all objects with athlete first name Jim and last name Donalds I want to be combined in one object, the same goes for all the other names.
When combining the objects based on the full name, values like "distance", "moving_time", "elapsed_time" and "total_elevation_gain" needs to be summed.
I tried using the code below but the problem is that I can't get it to work with multiple values like I mention above.
This is working only with one value, distance for example:
var obj = {}; // Initialize the object
angular.forEach(data, function(value, key) {
if (value.start_date > firstdayOfWeek && value.start_date < lastdayOfWeek) {
if (obj[value.athlete.firstname + ' ' + value.athlete.lastname]) { // If already exists
obj[value.athlete.firstname + ' ' + value.athlete.lastname] += value.distance; // Add value to previous value
} else {
obj[value.athlete.firstname + ' ' + value.athlete.lastname] = value.distance; // Add in object
}
} else {
//do nothing
}
});
console.log(obj); // Result
When I modify it like this it is not working anymore.
var obj = {};
angular.forEach(data, function(value, key) {
//console.log(value);
if (value.start_date > startOfLastWeek && value.start_date < endOfLastWeek) {
//console.log(value);
if (obj[value.athlete.firstname + ' ' + value.athlete.lastname]) { // If already exists
obj[value.athlete.firstname + ' ' + value.athlete.lastname] += {
"profile" : value.athlete.profile,
"distance" : value.distance,
"moving_time" : value.moving_time,
"elapsed_time" : value.elapsed_time,
"total_elevation_gain" : value.total_elevation_gain,
}; // Add value to previous value
} else {
obj[value.athlete.firstname + ' ' + value.athlete.lastname] = {
"profile" : value.athlete.profile,
"distance" : value.distance,
"moving_time" : value.moving_time,
"elapsed_time" : value.elapsed_time,
"total_elevation_gain" : value.total_elevation_gain,
}; // Add in object
}
} else {
//do nothing
}
});
console.log(obj); // Result
Thanks!
try to add item by item... You can't add all with += { ... }:
var obj = {};
angular.forEach(data, function(value, key) {
//console.log(value);
if (value.start_date > startOfLastWeek && value.start_date < endOfLastWeek) {
//console.log(value);
if (obj[value.athlete.firstname + ' ' + value.athlete.lastname]) { // If already exists
var aux = obj[value.athlete.firstname + ' ' + value.athlete.lastname];
aux.profile += value.athlete.profile;
aux.distance += value.distance;
...
} else {
obj[value.athlete.firstname + ' ' + value.athlete.lastname] = {
"profile" : value.athlete.profile,
"distance" : value.distance,
"moving_time" : value.moving_time,
"elapsed_time" : value.elapsed_time,
"total_elevation_gain" : value.total_elevation_gain,
}; // Add in object
}
} else {
//do nothing
}
});
console.log(obj); // Result
Use underscore or lodash groupBy, map and reduce
with lodash:
_.chain(myArr).map(function(o) {
return {
fullname: o.athlete.firstname + ' ' + o.athlete.lastname,
distance: o.distance,
moving_time: o.moving_time,
elapsed_time: o.elapsed_time,
total_elevation_gain: o.total_elevation_gain
}
}).groupBy(function(o) {
return o.fullaname
}).map(function(d, fullname) {
var totals = _.reduce(d, function(result, run, n) {
result.moving_time += run.moving_time | 0
result.elapsed_time += run.elapsed_time | 0
result.total_elevation_gain += run.total_elevation_gain | 0
return result
}, {
moving_time: 0,
elapsed_time: 0,
total_elevation_gain: 0
})
totals.fullname = fullname
return totals
})