Template.templatename.rendered can't return any data from mongodb - mongodb

I would like to know how can I get the data from mongodb in Template.templatename.rendered function. I tried click event on other template and it's all working fine and return the results i wanted. But what I need is to rendered the chart on load. But I could not get any data from the mongodb.
//poll.js
var drawPollChart = function(){
//returns data on other template methods except for
//Template.templatename.rendered
var dist = getDistinctQuestionId();
alert('dist:'+dist);
var data_x =[];
for(var i=0; i< 1; i++)
{
var count = getDataCount(dist[i]);
var uniq = getDistinctResponseBucket(dist[i]);
for(var j=0; j<uniq.length; j++)
{
//alert('data:' + count[uniq[j]] + ", label:" + uniq[j]);
data_x.push({
data : count[uniq[j]],
label: uniq[j]
});
}
}
Template.pollChart.rendered = function() {
//can't draw a thing cause can't get any data from mongodb
drawPollChart();
};
Help please? Thanks in advance.

Just because the template is rendered doesn't mean the DB is connected.
Use Meteor.status().status to detect the state of the connection. For example you could wait to render the pollChart-template at all until Meteor.status().status === 'connected'.

Related

Adding color to Netsuite suitelet's sublist row depending upon the result

Is there any way to add colors to a sublist's row depending upon a condition. I have loaded a saved search to show output on a sublist. But now I want to highlight the rows if the difference between todays date and audit date(search output) is more than 100 days.
var search = nlapiLoadSearch('customrecord_cseg_properties', 'customsearch52');
var columns=search.getColumns();
var sublist = form.addSubList('customsublist', 'staticlist', 'List of properties');
for(var i = 0; i< columns.length; i++){
sublist.addField('customcolumn'+i, 'text', columns[i].getLabel());
}
var result= search.runSearch();
var resultIndex = 0,resultStep = 1000,resultSet,resultSets = [];
do {
resultSet = result.getResults(resultIndex, resultIndex + resultStep);
resultSets = resultSets.concat(resultSet);
resultIndex = resultIndex + resultStep;
} while (resultSet.length > 0);
nlapiLogExecution('DEBUG','The Total number of rows is',resultSets.length);
for(var w= 0; w<resultSets.length ;w++){
for(var x=0; x<columns.length; x++){
var temp;
temp=resultSets[w].getText(columns[x]);
if(temp==null || temp==''){
temp=resultSets[w].getValue(columns[x]);
}
sublist.setLineItemValue('customcolumn'+x, Number(w)+1,temp);
}
I couldn't find any functions in UI Builder API for Netsuite for doing this. Please let me know if there is any other way to do this. Above is the code which I have used to display search result in suitelet.
There is no native api for that.
You can do it by mainpulating the DOM on the client script onInit function.
Just keep in mind that DOM manipulation are risky since they can break if NetSuite will chnage the DOM structure.

List all Labels of an email to Spreadsheet

My emails usually has more than one Labels assigned. I like to search emails with a specific label then list them into the spreadsheet and show all other labels also assigned to the email.
Here's what i have so far, can't figure out how to get the other labels...
function myFunction() {
var ss = SpreadsheetApp.getActiveSheet();
var threads = GmailApp.search("label:Test");
for (var i=0; i<threads.length; i++)
{
var messages = threads[i].getMessages();
for (var j=0; j<messages.length; j++)
{
var sub = messages[j].getSubject();
var from = messages[j].getFrom();
var dat = messages[j].getDate();
ss.appendRow([dat, sub, from])
}
}
}
As far as Apps Script is concerned, Gmail labels are applied to threads and not to individual messages. (There are other contexts where this isn't necessarily true, as a Web Apps post details).
So, you should use the getLabels method of the Thread object. It then makes sense to structure the output so that each row corresponds to a thread, rather than a message. This is what I did below. The script takes subject/from/date from the first message in each thread. The 4th column is the comma-separated list of labels, except the one you search for.
function myFunction() {
var sheet = SpreadsheetApp.getActiveSheet();
var search_label = 'Test';
var threads = GmailApp.search('label:' + search_label);
var output = [];
for (var i=0; i < threads.length; i++) {
var firstMessage = threads[i].getMessages()[0];
var sub = firstMessage.getSubject();
var from = firstMessage.getFrom();
var dat = firstMessage.getDate();
var labels = threads[i].getLabels();
var otherLabels = [];
for (var j = 0; j < labels.length; j++) {
var labelName = labels[j].getName();
if (labelName != search_label) {
otherLabels.push(labelName);
}
}
output.push([dat, sub, from, otherLabels.join(', ')]);
}
sheet.getRange(1, 1, output.length, output[0].length).setValues(output);
}
I prefer not to add one row at a time, instead gathering the double array output and inserting it all at once. Of course you can use appendRow as in your script. Then you wouldn't necessarily need a comma-separated list,
sheet.appendRow([dat, sub, from].concat(otherLabels));
would work.

POSTMAN jetpacks TESTING within for loop

Hitting API w/ GET request, checking if item has been deleted by globals.id variable, have test inside forloop and when I run test returns 0/0 tests passed. All of my console logs within the for loop work, the objects contain values matching what I have as well. Anyone know how to do this?
var data = JSON.parse(responseBody);
for (var i = 0; i < data.length; i++){
tests["id has been deleted"] = data[i].id !== globals.id;
if(data[i].id !== globalID){
tests["id has been deleted"] = data[i].id !== globals.id;
return true;
}
}
I could make test with for loop.
My Json:
{
"rows": [
{
"id": "2804",
"title": "Some title",
...
},
...
],
"total": "2788"
}
My test:
for (var i in data.rows){
var obj = data.rows[i];
tests["title of row #" + i + " is not null"] = !!obj.title;
tests["title of row #" + i + " is not empty"] = obj.title !== "";
}
But if I use "return true" Postman shows "Tests (0/0)"
You can make use of forEach loop for iterating the result set returned in response. It returns the objects of specified type which can be used for processing.
var data = JSON.parse(responseBody);
data.forEach(function(process){
var processId = "Id" + process.id;
//console.log("processId" + processId);
})
Yes Ranson Namba! I'm experiencing the same thing - even attempting to write to the console is ignored within my For loops. What's more, it would be ever so helpful to be able to specify arrays within the For loop, but apparently Postman doesn't allow that either. What's the solution to all this limiting BS?
var responseData = JSON.parse(responseBody);
for (i = 0; i < responseData.scoringResults.length; i++) {
var scores = responseData[i].score;
for (j; j < scores.length; j++){ //scores.length = 4 at this point
var scoreValues = scores[j].split(",");
tests["Verify number of score dimensions"] = scoreValues.length === 4;
}
}
tests["Status code is 200"] = responseCode.code === 200;
The last tests works fine, just nothing you put inside either for loop works, even a simple console.log("whatever"). A little help? Thx

Export Email-adress from a label in Gmail using Apps Script

Hi im trying to export the Emailadresses from the senders in a label in Gmail Called "Suarez". But it's just running and never completing, it should be about 372 emails. Is it to much to print to the logger?
Here is what im trying:
function getEmailsadresses(){
var threads = GmailApp.search("in:suarez");
for (var i = 0; i < threads.length; i++) {
var messages = threads[i].getMessages();
for (var m = 0; m < messages.length; m++) {
var msg = messages[m].getFrom();
}
}
Logger.log(msg()); // log from address of the message
}
I use a script embedded in an spreadsheet the reads every messages in every threads in a Label that could probably be a good starting point for you.
My specific use case was to log SMS messages that my android phone sends me as emails each time I send or receive a text message.
So it will work for you by just changing the label name and maybe remove the data filtering I added on the message. Since I have a lot of data I set up a time trigger task manager to works in small bunches to avoid exceeding time limit.
Usage is simple : run the "startSMSLog" and go have a couple of coffees until the cell A1 in the spreadsheet stops being RED... that's it.
Code below : the start function
function startSMSLog(){
var triggerID = ScriptApp.newTrigger('countSMSLogEmails').timeBased().everyMinutes(5).create().getUniqueId();
var thisTrigger = PropertiesService.getScriptProperties().setProperty('thisTriggerSMS',triggerID);
PropertiesService.getScriptProperties().setProperty('current thread SMS',0);
var sh = SpreadsheetApp.getActive().getSheetByName('SMS'); // change to the name of your sheet
sh.getRange('A1').setBackground('red');
countSMSLogEmails(true);
}
and the "working" code :
function countSMSLogEmails(clearSheet){
var sh = SpreadsheetApp.getActive().getSheetByName('SMS');
var start = Number(PropertiesService.getScriptProperties().getProperty('current thread SMS'));
var CallLogThreads = GmailApp.getUserLabelByName('SMS').getThreads(start,10);
if(CallLogThreads.length==0){
sh.sort(2,false);
sh.getRange('A1').setBackground('#FFC');
var triggers = ScriptApp.getProjectTriggers();
var thisTrigger = PropertiesService.getScriptProperties().getProperty('thisTriggerSMS');
for(var n in triggers){
if(triggers[n].getUniqueId()==thisTrigger){ScriptApp.deleteTrigger(triggers[n])};
}
sh.getRange('A1').setValue('Subject (Log on '+Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "dd-MMM-yy HH:mm")+')');
return;
} else {
PropertiesService.getScriptProperties().setProperty('current thread SMS',start+CallLogThreads.length);
}
var data = [];
for(var n=0;n<CallLogThreads.length;n++){
var thread = CallLogThreads[n];
Logger.log('thread message count = '+thread.getMessageCount());
var msg = thread.getMessages();
var msgData = [];
for(var m in msg){
var msgDate = msg[m].getDate();
var msgSubject = msg[m].getSubject();
var msgBody = msg[m].getBody().replace(/[\n\r]/g,' ').replace(/'/g,"'").replace(/ /g,"!").replace(/&/g,"&").replace(/"/g,'"')
.replace(/>/g,'>').replace(/</g,'<').replace(/<br \/>/g,'\n').replace(/<br>/g,'\n');
msgData.push([msgSubject,msgDate,msgBody]);
}
data.push(msgData);
}
var dataTotal = [];
if (clearSheet==true) {
dataTotal.push(['subject', 'date', 'message']);
}
for(var n in data){
dataTotal = dataTotal.concat(data[n]);
};
Logger.log(JSON.stringify(dataTotal));
if (clearSheet==true) {
sh.clearContents();
sh.getRange(1,1,dataTotal.length,dataTotal[0].length).setValues(dataTotal);
}else{
sh.getRange(sh.getLastRow()+1,1,dataTotal.length,dataTotal[0].length).setValues(dataTotal);
}
}

Find if given lat-long lies in any of the polygon in MongoDB

I want to know if I get a lat-long of a user and want to check if he lies in any of the polygon that is stored in my db (MongoDB). How can this be achieved using mongoDB.
For instance my db will have 10 polygons stored as GeoJson objects. I get a lat-long and want to check if this lat-long lies in any of the 10 polygons in my DB.
Can this be achieved in MongoDB?
I dont think your particular case can be achieved in MongoDB. MongoDB does have polygon calculations with the $polygon operator. However, this operator takes a polygon and confirms if any documents are within it not the other way round.
I wrote this code in javascript it is working fine for me
var polygonData = "43.64486433588385,-79.3791389465332;43.64508171979899,-79.3930435180664;43.63682057801007,-79.38437461853027;43.63946054004705,-79.36819553375244;43.652720712083266,-79.37201499938965;43.65793702655821,-79.39111232757568;43.64927396999741,-79.37222957611084";
var lat='43.64927396999741';
var lng='-79.37222957611084';
polySearch(polygonData,lat,lng);
function polySearch(polygonData,lat,lng){
var lat_long=lat+","+lng;
var longitude_x = lng;
var latitude_y = lat;
var is_in_polygon=false;
var vertices_x=[];
var vertices_y=[];
var arr=polygonData.split(';');
for(var j=0; j<arr.length; j++){
var arr1=arr[j].split(',');
vertices_x.push(arr1[1]);
vertices_y.push(arr1[0]);
}
var points_polygon = vertices_x.length;
var isIn=isInPolygon(points_polygon, vertices_x, vertices_y, longitude_x, latitude_y);
if (isIn==1)
console.log('Which is in polygon');
else
console.log('Which is not in polygon');
function isInPolygon(points_polygon, vertices_x, vertices_y, longitude_x, latitude_y)
{
var i = 0;
var j = 0;
var c = 0;
for (i = 0, j = points_polygon-1 ; i < points_polygon; j = i++) {
var val="((("+vertices_y[i]+" > "+latitude_y+") != ("+vertices_y[j]+" > "+latitude_y+")) && ("+longitude_x+" < ("+vertices_x[j]+" - "+vertices_x[i]+") * ("+latitude_y+" - "+vertices_y[i]+") / ("+vertices_y[j]+" - "+vertices_y[i]+") + "+vertices_x[i]+"))";
if(eval(val))c=!c;
}
return c;
}
}
Sorry to only past two links, but i think these explains what should be done far better then i would:
A SO answer in the same subject
An excellent tutorial how to use mongodb geospatial indexes