<commit_before>/**
 * @module  app
 * @author 	Flavio De Stefano <flavio.destefano@caffeinalab.com>
 */

/**
 * @property config
 * @property {Boolean} [config.enqueueRouteWithUniversalLink=true] 	Auto enqueue route with Universal link
 * @property {Boolean} [config.enqueueRouteWithDeepLink=true] 			Auto enqueue route with deep link
 */
exports.config = _.extend({
	enqueueRouteWithUniversalLink: true,
	enqueueRouteWithDeepLink: true,
}, Alloy.CFG.T ? Alloy.CFG.T.app : {});

var Util = require('T/util');
var Router = require('T/router');

/**
 * A static method used to convert a Universal link to a route
 * With its default implementation, the original incoming string is return.
 * You can override this function to get a different behaviour
 * @param  {String} url The URL
 * @return {String} The route
 */
exports.universalLinkToRoute = function(url) { return url; };

/**
 * A static method used to convert a Deep link to a route
 * With its default implementation, the original incoming string is return
 * You can override this function to get a different behaviour
 * @param  {String} url The URL
 * @return {String} The route
 */
exports.deepLinkToRoute = function(url) { return url; };

/**
 * Check if the first opening of the app.
 * Call {@link setFirstUse} to set the first use of the app.
 * @param {String} [prefix=""] A prefix to apply
 * @return {Boolean}
 */
exports.isFirstUse = function(prefix) {
	prefix = prefix || '';
	return !Ti.App.Properties.hasProperty('app.firstuse' + prefix);
};

/**
 * Set the app first usage date.
 * @param {String} [prefix=""] A prefix to apply
 * Use in conjunction with {@link isFirstUse}
 */
exports.setFirstUse = function(prefix) {
	prefix = prefix || '';
	Ti.App.Properties.setString('app.firstuse' + prefix, Util.now());
};

/**
 * Check on the App/Play store if new version of this app has been released.
 * If it is, a dialog is shown to update the app.
 * @param  {String} 		url
 * @param  {Function} 	versionCb
 * @param  {Function} 	successCb
 */
exports.notifyUpdate = function(url, versionCb, successCb) {
	if (!Ti.Network.online) return;

	if (url == null) {
		if (OS_IOS) {
			url = 'https://itunes.apple.com/lookup?bundleId=' + Ti.App.id;
		} else {
			return null;
		}
	}

	versionCb = versionCb || function(response) {
		if (OS_IOS) {
			return (response.results && response.results[0]) ? response.results[0].version : null;
		} else {
			return null;
		}
	};

	successCb = successCb || function(response) {
		Util.openInStore((function() {
			if (OS_IOS) return response.results[0].trackId;
			else return null;
		})() );
	};

	require('T/http').send({
		url: url,
		cache: false,
		format: 'json',
		success: function(response) {
			if (response == null || !_.isObject(response)) return;

			var new_version = versionCb(response);
			var version_compare = Util.compareVersions(new_version, Ti.App.version);

			Ti.API.info('Util: App store version is ' + new_version);
			Ti.API.info('Util: Current version is ' + Ti.App.version);

			if (version_compare > 0) {
				require('T/dialog').confirm(
				L('app_new_version_title', 'Update available'),
				String.format(L('app_new_version_message', 'A new version of %s is available: %s'), Ti.App.name, new_version), [
				{
					title: L('app_new_version_button_later', 'Later'),
					callback: function() {
						require('T/ga').trackEvent('updatedialog', 'later');
					}
				},
				{
					title: L('app_new_version_button_update', 'Update'),
					selected: true,
					callback: function() {
						successCb(response);
					}
				}
				]);
			}
		}
	});
};

//////////
// Init //
//////////

if (OS_IOS) {

	if (exports.config.enqueueRouteWithDeepLink) {
		// The "resume" event is to handle all incoming deep links
		Ti.App.addEventListener('resumed', function() {
			var url = Util.parseSchema();
			Ti.API.info('App: Resumed with schema <' + url + '>');

			if (url != null) {
				Router.go( exports.deepLinkToRoute(url) );
			}
		});
	}

	if (exports.config.enqueueRouteWithUniversalLink) {
		// This one "continueactivity.NSUserActivityTypeBrowsingWeb", handle Universal Links
		Ti.App.iOS.addEventListener('continueactivity', function(e) {
			if (e.activityType !== 'NSUserActivityTypeBrowsingWeb') return;
			if (e.webpageURL != null) {
				Router.enqueue( exports.universalLinkToRoute(e.webpageURL) );
			}
		});
	}

}

var url = Util.parseSchema();

if (url != null) {
	Ti.API.info('App: Started with schema <' + url + '>');

	if (exports.config.enqueueRouteWithDeepLink) {
		Router.enqueue( exports.deepLinkToRoute(url) );
	}
}
<commit_msg>Refactored doc for App<commit_after>/**
 * @module  app
 * @author 	Flavio De Stefano <flavio.destefano@caffeinalab.com>
 */

/**
 * @property config
 * @property {Boolean} [config.enqueueRouteWithUniversalLink=true] 	Auto enqueue route with Universal link
 * @property {Boolean} [config.enqueueRouteWithDeepLink=true] 			Auto enqueue route with deep link
 */
exports.config = _.extend({
	enqueueRouteWithUniversalLink: true,
	enqueueRouteWithDeepLink: true,
}, Alloy.CFG.T ? Alloy.CFG.T.app : {});

var Util = require('T/util');
var Router = require('T/router');

/**
 * A static method used to convert a Universal link to a route
 * With its default implementation, the original incoming string is return.
 * You can override this function to get a different behaviour
 * @param  {String} url The URL
 * @return {String} The route
 */
exports.universalLinkToRoute = function(url) { return url; };

/**
 * A static method used to convert a Deep link to a route
 * With its default implementation, the original incoming string is return
 * You can override this function to get a different behaviour
 * @param  {String} url The URL
 * @return {String} The route
 */
exports.deepLinkToRoute = function(url) { return url; };

/**
 * Check if the first opening of the app.
 * Call {@link setFirstUse} to set the first use of the app.
 * @param {String} [prefix=""] A prefix to apply
 * @return {Boolean}
 */
exports.isFirstUse = function(prefix) {
	prefix = prefix || '';
	return !Ti.App.Properties.hasProperty('app.firstuse' + prefix);
};

/**
 * Set the app first usage date.
 * @param {String} [prefix=""] A prefix to apply
 * Use in conjunction with {@link isFirstUse}
 */
exports.setFirstUse = function(prefix) {
	prefix = prefix || '';
	Ti.App.Properties.setString('app.firstuse' + prefix, Util.now());
};

/**
 * Check on the App/Play store (or on a your distributed URL) if new version of this app has been released.
 * If it is, a dialog is shown to prompt the user for the update.
 * On iOS, all three parameters are auto-generated based on the app ID to check against the App Store.
 * On Android, there's no a reliable method to check this on the Play Store, so you have to
 * specify it manually the URL (maybe on a server where you handle the current version) and the other two parameters.
 * For In-House applications or Development application, you have to do the same.
 * @param  {String} 		[url=null]					The URL to use to check for the update.
 * @param  {Function} 	[version_cb=null]			The function to call that handle the parsing of the response: it must returns the version.
 * @param  {Function} 	[success_cb=null]			The function to call when the user click: "Update"
 */
exports.notifyUpdate = function(url, version_cb, success_cb) {
	if (!Ti.Network.online) return;

	var HTTP = require('T/http');
	var Dialog = require('T/dialog');
	var GA = require('T/ga');

	if (url == null) {
		if (OS_IOS) {
			url = 'https://itunes.apple.com/lookup?bundleId=' + Ti.App.id;
		} else {
			return null;
		}
	}

	version_cb = version_cb || function(response) {
		if (OS_IOS) {
			return (response.results && response.results[0]) ? response.results[0].version : null;
		} else {
			return null;
		}
	};

	success_cb = success_cb || function(response) {
		Util.openInStore((function() {
			if (OS_IOS) return response.results[0].trackId;
			else return null;
		})() );
	};

	HTTP.send({
		url: url,
		cache: false,
		format: 'json',
		success: function(response) {
			if (response == null || !_.isObject(response)) return;

			var new_version = version_cb(response);
			var version_compare = Util.compareVersions(new_version, Ti.App.version);

			Ti.API.info('Util: App store version is ' + new_version);
			Ti.API.info('Util: Current version is ' + Ti.App.version);

			if (version_compare > 0) {
				var title = L('app_new_version_title', 'Update available');
				var message = String.format(L('app_new_version_message', 'A new version of %s is available: %s'), Ti.App.name, new_version);

				Dialog.confirm(title, message, [
				{
					title: L('app_new_version_button_later', 'Later'),
					callback: function() {
						GA.trackEvent('updatedialog', 'later');
					}
				},
				{
					title: L('app_new_version_button_update', 'Update'),
					selected: true,
					callback: function() {
						GA.trackEvent('updatedialog', 'doit');
						success_cb(response);
					}
				}
				]);
			}
		}
	});
};

//////////
// Init //
//////////

if (OS_IOS) {

	if (exports.config.enqueueRouteWithDeepLink) {
		// The "resume" event is to handle all incoming deep links
		Ti.App.addEventListener('resumed', function() {
			var url = Util.parseSchema();
			Ti.API.info('App: Resumed with schema <' + url + '>');

			if (url != null) {
				Router.go( exports.deepLinkToRoute(url) );
			}
		});
	}

	if (exports.config.enqueueRouteWithUniversalLink) {
		// This one "continueactivity.NSUserActivityTypeBrowsingWeb", handle Universal Links
		Ti.App.iOS.addEventListener('continueactivity', function(e) {
			if (e.activityType !== 'NSUserActivityTypeBrowsingWeb') return;
			if (e.webpageURL != null) {
				Router.enqueue( exports.universalLinkToRoute(e.webpageURL) );
			}
		});
	}

}

var url = Util.parseSchema();

if (url != null) {
	Ti.API.info('App: Started with schema <' + url + '>');

	if (exports.config.enqueueRouteWithDeepLink) {
		Router.enqueue( exports.deepLinkToRoute(url) );
	}
}
<|endoftext|>


<commit_before> angular.module('emission.main.diary.current', ['ui-leaflet',
                                                'ngCordova',
                                                'emission.services',
                                                'ionic',
                                                'emission.incident.posttrip.manual',
                                                'rzModule',
                                                'angularLocalStorage',
                                                'emission.plugin.logger'])

.controller('CurrMapCtrl', function($scope, Config, $state, $timeout, $ionicActionSheet,leafletData,
                                    Logger, $window, PostTripManualMarker, CommHelper, $http, storage, $ionicPlatform) {

  console.log("controller CurrMapCtrl called from current.js");
  var _map;
  var db = window.cordova.plugins.BEMUserCache;
  MANUAL_INCIDENT = "manual/incident";
  BACKGROUND_LOCATION = "background/location";
  INCIDENT_CONFIG = 'incident_config';
  $scope.mapCtrl = {};
  var directions = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"];

  $scope.diary = function() {
    console.log('diary', "in diary");
    $state.go("root.main.diary");
  };

  angular.extend($scope.mapCtrl, {
    defaults: {
    }
  });

  angular.extend($scope.mapCtrl.defaults, Config.getMapTiles());
  console.log("mapCtrl", $scope.mapCtrl);

  $scope.verticalSlider = {
    options: {
      floor:0,
      ceil: 7,
      vertical: true,
      showTicks: true,
      showSelectionBar: true,
      hideLimitLabels: true,
      translate: function(value) {
          if (value === 1) {
            return "Yesterday";
          } else if (value === 7) {
            return "Week ago";
          }
        return "";
      }
    }
  };

  var incident_value = storage.get(INCIDENT_CONFIG);
  if(incident_value !== null) {
    $scope.verticalSlider.value = incident_value;
  } else {
    $scope.verticalSlider.value = 1;
  }

  var fromIncidentDate = moment().subtract($scope.verticalSlider.value, 'd');

  $scope.$watch('verticalSlider.value', function(newVal, oldVal){
    storage.set(INCIDENT_CONFIG, newVal);
    incidentServerCalldata.from_local_date = CommHelper.moment2Localdate(moment().subtract(newVal, 'd'));
  }, true);

  var incidentServerCalldata = {
      from_local_date: CommHelper.moment2Localdate(fromIncidentDate),
      to_local_date: CommHelper.moment2Localdate(moment()),
      sel_region: null
  };

  var startTimeFn = function(ts) {
    var date = new Date(ts*1000);
    var hours = date.getHours();
    var minutes = date.getMinutes();
    var amOrPm = hours < 12 ? 'AM' : 'PM';
    hours = hours % 12;
    hours = hours ? hours : 12;
    minutes = minutes < 10 ? '0'+ minutes : minutes;
    return hours + ':' + minutes + ' ' + amOrPm;
  };

  var getSpeed = function(curr_lglat, last_lglat, curr_ts, last_ts) {
    var curr_latlng = L.latLng(curr_lglat[1],curr_lglat[0]);
    var last_latlng = L.latLng(last_lglat[1],last_lglat[0]);
    var meters = curr_latlng.distanceTo(last_latlng);
    time = moment(curr_ts).diff(moment(last_ts));
    var speed = Math.round(meters / time * 3.6); // mps to kmph
    Logger.log("Current Speed: " + speed);
    return speed;
  };

  var degreeToDirection = function(degree) {
    var index = Math.floor((degree / 45) + 0.5) % 8;
    return directions[index];
  };

  leafletData.getMap('current').then(function(map) {
    _map = map;
    _map.removeControl(_map.zoomControl);
  });

  var refreshTrip = function() {
    db.getAllSensorData(BACKGROUND_LOCATION).then(function(result) {
      $scope.$apply(function() {
        Logger.log("current location data" + JSON.stringify(result[0].data));
        var coordinates = result.map(function(locWrapper, index, locList) {
          return [locWrapper.data.longitude, locWrapper.data.latitude];
        });
        var both = [result[0].data.longitude, result[0].data.latitude];
        var last_both = [result[1].data.longitude, result[1].data.latitude];
        var curr_ts = result[0].data.ts;
        var last_ts = result[1].data.ts;
        var bearing = Math.round(result[0].data.bearing);
        $scope.startTime = startTimeFn(result[result.length - 1].data.ts);
        if(angular.isDefined(result[0].data.sensed_speed)) {
          $scope.currSpeedInKmh = Math.round(result[0].data.sensed_speed * 3.6);
        } else {
          if(curr_ts !== last_ts){
            $scope.currSpeedInKmh = getSpeed(both, last_both, curr_ts, last_ts);
          }
        }
        $scope.currentDirection = degreeToDirection(bearing);
        angular.extend($scope.mapCtrl, {
          defaults : {
            center: {
              lat: both[1],
              lng: both[0],
              zoom: 15
            }
          },
          markers: {
            hereMarker: {
              lat: both[1],
              lng: both[0],
              icon: {
                iconUrl: 'img/ic_navigation_black_24dp.png',
                iconSize: [40, 40],
                iconAnchor: [20, 20],
                popupAnchor: [0, 0],
                shadowSize: [0, 0],
                shadowAnchor: [0, 0]
              },
              iconAngle: bearing,
            }
          },
          geojson: {
            data: [
              {
                type: "LineString",
                coordinates: coordinates
              },
            ],
          },
        });
      });
    });
    console.log($scope.mapCtrl);
  };

  $scope.$on('leafletDirectiveMap.current.resize', function(event, data) {
        console.log("current/map received resize event, invalidating map size");
        data.leafletObject.invalidateSize();
  });

  var addIncidentLayer = function(stress, marker, map) {
    if(stress === 0) {
      marker.setStyle({color: 'green'});
    } else if (stress === 100) {
      marker.setStyle({color: 'red'});
    }
    map.addLayer(marker);
  };

  var addIncidents = function(incidents, _map) {
    incidents.forEach(function(incident) {
        latlng = {
            lat: incident.data.loc.coordinates[1],
            lng: incident.data.loc.coordinates[0]
        };
        var marker = L.circleMarker(latlng);
        addIncidentLayer(incident.data.stress, marker, _map);
      });
  };

  var getLocalIncidents = function() {
    db.getAllMessages(MANUAL_INCIDENT).then(function(incidents) {
      console.log("Incidents stored locally", incidents);
      addIncidents(incidents, _map);
    });
  };

  var getServerIncidents = function() {
      console.log(incidentServerCalldata);
      $http.post("https://e-mission.eecs.berkeley.edu/result/heatmap/incidents/local_date", incidentServerCalldata).then(function(res){
      console.log(res);
      if(res.data.incidents.length > 0) {
        addIncidents(res.data.incidents, _map);
      }
    }, function(error){
      console.log("Error when getting incidents");
      console.log(error);
    });
  };

  var marker;
  $scope.showIncidentSheet = function() {
    db.getAllSensorData(BACKGROUND_LOCATION).then(function(result) {
            both = [result[0].data.latitude, result[0].data.longitude];
            var ts = result[0].data.ts;
            var latlng = L.latLng(both);
            $scope.features = [];
            marker = L.circleMarker(latlng);
            console.log(marker);
            PostTripManualMarker.showSheet($scope.features, latlng, ts, marker, _map);
    })
    .catch(function(error) {
      console.log("error while getting map current from leafletData");
    });
  };

  $scope.$watch('features', function(newVal, oldVal){
    if(angular.isDefined(newVal)) {
      if(newVal.length === 1) {
        addIncidentLayer(newVal[0].properties.stress, marker, _map);
      }
    }
  }, true);

  var mapRunning;
  var gettingIncidents;
  var refreshTripLoop = function() {
    refreshTrip();
    mapRunning = setTimeout(refreshTripLoop, 30 * 1000); //refresh every 30 secs
    // on android, we read the location points every 30 secs by default
  };

  var getIncidentsLoop = function() {
    getServerIncidents();
    gettingIncidents = setTimeout(getIncidentsLoop, 5 * 60 * 1000); //refresh 5 minutes
    // refreshing more frequently would put a big load on the server
  };

  $scope.$on('$ionicView.enter', function() {
    refreshTripLoop();
    getIncidentsLoop();
  });

  $scope.$on('$ionicView.leave', function() {
    clearTimeout(mapRunning);
    clearTimeout(gettingIncidents);
  });

  $ionicPlatform.on("resume", function(event) {
    refreshTripLoop();
    getIncidentsLoop();
  });

  $ionicPlatform.on("pause", function(event) {
    clearTimeout(mapRunning);
    clearTimeout(gettingIncidents);
  });
  getLocalIncidents();

});
<commit_msg>Minor fixes to the current screen<commit_after> angular.module('emission.main.diary.current', ['ui-leaflet',
                                                'ngCordova',
                                                'emission.services',
                                                'ionic',
                                                'emission.incident.posttrip.manual',
                                                'rzModule',
                                                'angularLocalStorage',
                                                'emission.plugin.logger'])

.controller('CurrMapCtrl', function($scope, Config, $state, $timeout, $ionicActionSheet,leafletData,
                                    Logger, $window, PostTripManualMarker, CommHelper, $http, storage, $ionicPlatform) {

  Logger.log("controller CurrMapCtrl called from current.js");
  var _map;
  var db = window.cordova.plugins.BEMUserCache;
  MANUAL_INCIDENT = "manual/incident";
  BACKGROUND_LOCATION = "background/location";
  INCIDENT_CONFIG = 'incident_config';
  $scope.mapCtrl = {};
  var directions = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"];

  $scope.diary = function() {
    console.log('diary', "in diary");
    $state.go("root.main.diary");
  };

  angular.extend($scope.mapCtrl, {
    defaults: {
    }
  });

  angular.extend($scope.mapCtrl.defaults, Config.getMapTiles());
  Logger.log("mapCtrl", $scope.mapCtrl);

  $scope.verticalSlider = {
    options: {
      floor:0,
      ceil: 7,
      vertical: true,
      showTicks: true,
      showSelectionBar: true,
      hideLimitLabels: true,
      translate: function(value) {
          if (value === 1) {
            return "Yesterday";
          } else if (value === 7) {
            return "Week ago";
          }
        return "";
      }
    }
  };

  var incident_value = storage.get(INCIDENT_CONFIG);
  if(incident_value !== null) {
    $scope.verticalSlider.value = incident_value;
  } else {
    $scope.verticalSlider.value = 1;
  }

  var fromIncidentDate = moment().subtract($scope.verticalSlider.value, 'd');

  $scope.$watch('verticalSlider.value', function(newVal, oldVal){
    storage.set(INCIDENT_CONFIG, newVal);
    incidentServerCalldata.from_local_date = CommHelper.moment2Localdate(moment().subtract(newVal, 'd'));
  }, true);

  var incidentServerCalldata = {
      from_local_date: CommHelper.moment2Localdate(fromIncidentDate),
      to_local_date: CommHelper.moment2Localdate(moment()),
      sel_region: null
  };

  var startTimeFn = function(ts) {
    var date = new Date(ts*1000);
    var hours = date.getHours();
    var minutes = date.getMinutes();
    var amOrPm = hours < 12 ? 'AM' : 'PM';
    hours = hours % 12;
    hours = hours ? hours : 12;
    minutes = minutes < 10 ? '0'+ minutes : minutes;
    return hours + ':' + minutes + ' ' + amOrPm;
  };

  var getSpeed = function(curr_lglat, last_lglat, curr_ts, last_ts) {
    var curr_latlng = L.latLng(curr_lglat[1],curr_lglat[0]);
    var last_latlng = L.latLng(last_lglat[1],last_lglat[0]);
    var meters = curr_latlng.distanceTo(last_latlng);
    time = moment(curr_ts).diff(moment(last_ts));
    var speed = Math.round(meters / time * 3.6); // mps to kmph
    Logger.log("Current Speed: " + speed);
    return speed;
  };

  var degreeToDirection = function(degree) {
    var index = Math.floor((degree / 45) + 0.5) % 8;
    return directions[index];
  };

  leafletData.getMap('current').then(function(map) {
    _map = map;
    _map.removeControl(_map.zoomControl);
  });

  var refreshTrip = function() {
    db.getAllSensorData(BACKGROUND_LOCATION).then(function(result) {
      $scope.$apply(function() {
        Logger.log("current location data" + JSON.stringify(result[0].data));
        var coordinates = result.map(function(locWrapper, index, locList) {
          return [locWrapper.data.longitude, locWrapper.data.latitude];
        });
        var both = [result[0].data.longitude, result[0].data.latitude];
        $scope.startTime = startTimeFn(result[result.length - 1].data.ts);
        var bearing = Math.round(result[0].data.bearing);

        Logger.log("last location data " + JSON.stringify(result[1]));
        if (angular.isDefined(result[1])) {
            var last_both = [result[1].data.longitude, result[1].data.latitude];
            var curr_ts = result[0].data.ts;
            var last_ts = result[1].data.ts;
            if(angular.isDefined(result[0].data.sensed_speed)) {
              $scope.currSpeedInKmh = Math.round(result[0].data.sensed_speed * 3.6);
            } else {
              if(curr_ts !== last_ts){
                $scope.currSpeedInKmh = getSpeed(both, last_both, curr_ts, last_ts);
              }
            }
            $scope.currentDirection = degreeToDirection(bearing);
        } else {
            Logger.log("last location is not defined, returning defaults");
            $scope.currSpeedInKmh = 0;
        }
        angular.extend($scope.mapCtrl, {
          defaults : {
            center: {
              lat: both[1],
              lng: both[0],
              zoom: 15
            }
          },
          markers: {
            hereMarker: {
              lat: both[1],
              lng: both[0],
              icon: {
                iconUrl: 'img/ic_navigation_black_24dp.png',
                iconSize: [40, 40],
                iconAnchor: [20, 20],
                popupAnchor: [0, 0],
                shadowSize: [0, 0],
                shadowAnchor: [0, 0]
              },
              iconAngle: bearing,
            }
          },
          geojson: {
            data: [
              {
                type: "LineString",
                coordinates: coordinates
              },
            ],
          },
        });
      });
    });
    console.log($scope.mapCtrl);
  };

  $scope.$on('leafletDirectiveMap.current.resize', function(event, data) {
        Logger.log("current/map received resize event, invalidating map size");
        data.leafletObject.invalidateSize();
  });

  var addIncidentLayer = function(stress, marker, map) {
    if(stress === 0) {
      marker.setStyle({color: 'green'});
    } else if (stress === 100) {
      marker.setStyle({color: 'red'});
    }
    map.addLayer(marker);
  };

  var addIncidents = function(incidents, _map) {
    incidents.forEach(function(incident) {
        Logger.log("Processing incident "+JSON.stringify(incident));
        if (angular.isDefined(incident) && angular.isDefined(incident.loc)) {
            latlng = {
                lat: incident.loc.coordinates[1],
                lng: incident.loc.coordinates[0]
            };
            Logger.log("Displaying incident report at "+JSON.stringify(latlng)+" on map");
            var marker = L.circleMarker(latlng);
            addIncidentLayer(incident.stress, marker, _map);
        }
      });
  };

  var getLocalIncidents = function() {
    db.getAllMessages(MANUAL_INCIDENT).then(function(incidents) {
      Logger.log("Incidents stored locally", incidents);
      addIncidents(incidents, _map);
    });
  };

  var getServerIncidents = function() {
      Logger.log("Getting server incidents with call "+JSON.stringify(incidentServerCalldata));
      $http.post("https://e-mission.eecs.berkeley.edu/result/heatmap/incidents/local_date", incidentServerCalldata).then(function(res){
      Logger.log("Result is "+JSON.stringify(res));
      if(res.data.incidents.length > 0) {
        addIncidents(res.data.incidents, _map);
      }
    }, function(error){
      Logger.log("Error when getting incidents");
      Logger.log(error);
    });
  };

  var marker;
  $scope.showIncidentSheet = function() {
    db.getAllSensorData(BACKGROUND_LOCATION).then(function(result) {
            both = [result[0].data.latitude, result[0].data.longitude];
            var ts = result[0].data.ts;
            var latlng = L.latLng(both);
            $scope.features = [];
            marker = L.circleMarker(latlng);
            Logger.log(marker);
            PostTripManualMarker.showSheet($scope.features, latlng, ts, marker, _map);
    })
    .catch(function(error) {
      Logger.log("error while getting map current from leafletData");
    });
  };

  $scope.$watch('features', function(newVal, oldVal){
    if(angular.isDefined(newVal)) {
      if(newVal.length === 1) {
        addIncidentLayer(newVal[0].properties.stress, marker, _map);
      }
    }
  }, true);

  var mapRunning;
  var gettingIncidents;
  var refreshTripLoop = function() {
    refreshTrip();
    mapRunning = setTimeout(refreshTripLoop, 30 * 1000); //refresh every 30 secs
    // on android, we read the location points every 30 secs by default
  };

  var getIncidentsLoop = function() {
    getServerIncidents();
    gettingIncidents = setTimeout(getIncidentsLoop, 5 * 60 * 1000); //refresh 5 minutes
    // refreshing more frequently would put a big load on the server
  };

  $scope.$on('$ionicView.enter', function() {
    Logger.log("entered current screen, starting incident refresh");
    refreshTripLoop();
    getIncidentsLoop();
  });

  $scope.$on('$ionicView.leave', function() {
    Logger.log("exited current screen, stopping incident refresh");
    clearTimeout(mapRunning);
    clearTimeout(gettingIncidents);
  });

  $ionicPlatform.on("resume", function(event) {
    Logger.log("resumed current screen, starting incident refresh");
    refreshTripLoop();
    getIncidentsLoop();
  });

  $ionicPlatform.on("pause", function(event) {
    Logger.log("paused current screen, stopping incident refresh");
    clearTimeout(mapRunning);
    clearTimeout(gettingIncidents);
  });
  getLocalIncidents();

});
<|endoftext|>


<commit_before>models.Questions = {
	items: null,
	init: function() {
		var me = this;
		me.items = [
			{
				questionType: "A",
				question: {
					text: "Marko i Danijel su krenuli na put. Marko je vozio prvih 90 km a Danijel ostatak puta. Na povratku je Marko prvi vozio, a Danijel preuzeo posljednjih 100 km. Tko je vozio više?",
					a1: "Danijel",
					a2: "Marko",
					a3: "Jednako",
					a4: "Nema dovoljno informacija",
					correctAnswer: "a1"
				}
			},
			{
				questionType: "A",
				question: {
					text: "Imamo tri označene kutije, ali svaka kutija je krivo označena. U kutijama se nalaze: jabuke, banane, te jabuke i banane. Iz kutije sa kojom oznakom možemo izvući jedno voće kako bi ih znali pravilno označiti?",
					a1: "Jabuke",
					a2: "Banane",
					a3: "Jabuke i banane",
					a4: "Nije moguće odrediti",
					correctAnswer: "a3"
				}
			},
			{
				questionType: "A",
				question: {
					text: "U šumi zaborava lav laže svakog ponedeljka, utorka i srijede, a jednorog laže četvrtkom, petkom i subotom. Lav: Jučer sam lagao. Jednorog: I ja sam. Kada su ovo izjavili?",
					a1: "U srijedu",
					a2: "U nedelju",
					a3: "U četvrtak",
					a4: "U subotu",
					correctAnswer: "a3"
				}
			},
			{
				questionType: "A",
				question: {
					text: "Pokvareni sat gubi 24 minute svakog sata. Sada pokazuje 03:00 h, a znamo da je bio točan u ponoć. Ako je sat prestao raditi prije jedan sat, koliko je sada sati?",
					a1: "05:35 h",
					a2: "05:25 h",
					a3: "05:00 h",
					a4: "06:00 h",
					correctAnswer: "a4"
				}
			},
			{
				questionType: "A",
				question: {
					text: "Question 5",
					a1: "Answer 1",
					a2: "Answer 2",
					a3: "Answer 3",
					a4: "Answer 4",
					correctAnswer: "a1"
				}
			},
			{
				questionType: "A",
				question: {
					text: "Question 6",
					a1: "Answer 1",
					a2: "Answer 2",
					a3: "Answer 3",
					a4: "Answer 4",
					correctAnswer: "a2"
				}
			},
			{
				questionType: "A",
				question: {
					text: "Question 7",
					a1: "Answer 1",
					a2: "Answer 2",
					a3: "Answer 3",
					a4: "Answer 4",
					correctAnswer: "a3"
				}
			},
			{
				questionType: "A",
				question: {
					text: "Question 8",
					a1: "Answer 1",
					a2: "Answer 2",
					a3: "Answer 3",
					a4: "Answer 4",
					correctAnswer: "a4"
				}
			},
			{
				questionType: "A",
				question: {
					text: "Question 9",
					a1: "Answer 1",
					a2: "Answer 2",
					a3: "Answer 3",
					a4: "Answer 4",
					correctAnswer: "a1"
				}
			},
			{
				questionType: "B",
				question: {
					text: "Maja i Emil imaju nekoliko jabuka. Ako Emil da Maji jabuku oboje će imati jednak broj jabuka. Ako Maja da Emilu jabuku, on će imati duplo više jabuka od nje. Koliko jabuka ima Emil?",
					correctAnswer: "7"
				}
			},
			{
				questionType: "B",
				question: {
					text: "Ana je u laboratoriju napravila smjesu koja je teska 20 kg i sadrži 90% vode. Idući dan je smjesa imala 50% vode. Koliko je kg smjesa sada teška ako dio smjese koji ne sadrži vodu nije promijenjen?",
					correctAnswer: "12"
				}
			},
			{
				questionType: "B",
				question: {
					text: "Quest B3",
					correctAnswer: "3"
				}
			},
			{
				questionType: "B",
				question: {
					text: "Quest B4",
					correctAnswer: "4"
				}
			},
			{
				questionType: "B",
				question: {
					text: "Quest B5",
					correctAnswer: "5"
				}
			},
			{
				questionType: "B",
				question: {
					text: "Quest B6",
					correctAnswer: "6"
				}
			},
			{
				questionType: "B",
				question: {
					text: "Quest B7",
					correctAnswer: "7"
				}
			},
			{
				questionType: "B",
				question: {
					text: "Quest B8",
					correctAnswer: "8"
				}
			},
			{
				questionType: "B",
				question: {
					text: "Quest B9",
					correctAnswer: "9"
				}
			}
		]
	},
	getAllQuestions: function() {
		var me = this;
		return me.items;
	}
}
<commit_msg>Update Questions.js<commit_after>models.Questions = {
	items: null,
	init: function() {
		var me = this;
		me.items = [
			{
				questionType: "A",
				question: {
					text: "Marko i Danijel su krenuli na put. Marko je vozio prvih 90 km a Danijel ostatak puta. Na povratku je Marko prvi vozio, a Danijel preuzeo posljednjih 100 km. Tko je vozio više?",
					a1: "Danijel",
					a2: "Marko",
					a3: "Jednako",
					a4: "Nema dovoljno informacija",
					correctAnswer: "a1"
				}
			},
			{
				questionType: "A",
				question: {
					text: "Imamo tri označene kutije, ali svaka kutija je krivo označena. U kutijama se nalaze: jabuke, banane, te jabuke i banane. Iz kutije sa kojom oznakom možemo izvući jedno voće kako bi ih znali pravilno označiti?",
					a1: "Jabuke",
					a2: "Banane",
					a3: "Jabuke i banane",
					a4: "Nije moguće odrediti",
					correctAnswer: "a3"
				}
			},
			{
				questionType: "A",
				question: {
					text: "U šumi zaborava lav laže svakog ponedeljka, utorka i srijede, a jednorog laže četvrtkom, petkom i subotom. Lav: Jučer sam lagao. Jednorog: I ja sam. Kada su ovo izjavili?",
					a1: "U srijedu",
					a2: "U nedelju",
					a3: "U četvrtak",
					a4: "U subotu",
					correctAnswer: "a3"
				}
			},
			{
				questionType: "A",
				question: {
					text: "Pokvareni sat gubi 24 minute svakog sata. Sada pokazuje 03:00 h, a znamo da je bio točan u ponoć. Ako je sat prestao raditi prije jedan sat, koliko je sada sati?",
					a1: "05:35 h",
					a2: "05:25 h",
					a3: "05:00 h",
					a4: "06:00 h",
					correctAnswer: "a4"
				}
			},
			{
				questionType: "A",
				question: {
					text: "Question 5",
					a1: "Answer 1",
					a2: "Answer 2",
					a3: "Answer 3",
					a4: "Answer 4",
					correctAnswer: "a1"
				}
			},
			{
				questionType: "A",
				question: {
					text: "Question 6",
					a1: "Answer 1",
					a2: "Answer 2",
					a3: "Answer 3",
					a4: "Answer 4",
					correctAnswer: "a2"
				}
			},
			{
				questionType: "A",
				question: {
					text: "Question 7",
					a1: "Answer 1",
					a2: "Answer 2",
					a3: "Answer 3",
					a4: "Answer 4",
					correctAnswer: "a3"
				}
			},
			{
				questionType: "A",
				question: {
					text: "Question 8",
					a1: "Answer 1",
					a2: "Answer 2",
					a3: "Answer 3",
					a4: "Answer 4",
					correctAnswer: "a4"
				}
			},
			{
				questionType: "A",
				question: {
					text: "Question 9",
					a1: "Answer 1",
					a2: "Answer 2",
					a3: "Answer 3",
					a4: "Answer 4",
					correctAnswer: "a1"
				}
			},
			{
				questionType: "B",
				question: {
					text: "Maja i Emil imaju nekoliko jabuka. Ako Emil da Maji jabuku oboje će imati jednak broj jabuka. Ako Maja da Emilu jabuku, on će imati duplo više jabuka od nje. Koliko jabuka ima Emil?",
					correctAnswer: "7"
				}
			},
			{
				questionType: "B",
				question: {
					text: "Ana je u laboratoriju napravila smjesu koja je teska 20 kg i sadrži 90% vode. Idući dan je smjesa imala 50% vode. Koliko je kg smjesa sada teška ako dio smjese koji ne sadrži vodu nije promijenjen?",
					correctAnswer: "12"
				}
			},
			{
				questionType: "B",
				question: {
					text: "Koji je broj 5 puta veći od zbroja svojih znamenaka?",
					correctAnswer: "45"
				}
			},
			{
				questionType: "B",
				question: {
					text: "Ove je godine jedan četvrti razred srednje škole pokazao izuzetan interes za strane jezike. Od 30 učenika u razredu samo dvoje nije odabralo dodatni izborni jezik. Od preostalih učenika 14 ih je odabralo talijanski kao dodatni predmet, a 22 španjolski. Može li se iz toga zaključiti koliko je učenika izabralo čak dva jezika kao izborni predmet?",
					correctAnswer: "8"
				}
			},
			{
				questionType: "B",
				question: {
					text: "Gospodin Lovrić kupio je novi alarm za kuću. Šifra ima pet znamenaka, a za slučaj da zaborave šifru, on je svojim ukućanima dao pet tragova: Zbroj petog i trećeg broja je 14, četvrti broj je za jedan veći od drugog, Prvi broj je za jedan manji od drugog pomnoženog s dva, zbroj drugog i trećeg je deset, zbroj svih brojeva je 30.",
					correctAnswer: "74658"
				}
			},
			{
				questionType: "B",
				question: {
					text: "U svakoj velikoj kutiji nalazi se toliko malih kutija koliko ukupno ima velikih kutija. Koliko ima velikih kutija, ako ukupno imamo 870 kutija?",
					correctAnswer: "29"
				}
			},
			{
				questionType: "B",
				question: {
					text: "Netko je upitao stočara na sajmu: - Koliko imate ovaca u svom stadu. On je odgovorio: - Danas sam kupio 40 ovaca i sada ih je tri puta više nego što ih je bilo prije toga. Koliko ovaca ima stočar?",
					correctAnswer: "60"
				}
			},
			{
				questionType: "B",
				question: {
					text: "Jučer je, u 4.e razredu, broj učenika koji su bili na nastavi bio 4 puta veći od broja učenika koji su ostali kod kuće radi gripe. Danas se jedan učenik vratio na nastavu, pa je broj učenika na nastavi bio 5 puta veći od broja odsutnih. Koliko je ukupno učenika u 4.e razredu?",
					correctAnswer: "30"
				}
			},
			{
				questionType: "B",
				question: {
					text: "Dok je mama kupovala ljekove u ljekarni, njezine tri kćeri zabavljale su se vagajući se zajedno na medicinskoj vagi. Naposljetku su sve zajedno stale na vagu. Koliko kilograma imaju sve tri zajedno ako su rezultati njihova vaganja bili ovakvi: Ana i Dora zajedno imaju 18kg, Tea i Ana imaju zajedno 21kg, Tea i Dora imaju zajedno 25kg.",
					correctAnswer: "32"
				}
			}
		]
	},
	getAllQuestions: function() {
		var me = this;
		return me.items;
	}
}
<|endoftext|>


<commit_before>// Top-level container object for this js file.
var NER = {};

// "nodes" is a table of entity names, mapping to an array position generated
// uniquely by the "counter" variable.  Once the table is complete, the nodes
// table can be recast into an array.
NER.nodes = {};
NER.links = {};
NER.counter = 0;

// This count will signal when the last ajax request has completed, and graph
// assembly can continue.
NER.num_files = 0;
NER.files_processed = 0;

function assembleGraph(){
    // Create a graph object.
    var g = {};

    // Copy the links over into an array within the graph object.
    g.links = [];
    $.each(NER.links, function(k, v){
        g.links.push(v);
    });

    // Do the same for the nodes, but do two additional things:
    //
    // 1. When extracting an object from the NER.nodes table, remove the "index"
    //    property, as it will no longer be needed after final placement of the
    //    node.
    //
    // 2. Place the node object into the place in the array indexed by that
    //    "index" property.  This ensures that the references in the link list
    //    are to the proper nodes.
    //
    // Start by creating an empty array of length equal to the number of total
    // entities.
    g.nodes = Array(Object.keys(NER.nodes).length);

    // Now plop each entity into its proper place.
    $.each(NER.nodes, function(k, v){
        var i = v.index;
        delete v.index;
        g.nodes[i] = v;
    });

    return g;
}

function renderGraph(g){
    //console.log(JSON.stringify(g));

    var width = 1000,
        height = 1000;

    var color = d3.scale.category20();

    var force = d3.layout.force()
        .charge(-120)
        .linkDistance(30)
        .size([width, height]);

    var svg = d3.select("#graph").append("svg")
        .attr("width", width)
        .attr("height", height);
    var stroke_width = 3;
    svg.append("rect")
        .attr("x", 0.5*stroke_width)
        .attr("y", 0.5*stroke_width)
        .attr("rx", 10)
        .attr("ry", 10)
        .attr("width", width - stroke_width)
        .attr("height", height - stroke_width)
        .style("fill-opacity", 0.1)
        .style("stroke", "black")
        .style("stroke-width", stroke_width);

    force
        .nodes(g.nodes)
        .links(g.links)
        .start();

    var link = svg.selectAll("line.link")
        .data(g.links)
      .enter().append("line")
        .attr("class", "link")
        .style("stroke-width", function(d) { return Math.sqrt(d.count); });

    var node = svg.selectAll("circle.node")
        .data(g.nodes)
      .enter().append("circle")
        .attr("class", "node")
        .attr("r", 5) // TODO(choudhury): make the radius dependent on the node count.
        .style("fill", function(d) { return color(d.type); })
        .call(force.drag);

    node.append("title")
        .text(function(d) { return d.node; }); // TODO(choudhury): the field "node" should be renamed to "name".

    force.on("tick", function(){
        link.attr("x1", function(d) { return d.source.x; })
            .attr("y1", function(d) { return d.source.y; })
            .attr("x2", function(d) { return d.target.x; })
            .attr("y2", function(d) { return d.target.y; });

        node.attr("cx", function(d) { return d.x; })
            .attr("cy", function(d) { return d.y; });

    });
}

function handleFileSelect(evt){
    // Grab the list of files selected by the user.
    var files = evt.target.files;

    // Compute how many of these files will actually be processed for named
    // entities (see comment below for explanation of how the files are vetted).
    NER.num_files = 0;
    $.each(files, function(k, v){
        if(v.type == '(n/a)' || v.type.slice(0,5) == 'text/'){
            NER.num_files++;
        }
    });
    console.log(NER.num_files + " files to process");

    // Now run through the files, using a callback to load the content from the
    // proper ones and pass it to an ajax call to perform named-entity
    // recognition.
    var output = [];
    for(var i=0; i<files.length; i++){
        var f = files[i];

        // Decide whether to process a selected file or not - accept everything
        // with a mime-type of text/*, as well as those with unspecified type
        // (assume the user knows what they are doing in such a case).
        var using = null;
        if(f.type == '(n/a)'){
            status = "accepted";
            msg = "ok, assuming text";
            using = true;
        }
        else if(f.type.slice(0,5) == 'text/'){
            status = "accepted";
            msg = "ok";
            using = true;
        }
        else{
            status = "rejected";
            msg = "rejected";
            using = false;
        }
        output.push('
', escape(f.name), ' (', f.type || 'n/a', ') - ', f.size, ' bytes ', f.type == 'text/plain' ? '(ok)' : '(rejected)');

        if(using){
            var reader = new FileReader();
            reader.onload = (function(file){
                return function(e){
                    var filename = escape(file.name);
                    console.log(filename);

                    // Grab the text of the file.
                    var text = e.target.result;

                    // Create a "progress" bullet point describing the current
                    // AJAX state of this file.
                    var elem = document.createElement("li");
                    elem.innerHTML = "processing " + filename;
                    elem.setAttribute("id", filename.replace(".","-"));
                    elem.setAttribute("class", "processing inprogress");
                    $("#blobs").get(0).appendChild(elem);

                    // Fire an AJAX call to retrieve the named entities in the
                    // document.
                    $.ajax({
                        url: '/service/NER',
                        data: {
                            text: text
                        },
                        dataType: 'text',
                        success: function(data){
                            console.log("success for " + filename);
                            $("#" + filename.replace(".","-")).removeClass("inprogress").addClass("done").get(0).innerHTML = filename + " processed";

                            // Create an entry for the document itself.
                            NER.nodes[filename] = {
                                node: filename,
                        type: "DOCUMENT",
                        count: 1,
                        index: NER.counter++
                            };
                            var doc_index = NER.counter - 1;

                            // Extract the JSON object from the AJAX response.
                            var entities = $.parseJSON(data);

                            // Process the entities.
                            $.each(entities, function(i, e){
                                // Place the entity into the global entity list
                                // if not already there.
                                //
                                // Also update the count of this entity.
                                var key = '["' + e[0] + '","' + e[1] + '"]';
                                if(!NER.nodes.hasOwnProperty(key)){
                                    NER.nodes[key] = {
                                        node: e[1],
                                type: e[0],
                                count: 1,
                                index: NER.counter++
                                    }
                                }
                                else{
                                    NER.nodes[key].count++;
                                }
                                var entity_index = NER.nodes[key].index;

                                // Enter a link into the link list, or just
                                // increase the count if the link exists
                                // already.
                                var link = "(" + entity_index + "," + doc_index + ")";
                                if(!NER.links.hasOwnProperty(link)){
                                    NER.links[link] = {
                                        source: entity_index,
                                        target: doc_index,
                                        count: 1
                                    };
                                }
                                else{
                                    NER.links[link].count++;
                                }
                            });

                            //console.log(NER.nodes);

                            // Increment the number of successfully processed
                            // files; if the number reaches the number of total
                            // files to process, launch the final step of
                            // assembling the graph.
                            ++NER.files_processed;
                            console.log(NER.files_processed + " of " + NER.num_files + " processed");

                            if(NER.files_processed == NER.num_files){
                                console.log("calling assembleGraph()");
                                var graph = assembleGraph();
                                renderGraph(graph);
                            }
                        },
                        error: function(){
                            console.log("error for " + filename);
                            $("#" + filename.replace(".","-")).removeClass("inprogress").addClass("failed").get(0).innerHTML = filename + " processed";
                        }
                    });
                }
            })(f);

            reader.readAsText(f);
        }
    }
    document.getElementById('file-info').innerHTML = '
' + output.join('') + '
';
}

window.onload = function(){
    document.getElementById('docs').addEventListener('change', handleFileSelect, false);
}
<commit_msg>broke ajax success callback out of inline position<commit_after>// Top-level container object for this js file.
var NER = {};

// "nodes" is a table of entity names, mapping to an array position generated
// uniquely by the "counter" variable.  Once the table is complete, the nodes
// table can be recast into an array.
NER.nodes = {};
NER.links = {};
NER.counter = 0;

// This count will signal when the last ajax request has completed, and graph
// assembly can continue.
NER.num_files = 0;
NER.files_processed = 0;

function assembleGraph(){
    // Create a graph object.
    var g = {};

    // Copy the links over into an array within the graph object.
    g.links = [];
    $.each(NER.links, function(k, v){
        g.links.push(v);
    });

    // Do the same for the nodes, but do two additional things:
    //
    // 1. When extracting an object from the NER.nodes table, remove the "index"
    //    property, as it will no longer be needed after final placement of the
    //    node.
    //
    // 2. Place the node object into the place in the array indexed by that
    //    "index" property.  This ensures that the references in the link list
    //    are to the proper nodes.
    //
    // Start by creating an empty array of length equal to the number of total
    // entities.
    g.nodes = Array(Object.keys(NER.nodes).length);

    // Now plop each entity into its proper place.
    $.each(NER.nodes, function(k, v){
        var i = v.index;
        delete v.index;
        g.nodes[i] = v;
    });

    return g;
}

function renderGraph(g){
    //console.log(JSON.stringify(g));

    var width = 1000,
        height = 1000;

    var color = d3.scale.category20();

    var force = d3.layout.force()
        .charge(-120)
        .linkDistance(30)
        .size([width, height]);

    var svg = d3.select("#graph").append("svg")
        .attr("width", width)
        .attr("height", height);
    var stroke_width = 3;
    svg.append("rect")
        .attr("x", 0.5*stroke_width)
        .attr("y", 0.5*stroke_width)
        .attr("rx", 10)
        .attr("ry", 10)
        .attr("width", width - stroke_width)
        .attr("height", height - stroke_width)
        .style("fill-opacity", 0.1)
        .style("stroke", "black")
        .style("stroke-width", stroke_width);

    force
        .nodes(g.nodes)
        .links(g.links)
        .start();

    var link = svg.selectAll("line.link")
        .data(g.links)
      .enter().append("line")
        .attr("class", "link")
        .style("stroke-width", function(d) { return Math.sqrt(d.count); });

    var node = svg.selectAll("circle.node")
        .data(g.nodes)
      .enter().append("circle")
        .attr("class", "node")
        .attr("r", 5) // TODO(choudhury): make the radius dependent on the node count.
        .style("fill", function(d) { return color(d.type); })
        .call(force.drag);

    node.append("title")
        .text(function(d) { return d.node; }); // TODO(choudhury): the field "node" should be renamed to "name".

    force.on("tick", function(){
        link.attr("x1", function(d) { return d.source.x; })
            .attr("y1", function(d) { return d.source.y; })
            .attr("x2", function(d) { return d.target.x; })
            .attr("y2", function(d) { return d.target.y; });

        node.attr("cx", function(d) { return d.x; })
            .attr("cy", function(d) { return d.y; });

    });
}

// This function can be called with a filename to *generate* an AJAX-success
// callback function to process the contents of some file.  The parameter passed
// into the generator is so that the callback has access to the name of the file
// being processed.
function processFileContents(filename){
    return function(data){
        console.log("success for " + filename);
        $("#" + filename.replace(".","-")).removeClass("inprogress").addClass("done").get(0).innerHTML = filename + " processed";

        // Create an entry for the document itself.
        NER.nodes[filename] = {
            node: filename,
            type: "DOCUMENT",
            count: 1,
            index: NER.counter++
        };
        var doc_index = NER.counter - 1;

        // Extract the JSON object from the AJAX response.
        var entities = $.parseJSON(data);

        // Process the entities.
        $.each(entities, function(i, e){
            // Place the entity into the global entity list
            // if not already there.
            //
            // Also update the count of this entity.
            var key = '["' + e[0] + '","' + e[1] + '"]';
            if(!NER.nodes.hasOwnProperty(key)){
                NER.nodes[key] = {
                    node: e[1],
            type: e[0],
            count: 1,
            index: NER.counter++
                }
            }
            else{
                NER.nodes[key].count++;
            }
            var entity_index = NER.nodes[key].index;

            // Enter a link into the link list, or just increase the count if
            // the link exists already.
            var link = "(" + entity_index + "," + doc_index + ")";
            if(!NER.links.hasOwnProperty(link)){
                NER.links[link] = {
                    source: entity_index,
                    target: doc_index,
                    count: 1
                };
            }
            else{
                NER.links[link].count++;
            }
        });

        //console.log(NER.nodes);

        // Increment the number of successfully processed
        // files; if the number reaches the number of total
        // files to process, launch the final step of
        // assembling the graph.
        ++NER.files_processed;
        console.log(NER.files_processed + " of " + NER.num_files + " processed");

        if(NER.files_processed == NER.num_files){
            console.log("calling assembleGraph()");
            var graph = assembleGraph();
            renderGraph(graph);
        }
    }
}

function handleFileSelect(evt){
    // Grab the list of files selected by the user.
    var files = evt.target.files;

    // Compute how many of these files will actually be processed for named
    // entities (see comment below for explanation of how the files are vetted).
    NER.num_files = 0;
    $.each(files, function(k, v){
        if(v.type == '(n/a)' || v.type.slice(0,5) == 'text/'){
            NER.num_files++;
        }
    });
    console.log(NER.num_files + " files to process");

    // Now run through the files, using a callback to load the content from the
    // proper ones and pass it to an ajax call to perform named-entity
    // recognition.
    var output = [];
    for(var i=0; i<files.length; i++){
        var f = files[i];

        // Decide whether to process a selected file or not - accept everything
        // with a mime-type of text/*, as well as those with unspecified type
        // (assume the user knows what they are doing in such a case).
        var using = null;
        if(f.type == '(n/a)'){
            status = "accepted";
            msg = "ok, assuming text";
            using = true;
        }
        else if(f.type.slice(0,5) == 'text/'){
            status = "accepted";
            msg = "ok";
            using = true;
        }
        else{
            status = "rejected";
            msg = "rejected";
            using = false;
        }
        output.push('
', escape(f.name), ' (', f.type || 'n/a', ') - ', f.size, ' bytes ', f.type == 'text/plain' ? '(ok)' : '(rejected)');

        if(using){
            var reader = new FileReader();
            reader.onload = (function(file){
                return function(e){
                    var filename = escape(file.name);
                    console.log(filename);

                    // Grab the text of the file.
                    var text = e.target.result;

                    // Create a "progress" bullet point describing the current
                    // AJAX state of this file.
                    var elem = document.createElement("li");
                    elem.innerHTML = "processing " + filename;
                    elem.setAttribute("id", filename.replace(".","-"));
                    elem.setAttribute("class", "processing inprogress");
                    $("#blobs").get(0).appendChild(elem);

                    // TODO(choudhury): check to see if the file contents were
                    // already processed, by querying the database for the
                    // results.  If they are found, retrieve them directly; if
                    // not, fire the AJAX call below (but db cache the result
                    // when it finishes!).

                    // Fire an AJAX call to retrieve the named entities in the
                    // document.
                    $.ajax({
                        url: '/service/NER',
                        data: {
                            text: text
                        },
                        dataType: 'text',
                        success: processFileContents(filename),
                        error: function(){
                            console.log("error for " + filename);
                            $("#" + filename.replace(".","-")).removeClass("inprogress").addClass("failed").get(0).innerHTML = filename + " processed";
                        }
                    });
                }
            })(f);

            reader.readAsText(f);
        }
    }
    document.getElementById('file-info').innerHTML = '
' + output.join('') + '
';
}

window.onload = function(){
    document.getElementById('docs').addEventListener('change', handleFileSelect, false);
}
<|endoftext|>


<commit_before>module.exports = {
  siteMetadata: {
    title: "DAN NATE - Web Developer",
    author: "Dan Nate",
    description: "Freelancer"
  },
  plugins: [
    'gatsby-plugin-react-helmet',
    {
      resolve: 'gatsby-plugin-google-analytics',
      options: {
        trackingId: "UA-144720509-1",
      }
    },
    {
      resolve: 'gatsby-source-filesystem',
      options: {
        path: `${__dirname}/src/pages`,
        name: 'pages',
      }
    },

      resolve: `gatsby-plugin-manifest`,
      options: {
        name: 'gatsby-starter-default',
        short_name: 'starter',
        start_url: '/',
        background_color: '#663399',
        theme_color: '#663399',
        display: 'minimal-ui',
        icon: 'src/images/gatsby-icon.png', // This path is relative to the root of the site.
      },
    },
    'gatsby-plugin-sass',
    'gatsby-plugin-offline',
    'gatsby-transformer-remark',
  ],
}
<commit_msg>Analytics :D<commit_after>module.exports = {
  siteMetadata: {
    title: "DAN NATE - Web Developer",
    author: "Dan Nate",
    description: "Freelancer"
  },
  plugins: [
    'gatsby-plugin-react-helmet',
    {
      resolve: 'gatsby-plugin-google-analytics',
      options: {
        trackingId: "UA-144720509-1",
      }
    },
    {
      resolve: 'gatsby-source-filesystem',
      options: {
        path: `${__dirname}/src/pages`,
        name: 'pages',
      }
    },
    {
      resolve: `gatsby-plugin-manifest`,
      options: {
        name: 'gatsby-starter-default',
        short_name: 'starter',
        start_url: '/',
        background_color: '#663399',
        theme_color: '#663399',
        display: 'minimal-ui',
        icon: 'src/images/gatsby-icon.png', // This path is relative to the root of the site.
      },
    },
    'gatsby-plugin-sass',
    'gatsby-plugin-offline',
    'gatsby-transformer-remark',
  ],
}
<|endoftext|>


<commit_before>module.exports = {
  siteMetadata: {
    title: "Yanglin Zhao"
  },
  plugins: [
    // Sources
    {
      resolve: "gatsby-source-filesystem",
      options: {
        name: "images",
        path: `${__dirname}/src/images`
      }
    },
    {
      resolve: "gatsby-source-filesystem",
      options: {
        name: "pages",
        path: `${__dirname}/src/pages`
      }
    },
    {
      resolve: "gatsby-source-filesystem",
      options: {
        name: "posts",
        path: `${__dirname}/src/posts`
      }
    },

    // Plugins
    "gatsby-plugin-react-helmet",
    "gatsby-plugin-sharp",
    "gatsby-transformer-remark",

    // Transformers
    "gatsby-transformer-sharp",
    {
      resolve: "gatsby-transformer-remark"
    }
  ]
};
<commit_msg>Add sass plugin<commit_after>module.exports = {
  siteMetadata: {
    title: "Yanglin Zhao"
  },
  plugins: [
    // Sources
    {
      resolve: "gatsby-source-filesystem",
      options: {
        name: "images",
        path: `${__dirname}/src/images`
      }
    },
    {
      resolve: "gatsby-source-filesystem",
      options: {
        name: "pages",
        path: `${__dirname}/src/pages`
      }
    },
    {
      resolve: "gatsby-source-filesystem",
      options: {
        name: "posts",
        path: `${__dirname}/src/posts`
      }
    },

    // Plugins
    "gatsby-plugin-react-helmet",
    "gatsby-plugin-sharp",
    "gatsby-transformer-remark",
    {
      resolve: `gatsby-plugin-sass`,
      options: {
        includePaths: [`${__dirname}/src`]
      }
    },

    // Transformers
    "gatsby-transformer-sharp",
    {
      resolve: "gatsby-transformer-remark"
    }
  ]
};
<|endoftext|>


<commit_before>const config = require('config')

const siteMetadata = config.util.loadFileConfigs()

module.exports = {
  siteMetadata,
  plugins: [
    'gatsby-plugin-react-helmet',
    {
      resolve: 'gatsby-source-filesystem',
      options: {
        name: 'post',
        path: `${__dirname}/contents`,
      },
    },
    {
      resolve: "gatsby-transformer-remark",
      options: {
        plugins: [
          {
            resolve: 'gatsby-remark-highlights',
            options: {
                scopePrefix: 'syntax--',
                codeWrap: {
                  className: 'highlight'
                },
              },
          },
        ],
      }
    },
    {
      resolve: "gatsby-plugin-nprogress",
      options: {
        // color: config.themeColor
      },
    },
  ]
}
<commit_msg>feat: :wrench: Set default color of nprogress<commit_after>const config = require('config')

const siteMetadata = config.util.loadFileConfigs()

module.exports = {
  siteMetadata,
  plugins: [
    'gatsby-plugin-react-helmet',
    {
      resolve: 'gatsby-source-filesystem',
      options: {
        name: 'post',
        path: `${__dirname}/contents`,
      },
    },
    {
      resolve: 'gatsby-transformer-remark',
      options: {
        plugins: [
          {
            resolve: 'gatsby-remark-highlights',
            options: {
                scopePrefix: 'syntax--',
                codeWrap: {
                  className: 'highlight'
                },
              },
          },
        ],
      }
    },
    {
      resolve: 'gatsby-plugin-nprogress',
      options: {
        color: '#366df0',
      }
    }
  ]
}
<|endoftext|>


<commit_before><commit_msg>change checking enviroment on pixelId<commit_after><|endoftext|>


<commit_before>var fs = require('fs');
var awsRegionTableParser = require('./index.js');

awsRegionTableParser.get().then(function(servicesAndRegions) {
  fs.writeFileSync('./data/parseddata.json', JSON.stringify(servicesAndRegions, null, 2), 'utf8');

  // TODO: clean this up
  const services = Object.values(servicesAndRegions.services);
  const edgeLocations = servicesAndRegions.edgeLocations;
  const regionalEdgeCaches = servicesAndRegions.regionalEdgeCaches;

  const regions = services[0];

  let READMEheader = `### ${services.length} Services\n`;
  READMEheader += `### ${edgeLocations.length} Edge Locations\n`;
  READMEheader += `### ${regionalEdgeCaches.length} Regional Edge Caches\n\n`;
  READMEheader += `| | ${Object.keys(regions).join(' | ')} |\n`;
  READMEheader += `| ------------- | ${Object.keys(regions).fill('-------------').join(' | ')}|`;
  const READMErows = [];

  for (var value in servicesAndRegions.services) {
    const longServiceName = servicesAndRegions.serviceNames[value];
    const row = `${longServiceName}|${Object.values(servicesAndRegions.services[value]).join(' | ')}`;

    READMErows.push(row);
  }

  const READMEtext = `${READMEheader}\n${READMErows.join('\n')}`;

  fs.writeFileSync('./data/README.md', READMEtext, 'utf8');
});
<commit_msg>change README generation layout<commit_after>var fs = require('fs');
var awsRegionTableParser = require('./index.js');

awsRegionTableParser.get().then(function(servicesAndRegions) {
  fs.writeFileSync('./data/parseddata.json', JSON.stringify(servicesAndRegions, null, 2), 'utf8');

  // TODO: clean this up
  const services = Object.values(servicesAndRegions.services);
  const edgeLocations = servicesAndRegions.edgeLocations;
  const regionalEdgeCaches = servicesAndRegions.regionalEdgeCaches;

  const regions = services[0];

  let READMEheader = `### ${edgeLocations.length} Edge Locations\n`;
  READMEheader += `### ${regionalEdgeCaches.length} Regional Edge Caches\n`;
  READMEheader += `### ${services.length} Services\n\n`;
  READMEheader += `| | ${Object.keys(regions).join(' | ')} |\n`;
  READMEheader += `| ------------- | ${Object.keys(regions).fill('-------------').join(' | ')}|`;
  const READMErows = [];

  for (var value in servicesAndRegions.services) {
    const longServiceName = servicesAndRegions.serviceNames[value];
    const row = `${longServiceName}|${Object.values(servicesAndRegions.services[value]).join(' | ')}`;

    READMErows.push(row);
  }

  const READMEtext = `${READMEheader}\n${READMErows.join('\n')}`;

  fs.writeFileSync('./data/README.md', READMEtext, 'utf8');
});
<|endoftext|>


<commit_before>"use strict";

function parsePR(url) {
  const match = url.match(/^https\:\/\/github.com\/([\w-]+\/[\w-]+\/pull\/[\d]+)/);
  return match && match[1];
}

const observer = {
  listeners: new Map(),

  emit(node) {
    if (node instanceof Element) {
      for (const [selector, listener] of observer.listeners) {
        node.querySelectorAll(selector).forEach(listener);
      }
    }
  },

  observe(mutations) {
    for (const record of mutations) {
      record.addedNodes.forEach(observer.emit);
    }
  },

  on(selector, listener) {
    if (!this.observer) {
      this.observer = new MutationObserver(this.observe);
      this.observer.observe(document, {childList: true, subtree: true});
    }

    this.listeners.set(selector, listener);
    document.querySelectorAll(selector).forEach(listener);
  },
};

observer.on("li.js-notification>span>svg.octicon-git-pull-request", a => {
  a.closest("li").classList.add("br-blind");
});

observer.on("li.js-issue-row>div>div>span>svg.octicon-git-pull-request", a => {
  a.closest("li").classList.add("br-blind");
});

observer.on("div.js-comment-container:first-child a.author", a => {
  const author = a.textContent;
  for (const x of document.querySelectorAll(`a[href="/${author}"],img[alt="@${author}"]`)) {
    x.style.visibility = "hidden";
  }
});

observer.on("div.pull-request-tab-content img.avatar, div.pull-request-tab-content a.commit-author", x => {
  x.style.visibility = "hidden";
});
<commit_msg>Optimize mutation observer, run listener once per match<commit_after>"use strict";

function parsePR(url) {
  const match = url.match(/^https\:\/\/github.com\/([\w-]+\/[\w-]+\/pull\/[\d]+)/);
  return match && match[1];
}

const observer = {
  listeners: new Map(),

  observe(mutations) {
    // Multiple events get coalesced when inserting nested nodes,
    // using a Set ensures we run the listener once per matched node.
    for (const [selector, listener] of observer.listeners) {
      const matched = new Set();

      for (const record of mutations) {
        for (const node of record.addedNodes) {
          if (node instanceof Element) {
            node.querySelectorAll(selector).forEach(m => matched.add(m));
          }
        }
      }
      matched.forEach(listener);
    }
  },

  on(selector, listener) {
    if (!this.observer) {
      this.observer = new MutationObserver(this.observe);
      this.observer.observe(document, {childList: true, subtree: true});
    }

    this.listeners.set(selector, listener);
    document.querySelectorAll(selector).forEach(listener);
  },
};

observer.on("li.js-notification>span>svg.octicon-git-pull-request", a => {
  a.closest("li").classList.add("br-blind");
});

observer.on("li.js-issue-row>div>div>span>svg.octicon-git-pull-request", a => {
  a.closest("li").classList.add("br-blind");
});

observer.on("div.js-comment-container:first-child a.author", a => {
  const author = a.textContent;
  for (const x of document.querySelectorAll(`a[href="/${author}"],img[alt="@${author}"]`)) {
    x.style.visibility = "hidden";
  }
});

observer.on("div.pull-request-tab-content img.avatar, div.pull-request-tab-content a.commit-author", x => {
  x.style.visibility = "hidden";
});
<|endoftext|>


<commit_before>module.exports = {
    local: {
        options: {
            options: { livereload: true }
        }
    },
    test: {
        options: {
            hostname: 'localhost',
            port: 7000
        }
    }
};<commit_msg>Ensuring server runs indefinitely with server command<commit_after>module.exports = {
    local: {
        options: {
            keepalive: true
        }
    },
    test: {
        options: {
            hostname: 'localhost',
            port: 7000
        }
    }
};<|endoftext|>


<commit_before>/* eslint-disable */

var path = require("path");
var webpack = require("webpack");

module.exports = {
  entry: [
    "babel-polyfill",
    "./index"
  ],
  output: {
    path: path.join(__dirname, "dist"),
    filename: "bundle.js",
    publicPath: "/dist/"
  },
  plugins: [
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.DefinePlugin({
      "process.env": {
        "NODE_ENV": JSON.stringify("production")
      }
    }),
    new webpack.optimize.UglifyJsPlugin({
      compressor: {
        warnings: false
      }
    })
  ],
  module: {
    loaders: [{
      test: /\.md$/,
      loader: "html-loader!markdown-loader?gfm=false"
    }, {
      test: /\.(js|jsx)$/,
      exclude: /node_modules/,
      loader: "babel-loader",
      query: {
        presets: ['es2015', 'react']
      }
    }, {
      test: /\.css$/,
      loader: "style-loader!css-loader"
    }, {
      test: /\.(png|jpg|gif)$/,
      loader: "url-loader?limit=8192"
    }, {
      test: /\.svg$/,
      loader: "url?limit=10000&mimetype=image/svg+xml"
    }]
  }
};
<commit_msg>Updated production config to fix SVG issues<commit_after>/* eslint-disable */

var path = require("path");
var webpack = require("webpack");

module.exports = {
  entry: [
    "babel-polyfill",
    "./index"
  ],
  output: {
    path: path.join(__dirname, "dist"),
    filename: "bundle.js",
    publicPath: "/dist/"
  },
  plugins: [
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.DefinePlugin({
      "process.env": {
        "NODE_ENV": JSON.stringify("production")
      }
    }),
    new webpack.optimize.UglifyJsPlugin({
      compressor: {
        warnings: false
      }
    })
  ],
  module: {
    loaders: [{
      test: /\.md$/,
      loader: "html-loader!markdown-loader?gfm=false"
    }, {
      test: /\.(js|jsx)$/,
      exclude: /node_modules/,
      loader: "babel-loader",
      query: {
        presets: ['es2015', 'react']
      }
    }, {
      test: /\.css$/,
      loader: "style-loader!css-loader"
    }, {
      test: /\.(png|jpg|gif)$/,
      loader: "url-loader?limit=8192"
    }, {
      test: /\.svg$/,
      loader: "file-loader?mimetype=image/svg+xml"
    }]
  }
};
<|endoftext|>


<commit_before>import BaseController from 'portia-web/controllers/base-controller';

export default BaseController.extend({
    breadCrumb: null,
    _breadCrumb: null,
});
<commit_msg>Use relative path for template<commit_after>import BaseController from '../base-controller';

export default BaseController.extend({
    breadCrumb: null,
    _breadCrumb: null,
});
<|endoftext|>


<commit_before>import Protocol from './protocol';
import Core from '../core';
import proplists from './erlang_compat/proplists';
import erlang from './erlang_compat/erlang';

function call_property(item, property) {
  if (!property) {
    if (item instanceof Function || typeof item === 'function') {
      return item();
    }

    return item;
  }

  if (item instanceof Map) {
    let prop = null;

    if (item.has(property)) {
      prop = property;
    } else if (item.has(Symbol.for(property))) {
      prop = Symbol.for(property);
    }

    if (prop === null) {
      throw new Error(`Property ${property} not found in ${item}`);
    }

    if (item.get(prop) instanceof Function || typeof item.get(prop) === 'function') {
      return item.get(prop)();
    }
    return item.get(prop);
  }

  let prop = null;

  if (
    typeof item === 'number' ||
    typeof item === 'symbol' ||
    typeof item === 'boolean' ||
    typeof item === 'string'
  ) {
    if (item[property] !== undefined) {
      prop = property;
    } else if (item[Symbol.for(property)] !== undefined) {
      prop = Symbol.for(property);
    }
  } else if (property in item) {
    prop = property;
  } else if (Symbol.for(property) in item) {
    prop = Symbol.for(property);
  }

  if (prop === null) {
    throw new Error(`Property ${property} not found in ${item}`);
  }

  if (item[prop] instanceof Function || typeof item[prop] === 'function') {
    return item[prop]();
  }
  return item[prop];
}

function defprotocol(spec) {
  return new Protocol(spec);
}

function defimpl(protocol, type, impl) {
  protocol.implementation(type, impl);
}

function build_namespace(ns, ns_string) {
  let parts = ns_string.split('.');
  const root = ns;
  let parent = ns;

  if (parts[0] === 'Elixir') {
    parts = parts.slice(1);
  }

  for (const part of parts) {
    if (typeof parent[part] === 'undefined') {
      parent[part] = {};
    }

    parent = parent[part];
  }

  root.__table__ = ns.__table__ || {};
  root.__table__[Symbol.for(ns_string)] = parent;

  return parent;
}

//TODO: Revisit performance of .toString() in tight loop
function map_to_object(map, options = []) {
  const opt_keys = proplists.get_value(Symbol.for('keys'), options);
  const opt_symbols = proplists.get_value(Symbol.for('symbols'), options);

  const object = {};

  for (let [key, value] of map.entries()) {
    if (opt_keys === Symbol.for('string') && typeof key === 'number') {
      key = key.toString();
    } else if (
      (opt_keys === Symbol.for('string') || opt_symbols !== Symbol.for('undefined'))
      && typeof key === 'symbol'
    ) {
      key = erlang.atom_to_binary(key);
    }

    if (value instanceof Map) {
      object[key] = map_to_object(value, options);
    } else if (opt_symbols !==  Symbol.for('undefined') && typeof value === 'symbol') {
      object[key] = erlang.atom_to_binary(value);
    } else {
      object[key] = value;
    }
  }

  return object;
}

class Recurse {
  constructor(func) {
    this.func = func;
  }
}

function trampoline(f) {
  let currentValue = f;

  while (currentValue && currentValue instanceof Recurse) {
    currentValue = currentValue.func();
  }

  return currentValue;
}

function split_at(value, position) {
  if (position < 0) {
    const newPosition = value.length + position;
    if (newPosition < 0) {
      return new Core.Tuple('', value);
    }

    return split_at(value, newPosition);
  }

  let first = '';
  let second = '';
  let index = 0;

  for (const character of value) {
    if (index < position) {
      first += character;
    } else {
      second += character;
    }

    index += 1;
  }

  return new Core.Tuple(first, second);
}

export default {
  call_property,
  defprotocol,
  defimpl,
  build_namespace,
  map_to_object,
  trampoline,
  Recurse,
  split_at,
};<commit_msg>remove rogue comment<commit_after>import Protocol from './protocol';
import Core from '../core';
import proplists from './erlang_compat/proplists';
import erlang from './erlang_compat/erlang';

function call_property(item, property) {
  if (!property) {
    if (item instanceof Function || typeof item === 'function') {
      return item();
    }

    return item;
  }

  if (item instanceof Map) {
    let prop = null;

    if (item.has(property)) {
      prop = property;
    } else if (item.has(Symbol.for(property))) {
      prop = Symbol.for(property);
    }

    if (prop === null) {
      throw new Error(`Property ${property} not found in ${item}`);
    }

    if (item.get(prop) instanceof Function || typeof item.get(prop) === 'function') {
      return item.get(prop)();
    }
    return item.get(prop);
  }

  let prop = null;

  if (
    typeof item === 'number' ||
    typeof item === 'symbol' ||
    typeof item === 'boolean' ||
    typeof item === 'string'
  ) {
    if (item[property] !== undefined) {
      prop = property;
    } else if (item[Symbol.for(property)] !== undefined) {
      prop = Symbol.for(property);
    }
  } else if (property in item) {
    prop = property;
  } else if (Symbol.for(property) in item) {
    prop = Symbol.for(property);
  }

  if (prop === null) {
    throw new Error(`Property ${property} not found in ${item}`);
  }

  if (item[prop] instanceof Function || typeof item[prop] === 'function') {
    return item[prop]();
  }
  return item[prop];
}

function defprotocol(spec) {
  return new Protocol(spec);
}

function defimpl(protocol, type, impl) {
  protocol.implementation(type, impl);
}

function build_namespace(ns, ns_string) {
  let parts = ns_string.split('.');
  const root = ns;
  let parent = ns;

  if (parts[0] === 'Elixir') {
    parts = parts.slice(1);
  }

  for (const part of parts) {
    if (typeof parent[part] === 'undefined') {
      parent[part] = {};
    }

    parent = parent[part];
  }

  root.__table__ = ns.__table__ || {};
  root.__table__[Symbol.for(ns_string)] = parent;

  return parent;
}

function map_to_object(map, options = []) {
  const opt_keys = proplists.get_value(Symbol.for('keys'), options);
  const opt_symbols = proplists.get_value(Symbol.for('symbols'), options);

  const object = {};

  for (let [key, value] of map.entries()) {
    if (opt_keys === Symbol.for('string') && typeof key === 'number') {
      key = key.toString();
    } else if (
      (opt_keys === Symbol.for('string') || opt_symbols !== Symbol.for('undefined'))
      && typeof key === 'symbol'
    ) {
      key = erlang.atom_to_binary(key);
    }

    if (value instanceof Map) {
      object[key] = map_to_object(value, options);
    } else if (opt_symbols !==  Symbol.for('undefined') && typeof value === 'symbol') {
      object[key] = erlang.atom_to_binary(value);
    } else {
      object[key] = value;
    }
  }

  return object;
}

class Recurse {
  constructor(func) {
    this.func = func;
  }
}

function trampoline(f) {
  let currentValue = f;

  while (currentValue && currentValue instanceof Recurse) {
    currentValue = currentValue.func();
  }

  return currentValue;
}

function split_at(value, position) {
  if (position < 0) {
    const newPosition = value.length + position;
    if (newPosition < 0) {
      return new Core.Tuple('', value);
    }

    return split_at(value, newPosition);
  }

  let first = '';
  let second = '';
  let index = 0;

  for (const character of value) {
    if (index < position) {
      first += character;
    } else {
      second += character;
    }

    index += 1;
  }

  return new Core.Tuple(first, second);
}

export default {
  call_property,
  defprotocol,
  defimpl,
  build_namespace,
  map_to_object,
  trampoline,
  Recurse,
  split_at,
};<|endoftext|>


<commit_before>//     Create.js - On-site web editing interface
//     (c) 2011-2012 Henri Bergius, IKS Consortium
//     Create may be freely distributed under the MIT license.
//     For all details and documentation:
//     http://createjs.org/
(function (jQuery, undefined) {
  jQuery.widget('Midgard.midgardToolbar', {
    options: {
      display: 'full',
      statechange: function () {}
    },

    _create: function () {
      this.element.append(this._getMinimized());
      this.element.append(this._getFull());

      var widget = this;
      jQuery('.create-ui-toggle').click(function () {
        if (widget.options.display === 'full') {
          widget.hide();
          widget.options.display = 'minimized';
        } else {
          widget.show();
          widget.options.display = 'full';
        }
        widget._trigger('statechange', null, widget.options);
      });

      this._setDisplay(this.options.display);

      widget = this;

      jQuery(this.element).bind('midgardcreatestatechange', function (event, options) {
        if (options.state == 'browse') {
          widget._clearWorkflows();
        }
      });

      jQuery(this.element).bind('midgardworkflowschanged', function (event, options) {
        widget._clearWorkflows();
        if (options.workflows.length) {
          options.workflows.each(function (workflow) {
            html = jQuery('body').data().midgardWorkflows.prepareItem(options.instance, workflow, function (err, model) {
              widget._clearWorkflows();
              if (err) {
                return;
              }
            });
            jQuery('.create-ui-tool-workflowarea', this.element).append(html);
          });
        }
      });
    },

    _setOption: function (key, value) {
      if (key === 'display') {
        this._setDisplay(value);
      }
      this.options[key] = value;
    },

    _setDisplay: function (value) {
      if (value === 'minimized') {
        jQuery('div.create-ui-toolbar-wrapper').hide();
      }
    },

    hide: function () {
      jQuery('div.create-ui-toolbar-wrapper').fadeToggle('fast', 'linear');
    },

    show: function () {
      jQuery('div.create-ui-toolbar-wrapper').fadeToggle('fast', 'linear');
    },

    _getMinimized: function () {
      return jQuery('

');
    },

    _getFull: function () {
      return jQuery('

');
    },

    _clearWorkflows: function () {
      jQuery('.create-ui-tool-workflowarea', this.element).empty();
    }
  });
})(jQuery);
<commit_msg>Clear the metadata area as well<commit_after>//     Create.js - On-site web editing interface
//     (c) 2011-2012 Henri Bergius, IKS Consortium
//     Create may be freely distributed under the MIT license.
//     For all details and documentation:
//     http://createjs.org/
(function (jQuery, undefined) {
  jQuery.widget('Midgard.midgardToolbar', {
    options: {
      display: 'full',
      statechange: function () {}
    },

    _create: function () {
      this.element.append(this._getMinimized());
      this.element.append(this._getFull());

      var widget = this;
      jQuery('.create-ui-toggle').click(function () {
        if (widget.options.display === 'full') {
          widget.hide();
          widget.options.display = 'minimized';
        } else {
          widget.show();
          widget.options.display = 'full';
        }
        widget._trigger('statechange', null, widget.options);
      });

      this._setDisplay(this.options.display);

      widget = this;

      jQuery(this.element).bind('midgardcreatestatechange', function (event, options) {
        if (options.state == 'browse') {
          widget._clearWorkflows();
          widget._clearMetadata();
        }
      });

      jQuery(this.element).bind('midgardworkflowschanged', function (event, options) {
        widget._clearWorkflows();
        if (options.workflows.length) {
          options.workflows.each(function (workflow) {
            html = jQuery('body').data().midgardWorkflows.prepareItem(options.instance, workflow, function (err, model) {
              widget._clearWorkflows();
              if (err) {
                return;
              }
            });
            jQuery('.create-ui-tool-workflowarea', this.element).append(html);
          });
        }
      });
    },

    _setOption: function (key, value) {
      if (key === 'display') {
        this._setDisplay(value);
      }
      this.options[key] = value;
    },

    _setDisplay: function (value) {
      if (value === 'minimized') {
        jQuery('div.create-ui-toolbar-wrapper').hide();
      }
    },

    hide: function () {
      jQuery('div.create-ui-toolbar-wrapper').fadeToggle('fast', 'linear');
    },

    show: function () {
      jQuery('div.create-ui-toolbar-wrapper').fadeToggle('fast', 'linear');
    },

    _getMinimized: function () {
      return jQuery('

');
    },

    _getFull: function () {
      return jQuery('

');
    },

    _clearWorkflows: function () {
      jQuery('.create-ui-tool-workflowarea', this.element).empty();
    },

    _clearMetadata: function () {
      jQuery('.create-ui-tool-metadataarea', this.element).empty();
    }
  });
})(jQuery);
<|endoftext|>


<commit_before>/* global jest, describe, beforeEach, it, expect */

jest.dontMock('reflux');
jest.dontMock('../../actions/actions.js');
jest.dontMock('../../utils/api-requests');
jest.dontMock('../../components/login.js');
jest.dontMock('../../stores/auth.js');

var React = require('react/addons');
var TestUtils = React.addons.TestUtils;

describe('Test for Login Component', function () {

  var apiRequests, Actions, Login, AuthStore, Router, browserWindow;

  beforeEach(function () {
    // Mock Electron's window.require
    // and remote.ipc
    browserWindow = function () {
      return {
        loadUrl: function () {
          return;
        },
        webContents: {
          on: function (event, callback) {

            if (event == 'did-get-redirect-request') {
              callback(
                'did-get-redirect-request',
                'http://www.github.com/?code=123123123',
                'http://www.github.com/?code=123123123'
              );
            }

          }
        },
        on: function () {
          return;
        },
        close: function () {
          return;
        }
      };
    };

    window.require = function () {
      return {
        require: function () {
          return browserWindow;
        },
        sendChannel: function () {
          return;
        }
      };
    };

    // Mock localStorage
    window.localStorage = {
      item: false,
      getItem: function () {
        return this.item;
      }
    };

    apiRequests = require('../../utils/api-requests.js');
    Actions = require('../../actions/actions.js');
    AuthStore = require('../../stores/auth.js');
    Login = require('../../components/login.js');
    Router = require('react-router');
  });

  it('Should get the token from github', function () {

    var instance;
    React.withContext({router: new Router()}, function () {
      instance = TestUtils.renderIntoDocument(<Login />);
    });

    expect(instance.authGithub).toBeDefined();
    expect(instance.requestGithubToken).toBeDefined();

    var superagent = require('superagent');
    superagent.__setResponse(200, 'ok', {'access_token': '123123123'}, false);

    instance.requestGithubToken({}, '456456');

  });

  it('Should fail to get the token from github', function () {

    var instance;
    React.withContext({router: new Router()}, function () {
      instance = TestUtils.renderIntoDocument(<Login />);
    });

    expect(instance.authGithub).toBeDefined();
    expect(instance.requestGithubToken).toBeDefined();

    var superagent = require('superagent');
    superagent.__setResponse(400, false, false, false);

    instance.requestGithubToken({}, '456456');

  });

  it('Should open the authWindow and login successfully', function () {

    var instance = TestUtils.renderIntoDocument(<Login />);
    expect(instance.authGithub).toBeDefined();

    // Prevent testing requestGithubToken
    // Tested in another case
    instance.requestGithubToken = function () {
      return;
    };

    instance.authGithub();

  });

});

describe('Test for Login Component - Callback with Error', function () {

  var Login, browserWindow;

  beforeEach(function () {
    // Mock Electron's window.require
    // and remote.ipc
    browserWindow = function () {
      return {
        loadUrl: function () {
          return;
        },
        webContents: {
          on: function (event, callback) {

            if (event == 'did-get-redirect-request') {
              callback(
                'did-get-redirect-request',
                'http://www.github.com/?error=FAILURE',
                'http://www.github.com/?error=FAILURE'
              );
            }

          }
        },
        on: function () {
          return;
        },
        close: function () {
          return;
        }
      };
    };

    window.require = function () {
      return {
        require: function () {
          return browserWindow;
        },
        sendChannel: function () {
          return;
        }
      };
    };

    // Mock alert
    window.alert = function () {
      return;
    };

    Login = require('../../components/login.js');
  });

  it('Should open the authWindow and fail to login', function () {

    var instance = TestUtils.renderIntoDocument(<Login />);
    expect(instance.authGithub).toBeDefined();

    instance.authGithub();

  });

});
<commit_msg>App Coverage 100%<commit_after>/* global jest, describe, beforeEach, it, expect */

jest.dontMock('reflux');
jest.dontMock('../../actions/actions.js');
jest.dontMock('../../utils/api-requests');
jest.dontMock('../../components/login.js');
jest.dontMock('../../stores/auth.js');

var React = require('react/addons');
var TestUtils = React.addons.TestUtils;

describe('Test for Login Component', function () {

  var apiRequests, Actions, Login, AuthStore, Router, browserWindow;

  beforeEach(function () {
    // Mock Electron's window.require
    // and remote.ipc
    browserWindow = function () {
      return {
        loadUrl: function () {
          return;
        },
        webContents: {
          on: function (event, callback) {

            if (event == 'did-get-redirect-request') {
              callback(
                'did-get-redirect-request',
                'http://www.github.com/?code=123123123',
                'http://www.github.com/?code=123123123'
              );
            }

          }
        },
        on: function () {
          return;
        },
        close: function () {
          return;
        }
      };
    };

    window.require = function () {
      return {
        require: function () {
          return browserWindow;
        },
        sendChannel: function () {
          return;
        }
      };
    };

    // Mock localStorage
    window.localStorage = {
      item: false,
      getItem: function () {
        return this.item;
      }
    };

    apiRequests = require('../../utils/api-requests.js');
    Actions = require('../../actions/actions.js');
    AuthStore = require('../../stores/auth.js');
    Login = require('../../components/login.js');
    Router = require('react-router');
  });

  it('Should get the token from github', function () {

    var instance;
    React.withContext({router: new Router()}, function () {
      instance = TestUtils.renderIntoDocument(<Login />);
    });

    expect(instance.authGithub).toBeDefined();
    expect(instance.requestGithubToken).toBeDefined();

    var superagent = require('superagent');
    superagent.__setResponse(200, 'ok', {'access_token': '123123123'}, false);

    instance.requestGithubToken({}, '456456');

  });

  it('Should fail to get the token from github', function () {

    var instance;
    React.withContext({router: new Router()}, function () {
      instance = TestUtils.renderIntoDocument(<Login />);
    });

    expect(instance.authGithub).toBeDefined();
    expect(instance.requestGithubToken).toBeDefined();

    var superagent = require('superagent');
    superagent.__setResponse(400, false, false, false);

    instance.requestGithubToken({}, '456456');

  });

  it('Should open the authWindow and login successfully', function () {

    var instance = TestUtils.renderIntoDocument(<Login />);
    expect(instance.authGithub).toBeDefined();

    // Prevent testing requestGithubToken
    // Tested in another case
    instance.requestGithubToken = function () {
      return;
    };

    instance.authGithub();

  });

});

describe('Test for Login Component - Callback with Error', function () {

  var Login, browserWindow;

  beforeEach(function () {
    // Mock Electron's window.require
    // and remote.ipc
    browserWindow = function () {
      return {
        loadUrl: function () {
          return;
        },
        webContents: {
          on: function (event, callback) {

            if (event == 'did-get-redirect-request') {
              callback(
                'did-get-redirect-request',
                'http://www.github.com/?error=FAILURE',
                'http://www.github.com/?error=FAILURE'
              );
            }

          }
        },
        on: function (event, callback) {
          callback();
        },
        close: function () {
          return;
        }
      };
    };

    window.require = function () {
      return {
        require: function () {
          return browserWindow;
        },
        sendChannel: function () {
          return;
        }
      };
    };

    // Mock alert
    window.alert = function () {
      return;
    };

    Login = require('../../components/login.js');
  });

  it('Should open the authWindow and fail to login', function () {

    var instance = TestUtils.renderIntoDocument(<Login />);
    expect(instance.authGithub).toBeDefined();

    instance.authGithub();

  });

});
<|endoftext|>