Can't $scope data after running method - javascript

I am building a small weather application, by using data from a weather API. I have to convert the temperature from kelvin to Celsius, and then use substring to get rid of all the decimals. However, sometimes the temperature is below 0 and even -10 Celsius, so i have to run through a for loop to make sure to get the same format every time (Max 1 decimal).
And now to my problem. I make an array that keeps all the temperatures in Celsius. Then i run through a loop to make sure to get the right format (-11.5, 1.9, 18.7....) Then i add it to a new array, and afterwards a json string. This whole thing works, but somehow i can't use $scope to send my data to the HTML file.
Any ideas of, what I am doing wrong?
success(function (data, status, headers, config) {
$scope.forecast = data;
//Creates array with temperatures
var arrayTemp = [
data.list[0].temp.day-273.15,
data.list[1].temp.day-273.15,
data.list[2].temp.day-273.15,
data.list[3].temp.day-273.15,
data.list[4].temp.day-273.15,
data.list[5].temp.day-273.15,
data.list[6].temp.day-273.15
];
//Function that takes array as parameter, and makes the right format
function add(array){
var newArray = [];
for (i = 0; i < array.length; i++) {
if (array[i] > 0) {
if (array[i] > 10) {
var res = array[i].toString().substring(0, 4)
} else {
var res = array[i].toString().substring(0, 3)
}
} else {
if (array[i] > -10) {
var res = array[i].toString().substring(0, 4)
} else {
var res = array[i].toString().substring(0, 5)
}
}
//Add data to new array
newArray.push(res);
}
//Creates json
var json = {"temps":{"one":newArray[0],"two":newArray[1],"three":newArray[2],"four":newArray[3],"five":newArray[4],"six":newArray[5],"seven":newArray[6]}};
return json;
}
var newJson = add(arrayTemp);
$scope.data = newJson;
}).

Related

Problem with creating multiple OBX segments in Mirth Connect

I have DB from where I'm getting my data of measurements. This is my code for looping through my measurements and adding them to OBX segments:
//getting MeasurementsData
var data = msg['measurements_measurement_data'].toString();
logger.info(data);
//inserting data in dictionary
var dictMeasurements = {};
for (var measurement in data) {
dictMeasurements[measurement] = data[measurement];
}
var dictSize = Object.keys(dictMeasurements).length;
var measureResult;
var measureType;
var counter = 1;
//Creating OBX measurements segments
while (counter <= dictSize) {
for (var key in dictMeasurements) {
//measure and result of measure
measureType = key;
measureResult = dictMeasurements[key];
createSegment('OBX', tmp, counter);
tmp['OBX'][counter]['OBX.1']['OBX.1.1'] = counter;
//ST-string or NM-numeric
tmp['OBX'][counter]['OBX.2']['OBX.2.1'] = isNumeric(measureResult);
tmp['OBX'][counter]['OBX.3']['OBX.3.1'] = ('ABI.' + measureType);
tmp['OBX'][counter]['OBX.3']['OBX.3.2'] = measureType;
tmp['OBX'][counter]['OBX.5']['OBX.5.1'] = measureResult;
tmp['OBX'][counter]['OBX.11']['OBX.11.1'] = 'F';
counter++;
}
}
If I run this code locally, it returns what I want (measurement type and its result), like:
cuffSizeArmLeft
1
cuffSizeArmRight
1
diaArmLeft
66
diaArmRight
66
But when I run it on MirthConnect chanel I get every letter from measure type in it's own column:
ST|ABI.0^0||{||||||F
OBX|2|ST|ABI.1^1||"||||||F
OBX|3|ST|ABI.2^2||c||||||F
OBX|4|ST|ABI.3^3||u||||||F
OBX|5|ST|ABI.4^4||f||||||F
OBX|6|ST|ABI.5^5||f||||||F
OBX|7|ST|ABI.6^6||S||||||F
OBX|8|ST|ABI.7^7||i||||||F
OBX|9|ST|ABI.8^8||z||||||F
OBX|10|ST|ABI.9^9||e||||||F
OBX|11|ST|ABI.10^10||A||||||F
OBX|12|ST|ABI.11^11||r||||||F
OBX|13|ST|ABI.12^12||m||||||F
OBX|14|ST|ABI.13^13||L||||||F
OBX|15|ST|ABI.14^14||e||||||F
OBX|16|ST|ABI.15^15||f||||||F
OBX|17|ST|ABI.16^16||t||||||F
OBX|18|ST|ABI.17^17||"||||||F
and my key in for loop is returning some numbers instead of measurement type, like it does locally.
This is similar question, but it didn't helped me.
Creating OBX segments from multiple DB rows
My another problem is that my function "isNumeric", is always returning a ST(string) instead a NM(numeric) type. Locally runs perfect.
function isNumeric(result) {
var reg = /^\d*\.?\d+$/;
if (typeof(result) == 'number') { return 'NM'; }
else { return 'ST'; }
}
console.log(isNumeric(140)); //return NM
console.log(isNumeric('test')); //return ST
Thanks for your help!

JavaScript array of dates and values

I am writing a function that takes an array of objects and parses the data into a date range. Right now I have the following:
function(result) {
var dates = [];
var data = [];
for (var i = 0; i < result.length; i++) {
var story = result[i];
var date = new Date(parseInt(story['UpdatedAt'].replace("/Date(", "").replace(")/", ""), 10));
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
var estimate = story['Estimate'];
if (estimate == null)
estimate = 0;
if (dates[date] == null) {
dates[date] = [date, 1, estimate];
data.push(dates[date]);
} else {
dates[date][1] += 1;
dates[date][2] += estimate;
data.push(dates[date]);
}
}
console.log(dates);
drawStoriesCompletedChart(data);
}
I have two arrays, one for dates and one for data. The result of this function is fed into the Google Charts API, which requires the data to be [[a,b,c], [a,b,c]]
The code above works thanks to the way Google Charts works, but I do know that since the data array is being pushed to every single loop iteration, there will be a bunch of duplicates without updated data.
What I want is take the data from each object and parse it so it is like the following:
[[Date, Total Stories, Total Estimate], [...]] and have nothing else in the object.

Total of different currencies from a json file

Currently working on an application which requires to display a set of values in different currencies. This is part of an application but everything I provide here should be enough as this is the main section I am working with. I have a json file which is read in and it is stored into an array called valuesArray, this array has all the information, such as the amount, currency, etc. With the currencies being sorted with highest first to the lowest on display like this:
EUR 500.00
USD 200.00
This is the code that I have created but it seems like this wouldn't be effective the more currencies I have. I've just put an array declaration above the function but just above this function is where I do all the json stuff and adding it into the array. $scope.valuesArray has data at this point.
$scope.valuesArray =[];
$scope.total = function()
{
var eur_total = 0;
var usd_total = 0;
if (typeof $scope.valuesArray != 'undefined')
{
var length = $scope.valuesArray.length;
for (var i = 0; i<length ; i++)
{
switch($scope.valuesArray[i].currency)
{
case "USD":
usd_total += parseFloat($scope.valuesArray[i].value);
break;
default:
eur_total += parseFloat($scope.valuesArray[i].value);
break;
}
}
}
var cost_total= [usd_total,eur_total];
total.sort(function(a, b){return b-a});
return format_to_decimal(total[0]) + "\x0A" + format_to_decimal(total[1]);
}
In my for loop I go through every single data in the array and break each currency down within the switch statement and finding the total amount of each currencies.
The last bit is kind of temporary as I couldn't figure out a different way of how to do it. I sort the totals for the currencies I have from the highest at the top.
I return the function with a function call for format_numeric_with_commas which gives me the value in proper currency format and this displays the value. Will update this and add that code when I get to it. But I have used the indexes as a rough logic to show what I want to get out of it. So in this case, total[0] should be 500.00 and total[1] should be 200.00.
On top of this I want to be able to display the currency type for each. So like the example above.
You can try to save all the calculations in the array with currency index.
$scope.valuesArray = [];
$scope.total = function () {
var totalsArray = [];
if (typeof $scope.valuesArray != 'undefined') {
var length = $scope.valuesArray.length
for (var i = 0; i < length; i++) {
if (!totalsArray[$scope.valuesArray[i].currency]) {
totalsArray[$scope.valuesArray[i].currency] = 0;
}
totalsArray[$scope.valuesArray[i].currency] += $scope.valuesArray[i].value;
}
}
var cost_total = [];
for (var k in totalsArray) {
cost_total.push(currency:k,value:totalsArray[k]);
}
cost_total.sort(function (a, b) {
return b.value - a.value
});
return format_to_decimal(cost_total[0].value)+cost_total[0].currency + "\x0A" + format_to_decimal(cost_total[1].value);

Store coordinates from prompt and calculate the distance

I work on distance calculation between coordinates and I built something which works fine.
var pointsCoordinates = [[5,7],[5,8],[2,8],[2,10]];
function lineDistance(points) {
var globalDistance = 0;
for(var i=0; i<points.length-1; i++) {
globalDistance += Math.sqrt(Math.pow( points[i+1][0]-points[i][0] , 2 ) + Math.pow( points[i+1][1]-points[i][1] , 2 ));
}
return globalDistance;
}
console.log(lineDistance(pointsCoordinates));
I would like to improve it a little bit and send a prompt to store coordinates sent by users.
example:
alert(prompt("send me random coordinates in this format [,] and I will calculate the distance))
I would like to store theses coordinates and calculate the distance with my function which works.
I know I have to use push but it doesn't works, someone can help me to write it? I know it's simple but... I can't do it.
Thank you very much
Working and tested code. Take coordinates from the prompt and pass it to the lineDistance function and convert passed string into array.
function lineDistance(points) {
var globalDistance = 0;
var points = JSON.parse(points); // convert entered string to array
for(var i=0; i<points.length-1; i++) {
globalDistance += Math.sqrt(Math.pow( points[i+1][0]-points[i][0] , 2 ) + Math.pow( points[i+1][1]-points[i][1] , 2 ));
}
return globalDistance;
}
var pointsCoordinates = prompt("send me random coordinates in this format [,] and I will calculate the distance");
if (coordinates != null)
console.log(lineDistance(coordinates)); //[[5,7],[5,8],[2,8],[2,10]]
else
alert("Entered value is null");
Hope this will help you.
var userPrompt = prompt("send me random coordinates");// e.g [100,2] [3,45] [51,6]
var pointsCoordinates = parseCoordinates(userPrompt);
function parseCoordinates(unparsedCoord) {
var arr = unparsedCoord.split(" ");
var pair;
for (var i = 0; i < arr.length; i++) {
pair = arr[i];
arr[i] = pair.substr(1, pair.length - 2).split(",")
}
return arr;
}
function lineDistance(points) {
var globalDistance = 0;
for(var i = 0; i < points.length - 1; i++) {
globalDistance += Math.sqrt(Math.pow(points[i + 1][0] - points[i][0], 2) + Math.pow(points[i+1][1]-points[i][1], 2));
}
return globalDistance;
}
console.log(pointsCoordinates);
console.log(lineDistance(pointsCoordinates));
If you use prompt you don't need to also wrap it with alert.
Also, prompt will return with a string value, so you'll need to parse the data you're getting back (unless you're fine with a string)
In this case, since you want to get back an array of points, parsing can be a more complicated than just converting values. My recommendation is to use JSON.parse() to parse the input array
In your case you could use this code
var coordString = prompt("send me random coordinates in this format [,] and I will calculate the distance");
try {
var coordinates = JSON.parse(coordString);
// now check that coordinates are an array
if ( coordinates.constructor === Array ) {
// this might still fail if the input array isn't made of numbers
// in case of error it will still be caught by catch
console.log(lineDistance(coordinates));
}
} catch(error) {
// if something goes wrong you get here
alert('An error occurred: ' + error);
}
I recommend reading the MDN docs for prompt() if you want to know what else you can do with them.
Also, the docs for JSON.parse() can be useful if you want to parse values from a text string.

How to get the total number of rows with particular value in json file in d3.js

I have a JSON file which I am using for visualization using d3.js. I want to get the count of total rows for a particular code. I am using the following for doing so:
data.keys(d.code).length
But its not working. How can I solve this?
I have found one idea but it is not showing correct values. Whats the wrong with it?
Object.keys(d.code).length
I have a JSON file with following sample data
[
{"name":"a","code":20},
{"name":"b","code":20},
{"name":"c","code":20},
{"name":"d","code":21}
]
My target is to get the count of data with same code. For example for code 20 I should get 3 as output.
You might as well use d3.nest() to group your data based on code and have it return the number of entries per group:
var json = [
{"name":"a","code":20},
{"name":"b","code":20},
{"name":"c","code":20},
{"name":"d","code":21}
];
var nest = d3.nest()
.key(function(d) { return d.code; })
.rollup(function(values) { return values.length; })
.entries(json);
You don't need D3.js for this. Simple JavaScript should do it. Something like:
total = data.reduce(function(count, entry) {
return count + (entry.code === 20 ? 1 : 0);
}, 0);
Obviously, you can convert it to a function to handle arbitrary values other than 20.
var count = 0;
var length = data.length;
for (var x = 0; x < length; x++)
{
if (data[x].code == 20)
count++;
}
console.log('Final count: ' + count);
Probably something like that.
If you want a function you could use this:
var getCount = function(data, val)
{
var count = 0;
var length = data.length;
for (var x = 0; x < length; x++)
{
if (data[x].code == val)
count++;
}
return count;
}
Then call it like this:
var count = getCount(data, 20); // should return 3

Categories