Pebble.js not loading menu data from JSON source - pebble-watch

I'm currently messing around with pebble.js (sdk 2.0), and I'm trying to make a menu based app which loads data from a JSON source.
I can get everything working fine, except the populating the menu part. Here is my code :
var UI = require('ui');
var ajax = require('ajax');
var dataJSON = [];
var fruits = [
{
title: "Apple",
subtitle: "Green and crispy!"
},
{
title: "Orange",
subtitle: "Peel first!"
},
{
title: "Melon",
subtitle: "Only three left!"
}
];
var parseFeed = function(data, quantity) {
var items = [];
for(var i = 0; i < quantity; i++) {
var teamOne = data.matches[i].team1.team_tag;
var teamTwo = data.matches[i].team2.team_tag;
var startTime = data.matches[i].starttime;
var title = (teamOne + ' vs ' + teamTwo);
var time = (startTime.substring(11) + " CET" );
items.push({
title:title,
subtitle:time
});
}
return items;
};
var matchMenu = new UI.Menu({
sections: [{
title: 'D2MT',
items: dataJSON
}]
});
ajax({
url:'http://dailydota2.com/match-api',
type:'json'
},
function(data) {
dataJSON = parseFeed(data, data.matches.length);
for(var i = 0; i < fruits.length; i++) {
console.log('title = ' + fruits[i].title);
console.log('subtitle = ' + fruits[i].subtitle);
}
for(var j = 0; j < dataJSON.length; j++) {
console.log('title = ' + dataJSON[j].title);
console.log('subtitle = ' + dataJSON[j].subtitle);
}
console.log('SHOW MENU');
matchMenu.show();
},
function(error) {
console.log('Download failed: ' + error);
}
);
which outputs :
[PHONE] pebble-app.js:?: title = Apple
[PHONE] pebble-app.js:?: subtitle = Green and crispy!
[PHONE] pebble-app.js:?: title = Orange
[PHONE] pebble-app.js:?: subtitle = Peel first!
[PHONE] pebble-app.js:?: title = Melon
[PHONE] pebble-app.js:?: subtitle = Only three left!
[PHONE] pebble-app.js:?: title = Rave vs 5eva
[PHONE] pebble-app.js:?: subtitle = 14:00:00 CET
[PHONE] pebble-app.js:?: title = Arcanys vs XctN
[PHONE] pebble-app.js:?: subtitle = 14:30:00 CET
[PHONE] pebble-app.js:?: title = VP vs Meepwn'd
[PHONE] pebble-app.js:?: subtitle = 17:00:00 CET
[PHONE] pebble-app.js:?: title = Vega vs NiP
[PHONE] pebble-app.js:?: subtitle = 17:00:00 CET
[PHONE] pebble-app.js:?: title = Secret vs Empire
[PHONE] pebble-app.js:?: subtitle = 20:00:00 CET
[PHONE] pebble-app.js:?: title = SumsRift vs HR
[PHONE] pebble-app.js:?: subtitle = 20:00:00 CET
[PHONE] pebble-app.js:?: title = NiP vs Vega
[PHONE] pebble-app.js:?: subtitle = 20:30:00 CET
[PHONE] pebble-app.js:?: title = Fire vs Thu
[PHONE] pebble-app.js:?: subtitle = 23:00:00 CET
[PHONE] pebble-app.js:?: title = Signature vs G Guard
[PHONE] pebble-app.js:?: subtitle = 08:00:00 CET
[PHONE] pebble-app.js:?: title = Aces vs MVP
[PHONE] pebble-app.js:?: subtitle = 11:00:00 CET
[PHONE] pebble-app.js:?: SHOW MENU
[PHONE] pebble-app.js:?: (+) [menu 1] : [menu 1]
The menu loads 'Fruits' fine, but when i load 'dataJSON' it doesn't do anything, anyone one else know whats going on with why it won't load the data into the menu

I failed to realise : var matchMenu = new UI.Menu, created the menu then and there, so when dataJSON was full, the menu was already made, fixed by creating the menu once dataJSON is full.

Like you mentioned in your own answer, you are making the menu right at the first call of var matchMenu = new UI.Menu. The way to fix that is one of two ways.
You can do it how you mentioned and make the menu after retrieving your data but then you are limiting when and how to call that menu. You likely created that menu inside a function that makes it have a lot of overhead to load it again.
You really should be doing it the way you started but then adding the dataJSON to the menu before displaying it. That will allow you the flexibility to have a global addressable menu that you can update as you proceed in your app, instead of each time requiring the server loaded information to be called again.
Also, in my suggested method, you can put in a base menu that can let the user know if that is displayed that we are having trouble loading information.

Related

Exporting Google Calendar to goggle sheet - issues with sorting from newest to oldest

How do I get this script to re-order so that when it exports the data the most recent entries are at the top? At the moment it puts the oldest data a the top.
function export_gcal_to_gsheet() {
var mycal = "Email";
var cal = CalendarApp.getCalendarById(mycal);
var events = cal.getEvents(new Date("July 01, 2022 00:00:00 UTC"), new Date ("September 12, 2022 23:59:59 UTC"));
var sheet = SpreadsheetApp.getActiveSheet();
sheet.clearContents();
var header = [["Calendar Address", "Event Title", "Event Description", "Event Location", "Event Start", "Event End", "Calculated Duration", "Visibility", "Date Created", "Last Updated", "MyStatus", "Created By", "All Day Event", "Recurring Event"]]
var range = sheet.getRange(1, 1, 1, 14);
range.setValues(header);
for (var i = 0; i < events.length; i++) {
var row=i+2;
var myformula_placeholder = '';
var details=[[mycal,events[i].getTitle(), events[i].getDescription(), events[i].getLocation(), events[i].getStartTime(), events[i].getEndTime(), myformula_placeholder, ('' + events[i].getVisibility()), events[i].getDateCreated(), events[i].getLastUpdated(), events[i].getMyStatus(), events[i].getCreators(), events[i].isAllDayEvent(), events[i].isRecurringEvent()]];
var range=sheet.getRange(row,1,1,14);
range.setValues(details);
var cell=sheet.getRange(row,7);
cell.setFormula('=(HOUR(F' +row+ ')+(MINUTE(F' +row+ ')/60))-(HOUR(E' +row+ ')+(MINUTE(E' +row+ ')/60))');
cell.setNumberFormat('.00');
}
}
Modify the Formula in your For Loop
In your for loop, modify the formula for your row from:
var row=i+2;
to:
var row = events.length + 1 - i;
This will display the most recent entry the top of the row.

How to sort last four files in a google drive folder via google-apps-script?

I have some google sheets in google drive. I am trying to send only last four months files in google drive to email. The problem is the months are defined in the file's name. So there is no timestamp
So far, I am searching the files by title contains "Mar 2019" or title contains "Apr 2019". if like this, I have to change the code every month after adding a file to the google drive.
function checkSales(){
var file, files = DriveApp.getFolderById("").searchFiles('title
contains "Mar 2019" or title contains "Apr 2019" or title contains "May
2019" or title contains "Jun 2019"')
var body = '';
var subject = [];
while (files.hasNext()) {
file = files.next();
var activeSpreadSheet = SpreadsheetApp.open(file);
var spreadsheetName = activeSpreadSheet.getName(); // Added
var sheets = activeSpreadSheet.getSheets();
for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) {
var sheet = sheets[sheetIndex];
var data = sheet.getDataRange().getValues();
var resultArr = [];
for (var i=1;i<data.length;i++) {
for (var j=11;j<19;j++) {
var cellVal = data[i][j];
if (cellVal > 0) {
resultArr.push([data[i][0],data[0][j],cellVal]);
}
}
}
}
}
I want the output to send the last four files in the google drive to email.
You want to automatically create the search query using a script.
You want to search files using the created search query.
For example, when today is July 2019, you want to create the search query like below.
'title contains "Mar 2019" or title contains "Apr 2019" or title contains "May 2019" or title contains "Jun 2019"'
If my understanding is correct, how about this modification? Please think of this as one of several answers.
Modification points:
At first, a JSON object is created as follows.
{0: "Jan", 1: "Feb", 2: "Mar", 3: "Apr", 4: "May", 5: "Jun", 6: "Jul", 7: "Aug", 8: "Sep", 9: "Oct", 10: "Nov", 11: "Dec"}.
Using this object and the date object, the filenames are created.
At first, please check the values of above JSON object I prepared. If there are modification values, please modify them. If the wrong values are included, the files cannot be retrieved. Please be careful this.
Modified script:
Please modify as follows.
From:
var file, files = DriveApp.getFolderById("").searchFiles('title contains "Mar 2019" or title contains "Apr 2019" or title contains "May 2019" or title contains "Jun 2019"')
To:
var months = {0: "Jan", 1: "Feb", 2: "Mar", 3: "Apr", 4: "May", 5: "Jun", 6: "Jul", 7: "Aug", 8: "Sep", 9: "Oct", 10: "Nov", 11: "Dec"};
var date = new Date();
var y = date.getFullYear();
var m = date.getMonth();
var fileNames = [];
for (var i = 0; i < 4; i++) {
m--; // For example, when today is July, you need June, May, Apr and Mar.
if (m < 0) {
m += 12;
y--;
}
fileNames.push(months[m] + " " + y);
// m--; // For example, when today is July, you need July, June, May and Apr.
}
var searchQuery = fileNames.map(function(e) {return 'title contains "' + e + '"'}).join(" or ");
var file, files = DriveApp.getFolderById("root").searchFiles(searchQuery);
Note:
I couldn't understand about var spreadsheetNames = DriveApp.searchFiles(. I think that when your script is saved, an error occurs.
This is also mentioned by Tedinoz's comment.
In this sample script, when today is July, June, May, Apr and Mar are retrieved. If you want to retrieve July, June, May and Apr, please modify the commented out of m--; of above script.
References:
getFullYear()
getMonth()
If I misunderstood your question and this was not the direction you want, I apologize.
Try this:
function getLastFourMonthFileIds(){
var nA=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Nov','Dec'];
var mA=[];
for(var i=0;i<4;i++) {
var dt=new Date(new Date().getFullYear(),new Date().getMonth()-i,new Date().getDate());
mA.push(nA[dt.getMonth()]+dt.getFullYear());
}
var fA=[];
var files = DriveApp.getFolderById("").getFilesByType(MimeType.GOOGLE_SHEETS);
while(files.hasNext()) {
var file=files.next();
if(mA.indexOf(file.getName())>-1) {
fA.push(file.getId());
}
}
Logger.log(fA);
return fA();
}
A code example using the getLastUpdated() attribute.
function so5689562902() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheetname = "56895629";
var sheet = ss.getSheetByName(sheetname);
sheet.activate;
// sundry variables
var filearray = [];
var filedetail = [];
var emailarray = [];
var emailattachments = [];
var numberReq = 4;
// get the files from the folder
var folder = DriveApp.getFolderById("<<insert Folder ID>>");
var files = folder.getFiles();
while (files.hasNext()) {
var file = files.next();
filedetail=[];
//Logger.log("DEBUG: file name: "+file.getName()+", file ID: "+file.getId()+", last updated: "+file.getLastUpdated());
filedetail.push(file.getName());
filedetail.push(file.getId());
filedetail.push(file.getLastUpdated());
// build cumulative array
filearray.push(filedetail);
}
// sort the array by date updated
filearray.sort(function(x,y){
var xp = x[2];
var yp = y[2];
return xp == yp ? 0 : xp > yp ? -1 : 1;
});
// get just the first N files
for (i=0;i<numberReq;i++){
filedetail=[];
filedetail.push(filearray[i][0] ); // name
filedetail.push(filearray[i][1] ); // file ID
filedetail.push(filearray[i][2] ); // last updated
// build the array of email files
emailarray.push(filedetail);
emailattachments.push(filearray[i][1])
}
// display the details for proof
//var arraylen = emailarray.length;
//Logger.log("DEBUG: the array length = "+arraylen);
//var targetrange = sheet.getRange(2,1,arraylen, 3);
//Logger.log("DEBUG: the target range = "+targetrange.getA1Notation());
//targetrange.setValues(emailarray);
// sample sendEmail.
// email attachments are included in the options
//GmailApp.sendEmail(<<recipient>>, <<Subject>>,nonhtmlmessage, {from:senderemail,htmlBody: htmlmessage,name: senderName,replyTo:senderemail ,attachments: emailattachments });
}

Telerik Reporting Static Table Layout

I need to create exactly like this report format shown from the image.
Is there any tutorial on how to create this kind of report?
My report need to be 11 rows x 4 column. So maximum is 44 data in 1 page.
Right now my report generate 44 pages instead of 1 page.
Here is my code:
if (rptModel.Details.FirstOrDefault() != null)
{
foreach (var item in rptModel.Details)
{
var rpt = new ProductLabelReport();
rpt.DataSource = rptModel;
rpt.ReportParameters["Location"].Value = string.IsNullOrEmpty(item.Location) ? string.Empty : item.Location;
rpt.ReportParameters["Part"].Value = string.IsNullOrEmpty(item.SKU) ? string.Empty : item.SKU;
rpt.ReportParameters["CartonID"].Value = string.IsNullOrEmpty(item.CartonID) ? string.Empty : item.CartonID;
string[] formats = { "dd/MM/yyyy hh:mm:ss tt", "dd/MM/yyyy hh:mm:ss", "d/M/yyyy hh:mm:ss tt", "d/M/yyyy h:mm:ss tt" };
DateTime expectedDate;
if (DateTime.TryParseExact(item.ActDate, formats, new System.Globalization.CultureInfo("en-US"),
System.Globalization.DateTimeStyles.None, out expectedDate))
{
rpt.ReportParameters["StockIn"].Value = expectedDate.ToString("dd/MM/yyyy");
}
else
{
rpt.ReportParameters["StockIn"].Value = "";
}
rptBook.Reports.Add(rpt);
}
}
RptDoc = rptBook;
I'm using Telerik Reporting Q2 2015 - 9.1.15.624 and WPF Visual Studio 2015.
Please help.
Just solve the issue..
In Properties => Page Setting (expand it) => ColumnCount (here set how many columns you want).
The code also need to change to:
if (rptModel.Details.FirstOrDefault() != null)
{
var rpt = new ProductLabelReport();
rpt.DataSource = rptModel.Details;
rptBook.Reports.Add(rpt);
}
RptDoc = rptBook;
without no foreach as before code have it.
The foreach is been used when inserting data for rptModel.Details

Setting Yearless Birthday in CNContact class with Xamarin iOS

How do you set a new Contact with a yearless birthday with Xamarin iOS?
iOS Documentation states you can just leave the NSDateComponent.year field blank for a yearless birthday.
After trying this in Xamarin iOS, it bugs out the birthday field on the New Contact UI, making it unusable.
var store = new CNContactStore();
var contact = new CNMutableContact();
// construct birthday w/o year
var birthDate = new NSDateComponents();
birthDate.Month = 11;
birthDate.Day = 12;
contact.Birthday = birthDate;
// pop iOS Contact UI
var editor = CNContactViewController.FromNewContact (contact);
editor.ContactStore = store;
editor.AllowsActions = false;
editor.AllowsEditing = true;
navcontroller.PushViewController(editor,true);
You need to save the contact first, then the iOS Contact Editor can handle the year-less date correctly.
var store = new CNContactStore();
var contact = new CNMutableContact()
{
GivenName = "Stack",
FamilyName = "Overflow"
};
var birthDate = new NSDateComponents();
contact.Birthday = new NSDateComponents()
{
Month = 11,
Day = 12,
};
######
var saveRequest = new CNSaveRequest();
saveRequest.AddContact(contact, null);
NSError error;
store.ExecuteSaveRequest(saveRequest, out error);
######
var editor = CNContactViewController.FromNewContact(contact);
editor.ContactStore = store;
editor.AllowsActions = false;
editor.AllowsEditing = true;
PresentViewControllerAsync(editor, true);
Figured it out. You have to set the calendar in the NSDateComponents to Gregorian.
var store = new CNContactStore();
var contact = new CNMutableContact();
// construct birthday w/o year
var birthDate = new NSDateComponents();
birthDate.Calendar = new NSCalendar(NSCalendarType.Gregorian);
birthDate.Month = 11;
birthDate.Day = 12;
contact.Birthday = birthDate;
// pop iOS Contact UI
var editor = CNContactViewController.FromNewContact (contact);
editor.ContactStore = store;
editor.AllowsActions = false;
editor.AllowsEditing = true;
navcontroller.PushViewController(editor,true);

Set the format of a Kendo DateTimePicker date sent to the controller

I'm using a Kendo DateTimePicker in my application.
The value I get from it in my application is
Wed Aug 13 2014 00:00:00 GMT+0200 (Romance Daylight Time)
I can't parse this to a DateTime. I get a "String was not recognized as a valid DateTime." error.
How can I set the format of the date I get from the DateTimePicker?? Is there an option in Kendo DateTimePicker??t
If you Need to Change the Date that you get from your application you can do as below
var dateobj=kendo.parseDate("Wed Aug 13 2014 00:00:00 GMT+0200 (Romance Daylight Time)", "yyyy-MM-dd h:mm:ss tt");
var datestring = kendo.toString(dateobj, "MM-dd-yyyy h:mm:ss tt");
kendo.parseDate() will Parse the Date to a Date Object and kendo.toString() will format the date to a string
If you need to convert the date you get from the Datepicker Do this
var datepicker = $("#datepicker").data("kendoDatePicker");
var value = datepicker.value();
kendo.toString(value,"dd/MM/YYYY")
IF you need to convert Datepicker date to the Sever Date
var datepicker = $("#datepicker").data("kendoDatePicker");
var value = datepicker.value();
value.toUTCString();
Here what I have used:
var dateobj = kendo.parseDate("Wed Aug 13 2014 00:00:00 GMT+0200 (Romance Daylight Time)");
var datestring = kendo.toString(dateobj, "MM-dd-yyyy h:mm:ss tt");
I created a custom binder which I use in place of the "VALUE" data-bind property
kendo.data.binders.widget.shortdate = kendo.data.Binder.extend({
init: function (widget, bindings, options) {
kendo.data.Binder.fn.init.call(this, widget.element[0], bindings, options);
var that = this;
$(widget.element).on("change", function () {
that.change();
});
},
refresh: function () {
var path = this.bindings.shortdate.path,
source = this.bindings.shortdate.source,
value = source.get(path);
this.bindings["shortdate"].set(value);
},
change: function () {
var formatedValue = this.element.value,
value = kendo.toString(new Date(formatedValue), "d");
if (value) {
this.bindings["shortdate"].set(value);
}
}
});
you can also try this
entity.ExpiredDate = ParseDate(model.ExpiredDate);
private static DateTime ParseDate(string input)
{
return DateTime.ParseExact(input, formats, CultureInfo.InvariantCulture, DateTimeStyles.None);
}
private static string[] formats = new string[]
{
"MM/dd/yyyy HH:mm:ss tt",
"MM/dd/yyyy HH:mm:ss",
"M/dd/yyyy H:mm:ss tt",
"M/dd/yyyy H:mm:ss" ,
"MM/dd/yyyy hh:mm tt"
};
You can also see this
If you are binding the grid using the kendo API, you can use .Format("0:d").
Here is the link where you can find meaning of standard and custom formats-
Date formatting
Here is one example using custom formatting
columns.Bound(model => model.CreatedOn).Format("{0:dd.MM.yyyy - HH:mm:ss}");
It result in this in 24 hour format: 20.07.2016 - 11:01:23.

Resources