Move coordinates from json to link (js) - javascript

I have js code to get data from back endю
Here is code:
var speeddata = [];
function getSpeedData() {
var googleurl =
"https://roads.googleapis.com/v1/speedLimits?path=50.72389,3.32214|51.72389,3.32214&key=8IAceOk43NpWKpczMAzN5dVosUI=";
$.getJSON(googleurl, function (data, status) {
speedlimits = data;
console.log(speedlimits);
});
var url = $('#getData').data('request-url');
$.getJSON(url,
function (data) {
speeddata = data;
console.log(speeddata);
});
}
Here is what I get
I need to push those coordinates to url to this segment path=50.72389,3.32214|51.72389,3.32214
How I can do this, via js?

You can try this:
var speeddata = [{Latitude2: 51.72389,Longitude2: 3.32214, Speed: 41},{Latitude2: 51.72389,Longitude2: 3.32214, Speed: 41}];
var args = 'yourpath = ';
for(var i=0; i < speeddata.length; i++){
args += speeddata[i].Latitude2 + ',' + speeddata[i].Longitude2;
if(speeddata.length == (i+1)){
break;
}else{
args += '|';
}
}
console.log(args);

Related

TypeError: Cannot find function forEach in object in Google App Script

I keep running to Cannot find function for each in object error while trying to loop entries. Is there something I am not seeing?. Here the code. This code is supposed to fetch time data from a system via API do calculations and send email
function getTime() {
var range = [5323, 9626, 4998];
var user = [];
for (var i = 0; i < range.length; i++) {
var auth = 'token'
var from = '2020-01-08'
var to = '2020-01-09'
var url = 'https://api.10000ft.com/api/v1/users/' + range[i] + '/time_entries?from=' + from + '&to=' + to + '&auth=' + auth;
var options = {
method: 'get',
headers: {
Authorization: 'Bearer ' + auth
}
};
var submitted_time_entries = {};
var response = UrlFetchApp.fetch(url, options);
var response = JSON.parse(response.getContentText());
var time_entries = response.data;
time_entries.forEach(function (time_entry) {
if (time_entry.user_id in submitted_time_entries) {
submitted_time_entries[time_entry.user_id] += time_entry.hours;
} else {
submitted_time_entries[time_entry.user_id] = time_entry.hours;
}
});
submitted_time_entries.forEach(function (user_id) {
if (submitted_time_entries[user_id] < 3) {
//send mail
}
});
}
}
response.data is probably not the array you expect. The server may be returning an error or a successful response that isn't parseable as an array. To find out, print response.data to the console and confirm it's the array you expect.
Seems my API returned an object. I figured out the way around it by using Object.keys method and it worked. Here is the working code.
function getTime() {
var range = [53, 926, 8098];
var user = [];
for (var i = 0; i < range.length; i++) {
var auth = 'token';
var from = '2020-01-08'
var to = '2020-01-09'
var url = 'https://api.10000ft.com/api/v1/users/' + '449625' + '/time_entries?from=' + from + '&to=' + to + '&auth=' + auth;
var options = {
method: 'get',
headers: {
Authorization: 'Bearer ' + auth
}
};
var submitted_time_entries = {};
var response = UrlFetchApp.fetch(url, options);
var response = JSON.parse(response.getContentText());
var time_entries = response.data;
Object.keys(time_entries).forEach(function (time_entry) {
if (time_entry.user_id in submitted_time_entries) {
submitted_time_entries[time_entry.user_id] += time_entry.hours;
} else {
submitted_time_entries[time_entry.user_id] = time_entry.hours;
}
});
Object.keys(submitted_time_entries).forEach(function (user_id) {
if (submitted_time_entries[user_id] < 3) {
Logger.log(time_entry)
//send mail
}
});
}
}

split json into carousel cards

I get the results from a JSON file and I want to display it in carousel,
how can I do it?
Here is the code:
var req = http.request(options, function (res) {
console.log('STATUS: ' + res.statusCode);
if (res.statusCode !== 201) {
session.send("Sorry, service is not reachable at the moment, please try again later");
}
//session.send(res.statusCode.toString());
var chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk);
var json = chunk.toString();
var graph = JSON.parse(json);
var attachmentList = [];
for (var i = 0; i < graph.clauses.length; i++) {
var obj = graph.clauses[i];
console.log(obj);
var clause_id;
var clause_text;
for (var key in obj) {
clause_id = key;
clause_text = obj[key].toString();
// session.send(clause_id+"<br>"+clause_text);
}
let card = new botbuilder_1.HeroCard(session)
.title(clause_id)
.subtitle(clause_text)
.buttons([botbuilder_1.CardAction.imBack(session, 'Mark as Relevant', 'Mark as Relevant')]);
let msg = new botbuilder_1.Message(session);
msg.attachmentLayout(botbuilder_1.AttachmentLayout.carousel);
msg.attachments([card]);
session.send(msg);
// session.endDialog(msg);
}
});
});
Here is the screenshot of the results:
You're sending a message on each iteration of the for loop, and each message only has one attachment. Try sending one message after the for loop and give that message the whole list of attachments.
var attachmentList = [];
for (var i = 0; i < graph.clauses.length; i++) {
var obj = graph.clauses[i];
console.log(obj);
var clause_id;
var clause_text;
for (var key in obj) {
clause_id = key;
clause_text = obj[key].toString();
// session.send(clause_id+"<br>"+clause_text);
}
let card = new botbuilder_1.HeroCard(session)
.title(clause_id)
.subtitle(clause_text)
.buttons([botbuilder_1.CardAction.imBack(session, 'Mark as Relevant', 'Mark as Relevant')]);
attachmentList.push(card);
}
let msg = new botbuilder_1.Message(session);
msg.attachmentLayout(botbuilder_1.AttachmentLayout.carousel);
msg.attachments(attachmentList);
session.send(msg);

Count how many times i have the same word

My variable tag returns one of these 4 different values: assistance, bug, evolution or maintenance. I would like to count how many times I have each of those words. I would like to display how many times I have each of those item in my console first. I really don't know how to do that. Here is my code :
function displaytickets(y){
$.ajax({
url: "https://cubber.zendesk.com/api/v2/users/" + y + "/tickets/requested.json?per_page=150",
type: 'GET',
dataType: 'json',
cors: true ,
contentType: 'application/json',
secure: true,
beforeSend: function(xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa(""));
},
success: function(data) {
var sortbydate = data.tickets.sort(function(a, b){
return new Date(b.created_at) - new Date(a.created_at);
});
var ids = $.map(data.tickets, function (data) {
return data.id;
})
localStorage.setItem("mesid", ids);
for (i = 0; i < data.tickets.length; i++) {
var myticket = data.tickets[i];
var mydate = data.tickets[i].created_at;
var created = moment(mydate).format("MM-DD-YY");
var mytitle = data.tickets[i].subject;
var description = data.tickets[i].description;
var status = data.tickets[i].status;
var tag = data.tickets[i].tags[0];
console.log(tag);
var myid = data.tickets[i].id;
}
var nbticket = data.tickets.length;
$("#name").append('<h2 class="title">' + " " + nbticket + " ticket(s)" + '</h2>');
},
});
}
Here's what I get from the console for the console.log(tag):
You can achieve this by using an object to store the occurrence count, keyed by the string itself. Try this:
var occurrences = {};
Then in your success handler you can add and increment the tags as you find them:
success: function(data) {
// your code here...
for (i = 0; i < data.tickets.length; i++) {
// your code here...
var tag = data.tickets[i].tags[0];
if (occurrences.hasOwnProperty(tag)) {
occurrences[tag]++;
} else {
occurrences[tag] = 1;
}
}
console.log(occurrences);
},
Working example
Did you try to count it in your for loop ?
var maintenance_counter = 0;
for (i = 0; i < data.tickets.length; i++) {
var myticket = data.tickets[i];
var mydate = data.tickets[i].created_at;
var created = moment(mydate).format("MM-DD-YY");
var mytitle = data.tickets[i].subject;
var description = data.tickets[i].description;
var status = data.tickets[i].status;
var tag = data.tickets[i].tags[0];
var myid = data.tickets[i].id;
if( tag == "maintenance" ){
maintenance_counter++;
}
}
alert("Total maintenance occurrence:"+ maintenance_counter);
Create an object to hold your tag result count, similar to this:
var tagCount = {};
for (i = 0; i < data.tickets.length; i++) {
var tag = data.tickets[i].tags[0];
if (tagCount[tag] === undefined) {
tagCount[tag] = 1;
} else {
tagCount[tag] += 1;
}
}
console.log(tagCount);

'Juggling Async' - Why does my solution not return anything at all?

After asking a question and getting a very helpful answer on what the 'Async Juggling' assignment in learnyounode was asking me to do, I set out to implement it myself.
The problem is, my setup isn't having any success! Even though I've referred to other solutions out there, my setup simply isn't returning any results when I do a learnyounode verify myscript.js.
GIST: jugglingAsync.js
var http = require('http');
var app = (function () {
// Private variables...
var responsesRemaining,
urls = [],
responses = [];
var displayResponses = function() {
for(var iterator in responses) {
console.log(responses[iterator]);
}
};
// Public scope...
var pub = {};
pub.main = function (args) {
responsesRemaining = args.length - 2;
// For every argument, push a URL and prep a response.
for(var i = 2; i < args.length; i++) {
urls.push(args[i]);
responses.push('');
}
// For every URL, set off an async request.
for(var iterator in urls) {
var i = iterator;
var url = urls[i];
http.get(url, function(response) {
response.setEncoding('utf8');
response.on('data', function(data) {
if(response.headers.host == url)
responses[i] += data;
});
response.on('end', function() {
if(--responsesRemaining == 0)
displayResponses();
});
});
}
};
return pub;
})();
app.main(process.argv);
Question: What am I doing wrong?
This line
for(var iterator in urls) {
doesn't do what you think it does. It actually loops over the properties of urls (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in). Instead, you have to do something like
for(var i = 0; i < urls.length; i++) {
var url = urls[i];
...
}
or
urls.forEach(function(url, index) {
...
});
In addition to not properly looping through the arrays inside the app module, I was also not properly concatenating data returned from the response.on('data') event. Originally I was doing...
responses[index] += data;
Instead, the correct thing to do was:
responses[index] = responses[index] + data;
Changing that, as well as the things noted by #arghbleargh got the 'Async Juggling' to fully verify!
I have tested my code and it all worked:
~ $ node juggling_async.js site1 site2 site3 site4 ...
The JS code does not limit only to three sites.
var http = require('http');
// Process all the site-names from the arguments and store them in sites[].
// This way does not limit the count to only 3 sites.
var sites = [];
(function loadSites() {
for(var i = 2, len = process.argv.length; i < len; ++i) {
var site = process.argv[i];
if(site.substr(0, 6) != 'http://') site = 'http://' + site;
sites.push(site);
}
})();
var home_pages = [];
var count = 0;
function httpGet(index) {
var home_page = '';
var site = sites[index];
http.get(site, function(res) {
res.setEncoding('utf8');
res.on('data', function(data) {
home_page += data;
});
res.on('end', function() {
++count;
home_pages[index] = home_page;
if(count == sites.length) {
// Yahoo! We have reached the last one.
for(var i = 0; i < sites.length; ++i) {
console.log('\n############ Site #' + (+i+1) + ': ' + sites[i]);
console.log(home_pages[i]);
console.log('============================================\n');
}
}
});
})
.on('error', function(e) {
console.log('Error at loop index ' + inddex + ': ' + e.message);
})
;
}
for(var i = 0; i < sites.length; ++i) {
httpGet(i);
}

Synchronous javascript does not work

I have a script which generates an array of audio files to be played on the click of a button. I am trying to use synchronous JS in order to change the values of some global variables and have been testing for changes with alerts but I get 'undefined' as a result (or my popups do not show).
My code:
jQuery.ajaxSetup({async:false});
var s;
var group;
var curr_rec;
var curr_start = 1;
var curr_end;
var curr_s_obj;
var recs;
var sync = new Array();
var sync_group = new Array();
var check_rec;
var check_id;
var check_start;
var check_end;
var loaded = 0;
var s_obj;
function compare(a,b){
if(a.fields.start_time<b.fields.start_time)
return -1;
if(a.fields.start_time>b.fields.start_time)
return 1;
return 0;
}
function process_data(recs){
for(var i=0;i<recs.length;i++){
check_rec = recs[i];
check_id = check_rec.fields.file_ID;
check_start = check_rec.fields.start_time;
check_end = check_rec_fields.end_time;
if((curr_start.getTime() <= check_start.getTime() && check_end.getTime()<= curr_end.getTime()) ||
(curr_start.getTime()>=check_start.getTime() && curr_start.getTime()<=check_end.getTime()) ||
(curr_end.getTime()>=check_start.getTime() && curr_end.getTime()<=check_end.getTime())
)
{
//diff = (check_start.getTime() - curr_start.getTime())/1000;
//check_rec["difference"] = diff;
sync.push(check_rec);
}
}
}
function load_data(sync){
var diff;
var last = sync[sync.length-1];
for(var j=0;j<sync.length-1;j++){
s_obj = new buzz.sound(sync[i].fields.rec_file);
sync_group.push(s_obj);
diff = (last.fields.start_time.getTime() - sync[i].fields.start_time.getTime())/1000;
if(diff>=0){
s_obj.setTime(diff);
}
else{
alert("error");
}
}
loaded = 1;
}
function synchronise(id){
$.ajax({
type:"GET",
url:"/webapp/playSound:" + id,
success: function(data){
curr_rec = eval("(" + data + ")");
curr_start = curr_rec.fields.start_time;
curr_end= curr_rec.fields.end_time;
curr_s_obj = new buzz.sound(curr_rec.fields.rec_file);
});
alert("ggo");
$.ajax(
type:"GET",
url:"/webapp/getRecs",
success: function(data){
recs = eval("("+ data +")");
process_data(recs);
});
alert(curr_start);
sync = sync.sort(compare);
load_data(sync);
var s1 = new buzz.sound( "../../static/data/second_audio.ogg");
s = new buzz.sound( "../../static/data/" + id +".ogg"); //curr_rec.fields.rec_file
/*
sync_group.push(s);
s.setTime(20.5);
sync_group.push(s1);
*/
group = new buzz.group(sync_group);
}
function playS(id){
if(loaded==0)
synchronise(id);
group.togglePlay();
}
function stopS(){
group.stop();
}

Categories

Resources