407 Proxy Error Encountered with Fusion Tables - google-fusion-tables

When I try to use the docid in place of the table id I get a 407 proxy error. My understanding is that you don't need to authenticate for selecting records, only for inserts, updates, and deletes. When I use the table id, the sql query hangs. I noticed these errors in the Firebug console window.
I am able to receive data from both tables (levels_a.txt & levels_b.txt) when the tables aren't merged. The same isn't true when they are merged. Please see below for my code.
google.load("visualization", "1", { packages: ["corechart", "annotatedtimeline"] });
var map, layer;
var tableID = 3013978;
//var tableID = "1RWnj3geWmOXHcedu8RUeyb1v4ZjZz3YWNpK0MDs";
var location_column = 'geometry';
var name, PID;
var chart;
var jqXHR;
var formatter_long;
var dt;
var rows;
var plot;
var scatter_chart;
var g;
function initialize() {
var latlng = new google.maps.LatLng(53.760861, -98.813876);
var myOptions = {
center: latlng,
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL
},
mapTypeControl: true,
mapTypeControlOptions: {
mapTypeIds: [
google.maps.MapTypeId.ROADMAP,
google.maps.MapTypeId.SATELLITE,
google.maps.MapTypeId.HYBRID,
google.maps.MapTypeId.TERRAIN
],
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
overviewMapControl: true,
overviewMapControlOptions: {
opened: true
}
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
layer = new google.maps.FusionTablesLayer({
query: {
select: location_column,
from: tableID
}
});
layer.setMap(map);
google.maps.event.addListener(layer, 'click', function (e) {
name = e.row['name'].value;
PID = e.row['WELL_PID'].value;
drawChart(PID, name);
});
}
function drawChart(PID, name) {
/*
var queryURL = "http://www.google.com/fusiontables/api/query?sql=";
var queryTail = '&jsonCallback=?';
var whereClause = "WHERE 'WELL_PID'=" + PID; // table id 3004502
var query = "SELECT 'Date','Level' FROM 3004502 " + whereClause;
var queryText = encodeURIComponent(query);
*/
//--------------------------------------------------------------------------------------------//
var queryUrlHead = 'http://www.google.com/fusiontables/api/query?sql=';
var queryUrlTail = '&jsonCallback=?';
var whereClause = "WHERE 'WELL_PID'=" + PID; // table id 3004502
var query = "SELECT 'Date','Level' FROM 1RrJI_dWPjrmJ7A6xD_GcZ3nxIso9ZTvOPWp0suI " + whereClause;
var queryurl = encodeURI(queryUrlHead + query + queryUrlTail);
var jqxhr = $.get(queryurl, dataHandler, "jsonp");
//console.log(jqxhr);
/*
var rows;
var items = [];
var arr = [];
var str;
$.ajax({
type: "GET",
url: queryURL + queryText + queryTail,
cache: false,
dataType: 'jsonp',
jsonpCallback: 'jsonpCallback',
success: function (data) {
rows = data.table.rows;
for (i = 0; i < rows.length; i++) {
var temp = rows[i];
var this_date;
items.push([parseDate(temp[0]), temp[1]]);
}
processData(items);
},
error: function () { alert("Please wait until chart loads before clicking on another well location."); }
});
*/
}
function dataHandler(d) {
var items = [];
var rows = d.table.rows;
for (i = 0; i < rows.length; i++) {
var temp = rows[i];
var this_date;
items.push([parseDate(temp[0]), temp[1]]);
}
processData(items);
}
function processData(res) {
var options = {
strokeWidth: 0.0,
displayAnnotations: true,
labelsKMB: false,
rollPeriod: 14,
showRangeSelector: true,
connectSeparatedPoints: false,
drawPoints: true,
stepPlot: false,
pointSize: 1,
digitsAfterDecimal: 3
};
var dat = new google.visualization.DataTable();
dat.addColumn('date', 'Date');
dat.addColumn('number', 'Water Level');
console.log(res.toString());
if (res.toString() === "") {
alert("Sorry, there is no data available for this well. Please check back at a later time.");
$("#dg_div").empty();
} else {
dat.addRows(res);
if (g) {
g.destroy();
}
g = new Dygraph(document.getElementById("dg_div"), dat, options);
}
}
I would like to perform the following joins:
geography.kml
name | geometry | description
well_name_and_PID.csv
WELL_PID | Name_Short
levels_a.txt
WELL_PID | Date | Level
levels_b.txt
WELL_PID | Date | Level
Joins:
[geography.kml].name -> [well_name_and_PID.csv].Name_Short
[well_name_and_PID.csv].WELL_PID -> [levels_a.txt].WELL_PID
[well_name_and_PID.csv].WELL_PID -> [levels_b.txt].WELL_PID
The rationale behind having two level files is that this file would othewise exceed the 100 meg table cap. These two files contain similar information.
As usual, any help on this is greatly appreciated.
Thanks in advance,
Michael

Related

vectorSource.addFeatures with the parameter Array containing more than 10 features using openlayers 4.3.3

I have a map and I'd like to add features. The features are added correctly always at the end of the array. If there are more than 10 features added, the eleven one - is inserted anywhere.
draw.on('drawend', function(evt) {
var feature = evt.feature;
var anfang = ol.proj.transform(feature.getGeometry().getFirstCoordinate(), 'EPSG:3857', 'EPSG:4326');
var ende = ol.proj.transform(feature.getGeometry().getLastCoordinate(), 'EPSG:3857', 'EPSG:4326');
var url = '?lonlats='+anfang+'|'+ende+'&nogos=&profile=shortest&alternativeidx=0&format=geojson';
url = encodeURIComponent(url);
url = broutes+url;
var response = new XMLHttpRequest();
response.open('GET', url);
var onError = function() {
console.log('error');
}
response.onerror = onError;
response.onload = function() {
if (response.status == 200) {
var data = Ext.decode(response.responseText);
var arr = data.features[0].geometry.coordinates;
var arrayNew = [];
for (i=0; i<arr.length; i++){
var n = ol.proj.transform(arr[i], 'EPSG:4326', 'EPSG:3857');
arrayNew.push(n);
}
var data = new ol.geom.LineString( arrayNew );
//console.log(data);
var featureSnake = new ol.Feature({
geometry: data
});
snakeSource.addFeature( featureSnake );
var win = Ext.create('MyProject.view.window.Edit', {
record : featureSnake,
toDo: 'insert',
});
win.show();
} else {
onError();
}
}
I chanced my code like you told me (using version 4.3.3)
vectorSource = new ol.source.Vector({
useSpatialIndex: false
});
Now I have the following result vectorSource.getFeatures()
polygon1
polygon2
...
polygon15
polygon2
polygon3
...
polygon15
polygon1
I have all features twice.

Google Sheets - A pull data function doesn't want to play nice with a history storing function

I found a couple of functions that met my needs, but they don't want to play nice together. The goal is to pull data once a day, then add it to a new column. The history function is fine, and I've got a trigger setup to run it once a day, but it's erroring when attempting to run automatically, and sending me an email with the following.
6/18/18 5:29 PM loadRegionAggregates TypeError: Cannot find function
forEach in object [object Object]. (line 19, file
"Code") time-based 6/18/18 5:29 PM
here's the full code.gs (I bolded the section with line 19, first line of the function)
// Requires a list of typeids, so something like Types!A:A
// https://docs.google.com/spreadsheets/d/1IixV0eNqg19FE6cLzb83G1Ucb0Otl-Jnvm6csAlPKwo/edit?usp=sharing for an example
function loadRegionAggregates(priceIDs,regionID){
if (typeof regionID == 'undefined'){
regionID=10000002;
}
if (typeof priceIDs == 'undefined'){
throw 'Need a list of typeids';
}
var prices = new Array();
var dirtyTypeIds = new Array();
var cleanTypeIds = new Array();
var url="https://market.fuzzwork.co.uk/aggregates/?station=60003760&types=34,35,36,37,38,39,40"
**priceIDs.forEach(function (row) {
row.forEach(function (cell) {
if (typeof(cell) === 'number' ) {
dirtyTypeIds.push(cell);
}**
});
});
cleanTypeIds = dirtyTypeIds.filter(function(v,i,a) {
return a.indexOf(v)===i;
});
prices.push(['TypeID','Buy volume','Buy Weighted Average','Max Buy','Min Buy','Buy Std Dev','Median Buy','Percentile Buy Price','Sell volume','Sell Weighted Average','Max sell','Min Sell','Sell Std Dev','Median Sell','Percentile Sell Price'])
var parameters = {method : "get", payload : ""};
var o,j,temparray,chunk = 100;
for (o=0,j=cleanTypeIds.length; o < j; o+=chunk) {
temparray = cleanTypeIds.slice(o,o+chunk);
Utilities.sleep(100);
var types=temparray.join(",").replace(/,$/,'')
var jsonFeed = UrlFetchApp.fetch(url+types, parameters).getContentText();
var json = JSON.parse(jsonFeed);
if(json) {
for(i in json) {
var price=[parseInt(i),
parseInt(json[i].buy.volume),
parseInt(json[i].buy.weightedAverage),
parseFloat(json[i].buy.max),
parseFloat(json[i].buy.min),
parseFloat(json[i].buy.stddev),
parseFloat(json[i].buy.median),
parseFloat(json[i].buy.percentile),
parseInt(json[i].sell.volume),
parseFloat(json[i].sell.weightedAverage),
parseFloat(json[i].sell.max),
parseFloat(json[i].sell.min),
parseFloat(json[i].sell.stddev),
parseFloat(json[i].sell.median),
parseFloat(json[i].sell.percentile)];
prices.push(price);
}
}
}
return prices;
}
function storeData() {
var sheet = SpreadsheetApp.getActiveSheet();
var datarange = sheet.getDataRange();
var numRows = datarange.getNumRows();
var numColumns = datarange.getNumColumns();
sheet.getRange(1,numColumns + 1).setValue(new Date());
for (var i=2; i <= numRows; i++) {
var prices = sheet.getRange(i, 8).getValue();
sheet.getRange(i, numColumns + 1).setValue(prices);
}
}
I found this link:
TypeError: Cannot find function forEach in object
Which explains some of it, but when the code runs in debug mode, I don't have a range defined, and then the live sheet bugs with:
ReferenceError: "row" is not defined (line 21).
Note: My original code works fine when I run the script locally, just not when the daily timer goes off. I'm assuming the issues listed on the linked query regarding no forEach class on the nested object are applying to whatever runs the triggered .gs
Edit: Ok so i've been working on this all day. I've learned how to set an array var (since I didn't need to change the array, static works) and i've been trying to get the rest of the code adjusted ever since. Here's where I am so far:
// Requires a list of typeids, so something like Types!A:A
// https://docs.google.com/spreadsheets/d/1IixV0eNqg19FE6cLzb83G1Ucb0Otl-Jnvm6csAlPKwo/edit?usp=sharing for an example
function loadRegionAggregates(priceIDs,regionID){
if (typeof regionID == 'undefined'){
regionID=10000002;
}
if (typeof priceIDs == 'undefined'){
priceIDs = [34,35,36,37,38,39,40,11399];
}
var prices = new Array();
var dirtyTypeIds = new Array();
var cleanTypeIds = new Array();
var url="https://market.fuzzwork.co.uk/aggregates/?station=60003760&types=34,35,36,37,38,39,40"
// for (var priceIDs) {
// if (row.hasOwnProperty(column)) {
// var cell = row[column];
// if (typeof cell == "number") {
priceIDs.push(priceIDs);
// }
// }
// }
cleanTypeIds = dirtyTypeIds.filter(function(v,i,a) {
return a.indexOf(v)===i;
});
prices.push(['TypeID','Buy volume','Buy Weighted Average','Max Buy','Min Buy','Buy Std Dev','Median Buy','Percentile Buy Price','Sell volume','Sell Weighted Average','Max sell','Min Sell','Sell Std Dev','Median Sell','Percentile Sell Price'])
var parameters = {method : "get", payload : ""};
var o,j,temparray,chunk = 100;
for (o=0,j=cleanTypeIds.length; o < j; o+=chunk) {
temparray = cleanTypeIds.slice(o,o+chunk);
Utilities.sleep(100);
var types=temparray.join(",").replace(/,$/,'')
var jsonFeed = UrlFetchApp.fetch(url+types, parameters).getContentText();
var json = JSON.parse(jsonFeed);
if(json) {
for(i in json) {
var price=[parseInt(i),
parseInt(json[i].buy.volume),
parseInt(json[i].buy.weightedAverage),
parseFloat(json[i].buy.max),
parseFloat(json[i].buy.min),
parseFloat(json[i].buy.stddev),
parseFloat(json[i].buy.median),
parseFloat(json[i].buy.percentile),
parseInt(json[i].sell.volume),
parseFloat(json[i].sell.weightedAverage),
parseFloat(json[i].sell.max),
parseFloat(json[i].sell.min),
parseFloat(json[i].sell.stddev),
parseFloat(json[i].sell.median),
parseFloat(json[i].sell.percentile)];
prices.push(price);
}
}
}
return prices;
}
function storeData() {
var sheet = SpreadsheetApp.getActiveSheet();
var datarange = sheet.getDataRange();
var numRows = datarange.getNumRows();
var numColumns = datarange.getNumColumns();
sheet.getRange(1,numColumns + 1).setValue(new Date());
for (var i=2; i <= numRows; i++) {
var prices = sheet.getRange(i, 8).getValue();
sheet.getRange(i, numColumns + 1).setValue(prices);
}
}
So far, so good. It's not throwing any more errors on debug, and the column headers are coming in, but it's not bringing in the data anymore from the push.
Help!

indexeddb on IOS devices

I have a problem with an indexeddb query with index when running on IOS devices.
$.indexedDB(dbName).objectStore(tablename).index("INDICE").each(function(itemLocal) {
itemLocal.delete();
}, [VALORINDICE]).then(function() {
callback();
}, function() {
console.log("error");
});
The problem is if there is more than one record that matches the index, it does not eliminate them, it eliminates the first one and leaves. But if for example I put console.log (itemLocal) instead of itemLocal.delete() if it shows all those that match the index. Any suggestions of something that may be leaking?
I have tried with this code and I get the same error(code without api jquery)
var request = indexedDB.open(DATABASE_NAME);
request.onsuccess = function(event) {
var db = request.result;
var transaction = db.transaction(["TABLE"], "readwrite");
var table = transaction.objectStore("TABLE");
var index = table.index("INDEX");
var req = index.openCursor();
req.onsuccess = function() {
var cursor = req.result;
if (cursor) {
console.info(cursor.value);
cursor["delete"]();
cursor["continue"]();
}
};
req.onerror = function(e) {
console.error(e, req);
};
};
request.onerror = function(e) {
console.error(e, request);
};

Read a GeometryCollection from a string

in OpenLayers 3 I can read Features or a single Geometry from a GeoJSON string through an instance of ol.format.GeoJSON().
Example:
var parser = new ol.format.GeoJSON();
var arrOfFeatures = parser.readFeatures(geoJsonString);
//or
var usrGeom = parser.readGeometry(geoJsonString);
Now I have a string representing a GeometryCollection (not a MultiPoint, MultiLine or MultyPolygon, nor a FeatureCollection).
I cannot find a way to readGeometryCollection(GeoJSONstring) or something, having an ol.geom.GeometryCollection object as the result.
Can anyone help with this?
Thanks in advance.
Ok, the solution was to read a GeometryCollection just like any other Openlayers ol.geom.Geometry and then loop to read any single geometry, so: 1)read the string into a Geometry object, 2) if .getType() is "GeometryCollection" then loop the collection, and forEach(item) in the collection read the Geometry.
parseSingleGeometry : function(geometry, callback) {
switch (geometry.getType()) {
case 'MultiLineString':
geometry.getLineStrings().forEach(function (p) {
var newFeat = new ol.Feature({ geometry: p });
_features.push(newFeat);
});
break;
case 'MultiPolygon':
geometry.getPolygons().forEach(function (p) {
var newFeat = new ol.Feature({ geometry: p });
_features.push(newFeat);
});
break;
case 'Polygon':
case 'LineString':
case 'Point':
var newFeat = new ol.Feature({ geometry: geometry });
_features.push(newFeat);
delete newFeat;
break;
default:
break;
}
if (callback) { callback(); }
},
parseGeometryCollection: function(collection, callback) {
var ciccio = new ol.geom.GeometryCollection();
//ciccio.getType
var itemCount = ciccio.getGeometries().length;
var itemProg = 0;
ciccio.getGeometries().forEach(function (item) {
parseSingleGeometry(item, function () {
itemProg++;
if (itemProg == itemCount) {
if (callback) {
callback();
}
}
})
});
}
[...]
importGeoJson: function (geoJsonString) {
var parser = new ol.format.GeoJSON();
var projection = parser.readProjection(geoJsonString);
var usrProjCode = projection.getCode();
var convert = false;
if (usrProjCode != 'EPSG:3857') {
var msg = "The file provided is in the " + usrProjCode + " projection. The system supports the EPSG:3857 projection only.\n\rWe are converting your geometries in EPSG:3857.\n\rPlease visually check that the added shapes are what your file defines.";
alert(msg);
convert = true;
}
//if it's a feature or feature collection than I can readFeatures()
if (geoJsonString.indexOf("Feature") !== -1) {
console.log("reading feature(s)");
var arrOfFeatures = parser.readFeatures(geoJsonString);
arrOfFeatures.forEach(function (item) {
var usrGeom = item.getGeometry();
var newGeom = (convert) ? usrGeom.clone().transform(usrProjCode, 'EPSG:3857') : usrGeom;
if (newGeom.getType() == "GeometryCollection") {
_private.parseGeometryCollection(newGeom, function () { /*do something*/ })
}
else {
_private.parseSingleGeometry(newGeom, function () { /*do something*/ });
}
});
}
else { //otherwise work with geometries
var usrGeom = parser.readGeometry(geoJsonString);
var newGeom = (convert) ? usrGeom.clone().transform(usrProjCode, 'EPSG:3857') : newGeom;
if (newGeom.getType() == "GeometryCollection") {
_private.parseGeometryCollection(newGeom, function () { /*do something*/ })
}
else {
_private.parseSingleGeometry(newGeom, function () { /*do something*/ });
}
}
},
_features is the ol.Collection containing the features showed on the map.

Google docs spreadsheet script error OAuthConfig when fetching data from Fitbit

I have got following script in Google docs spreadsheet which is fetching data from Fitbit. Script worked fine so far but recently on 6th July Google stopped using OAuthConfig so script is not working since:-(
I am not programmer, I am just advanced user. So I would like to kindly ask some programmer to help tune script below in order to make it work again.
// Key of ScriptProperty for Firtbit consumer key.
var CONSUMER_KEY_PROPERTY_NAME = "fitbitConsumerKey";
// Key of ScriptProperty for Fitbit consumer secret.
var CONSUMER_SECRET_PROPERTY_NAME = "fitbitConsumerSecret";
// Default loggable resources (from Fitbit API docs).
var LOGGABLES = ["activities/log/steps", "activities/log/distance",
"activities/log/activeScore", "activities/log/activityCalories",
"activities/log/calories", "foods/log/caloriesIn",
"activities/log/minutesSedentary",
"activities/log/minutesLightlyActive",
"activities/log/minutesFairlyActive",
"activities/log/minutesVeryActive", "sleep/timeInBed",
"sleep/minutesAsleep", "sleep/minutesAwake", "sleep/awakeningsCount",
"body/weight", "body/bmi", "body/fat",];
// function authorize() makes a call to the Fitbit API to fetch the user profile
function authorize() {
var oAuthConfig = UrlFetchApp.addOAuthService("fitbit");
oAuthConfig.setAccessTokenUrl("https://api.fitbit.com/oauth/access_token");
oAuthConfig.setRequestTokenUrl("https://api.fitbit.com/oauth/request_token");
oAuthConfig.setAuthorizationUrl("https://api.fitbit.com/oauth/authorize");
oAuthConfig.setConsumerKey(getConsumerKey());
oAuthConfig.setConsumerSecret(getConsumerSecret());
var options = {
"oAuthServiceName": "fitbit",
"oAuthUseToken": "always",
};
// get the profile to force authentication
Logger.log("Function authorize() is attempting a fetch...");
try {
var result = UrlFetchApp.fetch("https://api.fitbit.com/1/user/-/profile.json", options);
var o = Utilities.jsonParse(result.getContentText());
return o.user;
}
catch (exception) {
Logger.log(exception);
Browser.msgBox("Error attempting authorization");
return null;
}
}
// function setup accepts and stores the Consumer Key, Consumer Secret, firstDate, and list of Data Elements
function setup() {
var doc = SpreadsheetApp.getActiveSpreadsheet();
var app = UiApp.createApplication().setTitle("Setup Fitbit Download");
app.setStyleAttribute("padding", "10px");
var consumerKeyLabel = app.createLabel("Fitbit OAuth Consumer Key:*");
var consumerKey = app.createTextBox();
consumerKey.setName("consumerKey");
consumerKey.setWidth("100%");
consumerKey.setText(getConsumerKey());
var consumerSecretLabel = app.createLabel("Fitbit OAuth Consumer Secret:*");
var consumerSecret = app.createTextBox();
consumerSecret.setName("consumerSecret");
consumerSecret.setWidth("100%");
consumerSecret.setText(getConsumerSecret());
var firstDate = app.createTextBox().setId("firstDate").setName("firstDate");
firstDate.setName("firstDate");
firstDate.setWidth("100%");
firstDate.setText(getFirstDate());
// add listbox to select data elements
var loggables = app.createListBox(true).setId("loggables").setName(
"loggables");
loggables.setVisibleItemCount(4);
// add all possible elements (in array LOGGABLES)
var logIndex = 0;
for (var resource in LOGGABLES) {
loggables.addItem(LOGGABLES[resource]);
// check if this resource is in the getLoggables list
if (getLoggables().indexOf(LOGGABLES[resource]) > -1) {
// if so, pre-select it
loggables.setItemSelected(logIndex, true);
}
logIndex++;
}
// create the save handler and button
var saveHandler = app.createServerClickHandler("saveSetup");
var saveButton = app.createButton("Save Setup", saveHandler);
// put the controls in a grid
var listPanel = app.createGrid(6, 3);
listPanel.setWidget(1, 0, consumerKeyLabel);
listPanel.setWidget(1, 1, consumerKey);
listPanel.setWidget(2, 0, consumerSecretLabel);
listPanel.setWidget(2, 1, consumerSecret);
listPanel.setWidget(3, 0, app.createLabel(" * (obtain these at dev.fitbit.com)"));
listPanel.setWidget(4, 0, app.createLabel("Start Date for download (yyyy-mm-dd)"));
listPanel.setWidget(4, 1, firstDate);
listPanel.setWidget(5, 0, app.createLabel("Data Elements to download:"));
listPanel.setWidget(5, 1, loggables);
// Ensure that all controls in the grid are handled
saveHandler.addCallbackElement(listPanel);
// Build a FlowPanel, adding the grid and the save button
var dialogPanel = app.createFlowPanel();
dialogPanel.add(listPanel);
dialogPanel.add(saveButton);
app.add(dialogPanel);
doc.show(app);
}
// function sync() is called to download all desired data from Fitbit API to the spreadsheet
function sync() {
// if the user has never performed setup, do it now
if (!isConfigured()) {
setup();
return;
}
var user = authorize();
// Spatny kod, oprava nize - var doc = SpreadsheetApp.getActiveSpreadsheet();
var doc = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Pavel');
doc.setFrozenRows(1);
var options = {
"oAuthServiceName": "fitbit",
"oAuthUseToken": "always",
"method": "GET"
};
// prepare and format today's date, and a list of desired data elements
var dateString = formatToday();
var activities = getLoggables();
// for each data element, fetch a list beginning from the firstDate, ending with today
for (var activity in activities) {
var currentActivity = activities[activity];
try {
var result = UrlFetchApp.fetch("https://api.fitbit.com/1/user/-/"
+ currentActivity + "/date/" + getFirstDate() + "/"
+ dateString + ".json", options);
} catch (exception) {
Logger.log(exception);
Browser.msgBox("Error downloading " + currentActivity);
}
var o = Utilities.jsonParse(result.getContentText());
// set title
var titleCell = doc.getRange("a1");
titleCell.setValue("date");
var cell = doc.getRange('a2');
// fill the spreadsheet with the data
var index = 0;
for (var i in o) {
// set title for this column
var title = i.substring(i.lastIndexOf('-') + 1);
titleCell.offset(0, 1 + activity * 1.0).setValue(title);
var row = o[i];
for (var j in row) {
var val = row[j];
cell.offset(index, 0).setValue(val["dateTime"]);
// set the date index
cell.offset(index, 1 + activity * 1.0).setValue(val["value"]);
// set the value index index
index++;
}
}
}
}
function isConfigured() {
return getConsumerKey() != "" && getConsumerSecret() != "";
}
function setConsumerKey(key) {
ScriptProperties.setProperty(CONSUMER_KEY_PROPERTY_NAME, key);
}
function getConsumerKey() {
var key = ScriptProperties.getProperty(CONSUMER_KEY_PROPERTY_NAME);
if (key == null) {
key = "";
}
return key;
}
function setLoggables(loggable) {
ScriptProperties.setProperty("loggables", loggable);
}
function getLoggables() {
var loggable = ScriptProperties.getProperty("loggables");
if (loggable == null) {
loggable = LOGGABLES;
} else {
loggable = loggable.split(',');
}
return loggable;
}
function setFirstDate(firstDate) {
ScriptProperties.setProperty("firstDate", firstDate);
}
function getFirstDate() {
var firstDate = ScriptProperties.getProperty("firstDate");
if (firstDate == null) {
firstDate = "2012-01-01";
}
return firstDate;
}
function formatToday() {
var todayDate = new Date;
return todayDate.getFullYear()
+ '-'
+ ("00" + (todayDate.getMonth() + 1)).slice(-2)
+ '-'
+ ("00" + todayDate.getDate()).slice(-2);
}
function setConsumerSecret(secret) {
ScriptProperties.setProperty(CONSUMER_SECRET_PROPERTY_NAME, secret);
}
function getConsumerSecret() {
var secret = ScriptProperties.getProperty(CONSUMER_SECRET_PROPERTY_NAME);
if (secret == null) {
secret = "";
}
return secret;
}
// function saveSetup saves the setup params from the UI
function saveSetup(e) {
setConsumerKey(e.parameter.consumerKey);
setConsumerSecret(e.parameter.consumerSecret);
setLoggables(e.parameter.loggables);
setFirstDate(e.parameter.firstDate);
var app = UiApp.getActiveApplication();
app.close();
return app;
}
// function onOpen is called when the spreadsheet is opened; adds the Fitbit menu
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var menuEntries = [{
name: "Sync",
functionName: "sync"
}, {
name: "Setup",
functionName: "setup"
}, {
name: "Authorize",
functionName: "authorize"
}];
ss.addMenu("Fitbit", menuEntries);
}
// function onInstall is called when the script is installed (obsolete?)
function onInstall() {
onOpen();
}
Problem solved with updated code at https://github.com/loghound/Fitbit-for-Google-App-Script

Resources