<commit_before>'use strict';

angular.module('core').controller('HomeController', ['$scope', '$sce', 'Authentication',
  function ($scope, $sce, Authentication) {
    // This provides Authentication context.
    $scope.authentication = Authentication;
    $scope.userLoggedIn = Authentication.user;
    if (Authentication.user) {
      $scope.adminUser = Authentication.user.roles.indexOf('admin') !== -1;
    }
    console.log(Authentication.user);
    $scope.about = { title: 'About Us', body:'Tripzilla is a Lorem ipsum dolor sit amet, consectetur adipisicing elit. Id itaque molestias soluta vero voluptatibus. Cumque dolores molestiae nostrum nulla odit recusandae reiciendis! Dicta explicabo illum nihil nulla numquam quas tempore?' };
    $scope.sites = { title:'Our Sites', body:'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aliquam asperiores at debitis, delectus deserunt dolores dolorum e' };
    $scope.renderHtml = function (html) {
        return $sce.trustAsHtml(html);
    };
}
]);
<commit_msg>Changed main page copy<commit_after>'use strict';

angular.module('core').controller('HomeController', ['$scope', '$sce', 'Authentication',
  function ($scope, $sce, Authentication) {
    // This provides Authentication context.
    $scope.authentication = Authentication;
    $scope.userLoggedIn = Authentication.user;
    if (Authentication.user) {
      $scope.adminUser = Authentication.user.roles.indexOf('admin') !== -1;
    }
    console.log(Authentication.user);
    $scope.about = { title: 'About Us', body:'Tripzilla is an artifical platform for booking fake trips for imaginary customers. We allow our false users to have the greatest overall experiences in their whole non-lives.' };
    $scope.sites = { title:'Our Sites', body:'Our sites don\'t exist, but if they did, they\'d be great and would be linked to right here.'};
    $scope.renderHtml = function (html) {
        return $sce.trustAsHtml(html);
    };
}
]);
<|endoftext|>


<commit_before>'use strict';

console.log('loading users');

angular.module('users').filter('noDomain', function () {
    return function (skills) {
        return _.filter(skills, function (skill) {
            return !skill.domains;
        });
    };
});

angular.module('users').filter('partOfDomain', function () {
    return function (skills, domain) {
        return _.filter(skills, function (skill) {
            if (skill.domains) {
                var domainsInUpperCase = _.map(skill.domains, function (domain) {
                        return domain.toUpperCase();
                    }
                );
                return domainsInUpperCase.indexOf(domain.toUpperCase()) >= 0;
            }
            return false;
        });
    };
});

angular.module('users').directive('domain', function () {
    return {
        restrict: 'E',
        scope: {
            label: '=label',
            skills: '=skills'
        },
        templateUrl: 'modules/users/views/domain.template.html'
    };
});

angular.module('users').controller('UsersController', ['_', '$scope', '$http', '$location', 'Users', 'Authentication',
    function (_, $scope, $http, $location, Users, Authentication) {

        $scope.user = Authentication.user;

        $scope.back = 'Back';
        $scope.cloud = 'Cloud';
        $scope.front = 'Front';
        $scope.devops = 'Devops';
        $scope.agile = 'Agile';
        $scope.mobile = 'Mobile';
        $scope.data = 'Data';
        $scope.craft = 'Craft';

        $scope.skillz = [];
        $scope.results = [];

        var reset = function () {
            $scope.newSkill = '';
            $scope.oldLevel = $scope.level = 0;
            $scope.like = false;
        };
        reset();

        $scope.hoveringOver = function (value) {
            $scope.tempLevel = value;
        };
        $scope.setLevel = function () {
            if ($scope.oldLevel === 1) {
                $scope.level = 0;
            } else {
                $scope.level = $scope.tempLevel;
            }
            $scope.oldLevel = $scope.tempLevel;
        };

        $scope.toggleLike = function () {
            $scope.like = !$scope.like;
        };

        $http.get('/users/me/skillz').then(function (response) {
            $scope.skillz = response.data;
        });

// If user is not signed in then redirect back home
        if (!$scope.user) $location.path('/');

        $scope.removeRelation = function (relationId) {
            $http.post('users/me/skillz/disassociate', {'relationId': relationId}).then(function (response) {
                $scope.skillz = response.data;
            });
        };

// Affect a skill to current user
        $scope.associateSkill = function () {
            if (!(_.find($scope.skillz, function (skill) {
                return skill.name === $scope.newSkill;
            }))) {
                $http.put('users/me/skillz', { 'skill': {'name': $scope.newSkill}, 'relation_properties': {'level': $scope.level, 'like': $scope.like }})
                    .then(function (response) {
                        reset();
                        $scope.skillz = response.data;
                    });
            }
        };

        $scope.changingSearchXebians = function () {
            $scope.results = [];
            if ($scope.query.length > 2) {
                $scope.searchXebians();
            }
        };
        $scope.searchXebians = function () {
            $http.get('/users', {'params': {'q': $scope.query}})
                .then(function (response) {
                    $scope.results = response.data;
                });
        };

// Get user profile
        $scope.getProfile = function () {
            console.log('get profile');
        };

        $scope.searchSkill = function (value) {
            return $http.get('/users/me/availableSkillz', {'params': {'q': value}})
                .then(function (response) {
                    return _.map(response.data, function (row) {
                        return row[0];
                    });
                });
        };

        $scope.updateLevel = function (skill) {
            console.log(skill);
            $http.put('/users/me/skillz/' + skill.relationId + '/level', {'level': skill.level}).then(function (response) {
                $scope.skillz = response.data;
            });
        };

        $scope.updateLike = function (skill) {
            skill.like = !skill.like;
            $http.put('/users/me/skillz/' + skill.relationId + '/like', {'like': skill.like}).then(function (response) {
                $scope.skillz = response.data;
            });
        };
    }
]);

<commit_msg>[Mon Profil] Correction de bug sur l'autocomplete<commit_after>'use strict';

console.log('loading users');

angular.module('users').filter('noDomain', function () {
    return function (skills) {
        return _.filter(skills, function (skill) {
            return !skill.domains;
        });
    };
});

angular.module('users').filter('partOfDomain', function () {
    return function (skills, domain) {
        return _.filter(skills, function (skill) {
            if (skill.domains) {
                var domainsInUpperCase = _.map(skill.domains, function (domain) {
                        return domain.toUpperCase();
                    }
                );
                return domainsInUpperCase.indexOf(domain.toUpperCase()) >= 0;
            }
            return false;
        });
    };
});

angular.module('users').directive('domain', function () {
    return {
        restrict: 'E',
        scope: {
            label: '=label',
            skills: '=skills'
        },
        templateUrl: 'modules/users/views/domain.template.html'
    };
});

angular.module('users').controller('UsersController', ['_', '$scope', '$http', '$location', 'Users', 'Authentication',
    function (_, $scope, $http, $location, Users, Authentication) {

        $scope.user = Authentication.user;

        $scope.back = 'Back';
        $scope.cloud = 'Cloud';
        $scope.front = 'Front';
        $scope.devops = 'Devops';
        $scope.agile = 'Agile';
        $scope.mobile = 'Mobile';
        $scope.data = 'Data';
        $scope.craft = 'Craft';

        $scope.skillz = [];
        $scope.results = [];

        var reset = function () {
            $scope.newSkill = '';
            $scope.oldLevel = $scope.level = 0;
            $scope.like = false;
        };
        reset();

        $scope.hoveringOver = function (value) {
            $scope.tempLevel = value;
        };
        $scope.setLevel = function () {
            if ($scope.oldLevel === 1) {
                $scope.level = 0;
            } else {
                $scope.level = $scope.tempLevel;
            }
            $scope.oldLevel = $scope.tempLevel;
        };

        $scope.toggleLike = function () {
            $scope.like = !$scope.like;
        };

        $http.get('/users/me/skillz').then(function (response) {
            $scope.skillz = response.data;
        });

// If user is not signed in then redirect back home
        if (!$scope.user) $location.path('/');

        $scope.removeRelation = function (relationId) {
            $http.post('users/me/skillz/disassociate', {'relationId': relationId}).then(function (response) {
                $scope.skillz = response.data;
            });
        };

// Affect a skill to current user
        $scope.associateSkill = function () {
            if (!(_.find($scope.skillz, function (skill) {
                return skill.name === $scope.newSkill;
            }))) {
                $http.put('users/me/skillz', { 'skill': {'name': $scope.newSkill}, 'relation_properties': {'level': $scope.level, 'like': $scope.like }})
                    .then(function (response) {
                        reset();
                        $scope.skillz = response.data;
                    });
            }
        };

        $scope.changingSearchXebians = function () {
            $scope.results = [];
            if ($scope.query.length > 2) {
                $scope.searchXebians();
            }
        };
        $scope.searchXebians = function () {
            $http.get('/users', {'params': {'q': $scope.query}})
                .then(function (response) {
                    $scope.results = response.data;
                });
        };

// Get user profile
        $scope.getProfile = function () {
            console.log('get profile');
        };

        $scope.searchSkill = function (value) {
            return $http.get('/users/me/availableSkillz', {'params': {'q': value}})
                .then(function (response) {
                    return _.map(response.data, function (row) {
                        return row.name;
                    });
                });
        };

        $scope.updateLevel = function (skill) {
            console.log(skill);
            $http.put('/users/me/skillz/' + skill.relationId + '/level', {'level': skill.level}).then(function (response) {
                $scope.skillz = response.data;
            });
        };

        $scope.updateLike = function (skill) {
            skill.like = !skill.like;
            $http.put('/users/me/skillz/' + skill.relationId + '/like', {'like': skill.like}).then(function (response) {
                $scope.skillz = response.data;
            });
        };
    }
]);

<|endoftext|>


<commit_before>// Domoticz Platform Shim for HomeBridge
// Written by Joep Verhaeg (http://www.joepverhaeg.nl)
//
// Revisions:
//
// 12 June 2015 [GizMoCuz]
// - Added support for RGB lights
// - Added support for Scenes
// - Sorting device names
//
// Domoticz JSON API required
// https://www.domoticz.com/wiki/Domoticz_API/JSON_URL's#Lights_and_switches
//
// Remember to add platform to config.json. Example:
// "platforms": [
//     {
//         "platform": "Domoticz",
//         "name": "Domoticz",
//         "server": "127.0.0.1",
//         "port": "8080"
//     }
// ],
//
// When you attempt to add a device, it will ask for a "PIN code".
// The default code for all HomeBridge accessories is 031-45-154.
//
var types = require("../lib/HAP-NodeJS/accessories/types.js");
var request = require("request");

function DomoticzPlatform(log, config){
	this.log     = log;
	this.server  = config["server"];
	this.port    = config["port"];
}

function sortByKey(array, key) {
    return array.sort(function(a, b) {
        var x = a[key]; var y = b[key];
        return ((x < y) ? -1 : ((x > y) ? 1 : 0));
    });
}

DomoticzPlatform.prototype = {
	accessories: function(callback) {
	    this.log("Fetching Domoticz lights and switches...");

	    var that = this;
	    var foundAccessories = [];
	    //Get Lights
		request.get({
			url: "http://" + this.server + ":" + this.port + "/json.htm?type=devices&filter=light&used=true&order=Name",
	      	json: true
	    }, function(err, response, json) {
			if (!err && response.statusCode == 200) {
				if (json['result'] != undefined) {
					var sArray=sortByKey(json['result'],"Name");
					sArray.map(function(s) {
						accessory = new DomoticzAccessory(that.log, that.server, that.port, false, s.idx, s.Name, s.HaveDimmer, s.MaxDimLevel, (s.SubType=="RGB")||(s.SubType=="RGBW"));
						foundAccessories.push(accessory);
	          		})
				}
				callback(foundAccessories);
			} else {
				that.log("There was a problem connecting to Domoticz.");
	      	}
		});
		//Get Scenes
		request.get({
			url: "http://" + this.server + ":" + this.port + "/json.htm?type=scenes",
	      	json: true
	    }, function(err, response, json) {
			if (!err && response.statusCode == 200) {
				if (json['result'] != undefined) {
					var sArray=sortByKey(json['result'],"Name");
					sArray.map(function(s) {
						accessory = new DomoticzAccessory(that.log, that.server, that.port, true, s.idx, s.Name, false, 0, false);
						foundAccessories.push(accessory);
	          		})
				}
				callback(foundAccessories);
			} else {
				that.log("There was a problem connecting to Domoticz.");
	      	}
		});
	}
}

function DomoticzAccessory(log, server, port, IsScene, idx, name, HaveDimmer, MaxDimLevel, HaveRGB) {
  // device info
  this.IsScene		= IsScene;
  this.idx			= idx;
  this.name			= name;
  this.HaveDimmer	= HaveDimmer;
  this.MaxDimLevel	= MaxDimLevel;
  this.HaveRGB		= HaveRGB;
  this.log 			= log;
  this.server		= server;
  this.port			= port;
}

DomoticzAccessory.prototype = {
	command: function(c,value) {
		this.log(this.name + " sending command " + c + " with value " + value);
		if (this.IsScene == false) {
			//Lights
			if (c == "On" || c == "Off") {
				url = "http://" + this.server + ":" + this.port + "/json.htm?type=command&param=switchlight&idx=" + this.idx + "&switchcmd=" + c + "&level=0";
			}
			else if (c == "setHue") {
				url = "http://" + this.server + ":" + this.port + "/json.htm?type=command&param=setcolbrightnessvalue&idx=" + this.idx + "&hue=" + value + "&brightness=100" + "&iswhite=false";
			}
			else if (c == "setLevel") {
				url = "http://" + this.server + ":" + this.port + "/json.htm?type=command&param=switchlight&idx=" + this.idx + "&switchcmd=Set%20Level&level=" + value;
			}
			else if (value != undefined) {
				this.log(this.name + " Unhandled Light command! cmd=" + c + ", value=" + value);
			}
		}
		else {
			//Scenes
			if (c == "On" || c == "Off") {
				url = "http://" + this.server + ":" + this.port + "/json.htm?type=command&param=switchscene&idx=" + this.idx + "&switchcmd=" + c;
			}
			else if (value != undefined) {
				this.log(this.name + " Unhandled Scene command! cmd=" + c + ", value=" + value);
			}
		}

    var that = this;
		request.put({ url: url }, function(err, response) {
			if (err) {
				that.log("There was a problem sending command " + c + " to" + that.name);
				that.log(url);
			} else {
				that.log(that.name + " sent command " + c);
      		}
      	})
  	},

  informationCharacteristics: function() {
    return [
      {
        cType: types.NAME_CTYPE,
        onUpdate: null,
        perms: ["pr"],
        format: "string",
        initialValue: this.name,
        supportEvents: false,
        supportBonjour: false,
        manfDescription: "Name of the accessory",
        designedMaxLength: 255
      },{
        cType: types.MANUFACTURER_CTYPE,
        onUpdate: null,
        perms: ["pr"],
        format: "string",
        initialValue: "Domoticz",
        supportEvents: false,
        supportBonjour: false,
        manfDescription: "Manufacturer",
        designedMaxLength: 255
      },{
        cType: types.MODEL_CTYPE,
        onUpdate: null,
        perms: ["pr"],
        format: "string",
        initialValue: "Rev-1",
        supportEvents: false,
        supportBonjour: false,
        manfDescription: "Model",
        designedMaxLength: 255
      },{
        cType: types.SERIAL_NUMBER_CTYPE,
        onUpdate: null,
        perms: ["pr"],
        format: "string",
        initialValue: "A1S2NASF88EW",
        supportEvents: false,
        supportBonjour: false,
        manfDescription: "SN",
        designedMaxLength: 255
      },{
        cType: types.IDENTIFY_CTYPE,
        onUpdate: null,
        perms: ["pw"],
        format: "bool",
        initialValue: false,
        supportEvents: false,
        supportBonjour: false,
        manfDescription: "Identify Accessory",
        designedMaxLength: 1
      }
    ]
  },

  controlCharacteristics: function(that) {
    cTypes = [{
      cType: types.NAME_CTYPE,
      onUpdate: null,
      perms: ["pr"],
      format: "string",
      initialValue: this.name,
      supportEvents: true,
      supportBonjour: false,
      manfDescription: "Name of service",
      designedMaxLength: 255
    }]

    if (this.idx != undefined) {
      cTypes.push({
        cType: types.POWER_STATE_CTYPE,
        onUpdate: function(value) {
          if (value == 0) {
            that.command("Off")
          } else {
            that.command("On")
          }
        },
        perms: ["pw","pr","ev"],
        format: "bool",
        initialValue: 0,
        supportEvents: true,
        supportBonjour: false,
        manfDescription: "Change the power state",
        designedMaxLength: 1
      })
    }

    if (this.HaveDimmer == true) {
      cTypes.push({
        cType: types.BRIGHTNESS_CTYPE,
        onUpdate: function(value) { that.command("setLevel", value); },
        perms: ["pw","pr","ev"],
        format: "int",
        initialValue:  0,
        supportEvents: true,
        supportBonjour: false,
        manfDescription: "Adjust Brightness of Light",
        designedMinValue: 0,
        designedMaxValue: this.MaxDimLevel,
        designedMinStep: 1,
        unit: "%"
      })
    }
    if (this.HaveRGB == true) {
      cTypes.push({
        cType: types.HUE_CTYPE,
        onUpdate: function(value) { that.command("setHue", value); },
        perms: ["pw","pr","ev"],
        format: "int",
        initialValue:  0,
        supportEvents: true,
        supportBonjour: false,
        manfDescription: "Adjust Hue of Light",
        designedMinValue: 0,
        designedMaxValue: 360,
        designedMinStep: 1,
        unit: "arcdegrees"
      })
    }

    return cTypes
  },

  sType: function() {
    if (this.HaveDimmer == true) {
      return types.LIGHTBULB_STYPE
    } else {
      return types.SWITCH_STYPE
    }
  },

  getServices: function() {
    var that = this;
    var services = [{
      sType: types.ACCESSORY_INFORMATION_STYPE,
      characteristics: this.informationCharacteristics(),
    },
    {
      sType: this.sType(),
      characteristics: this.controlCharacteristics(that)
    }];
    this.log("Loaded services for " + this.name)
    return services;
  }
};

module.exports.accessory = DomoticzAccessory;
module.exports.platform = DomoticzPlatform;<commit_msg>- Implemented, optional configuration parameter for 'roomid' - Fixed: trying to add duplicate sensors<commit_after>// Domoticz Platform Shim for HomeBridge
// Written by Joep Verhaeg (http://www.joepverhaeg.nl)
//
// Revisions:
//
// 12 June 2015 [GizMoCuz]
// - Added support for RGB lights
// - Added support for Scenes
// - Sorting device names
//
// Domoticz JSON API required
// https://www.domoticz.com/wiki/Domoticz_API/JSON_URL's#Lights_and_switches
//
// Remember to add platform to config.json. Example:
// "platforms": [
//     {
//         "platform": "Domoticz",
//         "name": "Domoticz",
//         "server": "127.0.0.1",
//         "port": "8080",
//         "roomid": 123 (0=no roomplan)
//     }
// ],
//
// When you attempt to add a device, it will ask for a "PIN code".
// The default code for all HomeBridge accessories is 031-45-154.
//
var types = require("../lib/HAP-NodeJS/accessories/types.js");
var request = require("request");

function DomoticzPlatform(log, config){
	this.log     = log;
	this.server  = config["server"];
	this.port    = config["port"];
	this.roomid  = 0;
	if (typeof config["roomid"] != 'undefined') {
		this.roomid = config["roomid"];
	}
}

function sortByKey(array, key) {
    return array.sort(function(a, b) {
        var x = a[key]; var y = b[key];
        return ((x < y) ? -1 : ((x > y) ? 1 : 0));
    });
}

DomoticzPlatform.prototype = {
	accessories: function(callback) {
	    this.log("Fetching Domoticz lights and switches...");

	    var that = this;
	    var foundAccessories = [];
	    if (this.roomid == 0) {
			//Get Lights
			request.get({
				url: "http://" + this.server + ":" + this.port + "/json.htm?type=devices&filter=light&used=true&order=Name",
				json: true
			}, function(err, response, json) {
				if (!err && response.statusCode == 200) {
					if (json['result'] != undefined) {
						var sArray=sortByKey(json['result'],"Name");
						sArray.map(function(s) {
							accessory = new DomoticzAccessory(that.log, that.server, that.port, false, s.idx, s.Name, s.HaveDimmer, s.MaxDimLevel, (s.SubType=="RGB")||(s.SubType=="RGBW"));
							foundAccessories.push(accessory);
						})
					}
					callback(foundAccessories);
				} else {
					that.log("There was a problem connecting to Domoticz.");
				}
			});
	    }
	    else {
			//Get all devices specified in the room
			request.get({
				url: "http://" + this.server + ":" + this.port + "/json.htm?type=devices&plan=" + this.roomid,
				json: true
			}, function(err, response, json) {
				if (!err && response.statusCode == 200) {
					if (json['result'] != undefined) {
						var sArray=sortByKey(json['result'],"Name");
						sArray.map(function(s) {
							//only accept switches for now
							if (typeof s.SwitchType != 'undefined') {
								accessory = new DomoticzAccessory(that.log, that.server, that.port, false, s.idx, s.Name, s.HaveDimmer, s.MaxDimLevel, (s.SubType=="RGB")||(s.SubType=="RGBW"));
								foundAccessories.push(accessory);
							}
						})
					}
					callback(foundAccessories);
				} else {
					that.log("There was a problem connecting to Domoticz.");
				}
			});
	    }
		//Get Scenes
		foundAccessories = [];
		request.get({
			url: "http://" + this.server + ":" + this.port + "/json.htm?type=scenes",
	      	json: true
	    }, function(err, response, json) {
			if (!err && response.statusCode == 200) {
				if (json['result'] != undefined) {
					var sArray=sortByKey(json['result'],"Name");
					sArray.map(function(s) {
						accessory = new DomoticzAccessory(that.log, that.server, that.port, true, s.idx, s.Name, false, 0, false);
						foundAccessories.push(accessory);
	          		})
				}
				callback(foundAccessories);
			} else {
				that.log("There was a problem connecting to Domoticz.");
	      	}
		});
	}
}

function DomoticzAccessory(log, server, port, IsScene, idx, name, HaveDimmer, MaxDimLevel, HaveRGB) {
  // device info
  this.IsScene		= IsScene;
  this.idx			= idx;
  this.name			= name;
  this.HaveDimmer	= HaveDimmer;
  this.MaxDimLevel	= MaxDimLevel;
  this.HaveRGB		= HaveRGB;
  this.log 			= log;
  this.server		= server;
  this.port			= port;
}

DomoticzAccessory.prototype = {
	command: function(c,value) {
		this.log(this.name + " sending command " + c + " with value " + value);
		if (this.IsScene == false) {
			//Lights
			if (c == "On" || c == "Off") {
				url = "http://" + this.server + ":" + this.port + "/json.htm?type=command&param=switchlight&idx=" + this.idx + "&switchcmd=" + c + "&level=0";
			}
			else if (c == "setHue") {
				url = "http://" + this.server + ":" + this.port + "/json.htm?type=command&param=setcolbrightnessvalue&idx=" + this.idx + "&hue=" + value + "&brightness=100" + "&iswhite=false";
			}
			else if (c == "setLevel") {
				url = "http://" + this.server + ":" + this.port + "/json.htm?type=command&param=switchlight&idx=" + this.idx + "&switchcmd=Set%20Level&level=" + value;
			}
			else if (value != undefined) {
				this.log(this.name + " Unhandled Light command! cmd=" + c + ", value=" + value);
			}
		}
		else {
			//Scenes
			if (c == "On" || c == "Off") {
				url = "http://" + this.server + ":" + this.port + "/json.htm?type=command&param=switchscene&idx=" + this.idx + "&switchcmd=" + c;
			}
			else if (value != undefined) {
				this.log(this.name + " Unhandled Scene command! cmd=" + c + ", value=" + value);
			}
		}

    var that = this;
		request.put({ url: url }, function(err, response) {
			if (err) {
				that.log("There was a problem sending command " + c + " to" + that.name);
				that.log(url);
			} else {
				that.log(that.name + " sent command " + c);
      		}
      	})
  	},

  informationCharacteristics: function() {
    return [
      {
        cType: types.NAME_CTYPE,
        onUpdate: null,
        perms: ["pr"],
        format: "string",
        initialValue: this.name,
        supportEvents: false,
        supportBonjour: false,
        manfDescription: "Name of the accessory",
        designedMaxLength: 255
      },{
        cType: types.MANUFACTURER_CTYPE,
        onUpdate: null,
        perms: ["pr"],
        format: "string",
        initialValue: "Domoticz",
        supportEvents: false,
        supportBonjour: false,
        manfDescription: "Manufacturer",
        designedMaxLength: 255
      },{
        cType: types.MODEL_CTYPE,
        onUpdate: null,
        perms: ["pr"],
        format: "string",
        initialValue: "Rev-1",
        supportEvents: false,
        supportBonjour: false,
        manfDescription: "Model",
        designedMaxLength: 255
      },{
        cType: types.SERIAL_NUMBER_CTYPE,
        onUpdate: null,
        perms: ["pr"],
        format: "string",
        initialValue: "A1S2NASF88EW",
        supportEvents: false,
        supportBonjour: false,
        manfDescription: "SN",
        designedMaxLength: 255
      },{
        cType: types.IDENTIFY_CTYPE,
        onUpdate: null,
        perms: ["pw"],
        format: "bool",
        initialValue: false,
        supportEvents: false,
        supportBonjour: false,
        manfDescription: "Identify Accessory",
        designedMaxLength: 1
      }
    ]
  },

  controlCharacteristics: function(that) {
    cTypes = [{
      cType: types.NAME_CTYPE,
      onUpdate: null,
      perms: ["pr"],
      format: "string",
      initialValue: this.name,
      supportEvents: true,
      supportBonjour: false,
      manfDescription: "Name of service",
      designedMaxLength: 255
    }]

    if (this.idx != undefined) {
      cTypes.push({
        cType: types.POWER_STATE_CTYPE,
        onUpdate: function(value) {
          if (value == 0) {
            that.command("Off")
          } else {
            that.command("On")
          }
        },
        perms: ["pw","pr","ev"],
        format: "bool",
        initialValue: 0,
        supportEvents: true,
        supportBonjour: false,
        manfDescription: "Change the power state",
        designedMaxLength: 1
      })
    }

    if (this.HaveDimmer == true) {
      cTypes.push({
        cType: types.BRIGHTNESS_CTYPE,
        onUpdate: function(value) { that.command("setLevel", value); },
        perms: ["pw","pr","ev"],
        format: "int",
        initialValue:  0,
        supportEvents: true,
        supportBonjour: false,
        manfDescription: "Adjust Brightness of Light",
        designedMinValue: 0,
        designedMaxValue: this.MaxDimLevel,
        designedMinStep: 1,
        unit: "%"
      })
    }
    if (this.HaveRGB == true) {
      cTypes.push({
        cType: types.HUE_CTYPE,
        onUpdate: function(value) { that.command("setHue", value); },
        perms: ["pw","pr","ev"],
        format: "int",
        initialValue:  0,
        supportEvents: true,
        supportBonjour: false,
        manfDescription: "Adjust Hue of Light",
        designedMinValue: 0,
        designedMaxValue: 360,
        designedMinStep: 1,
        unit: "arcdegrees"
      })
    }

    return cTypes
  },

  sType: function() {
    if (this.HaveDimmer == true) {
      return types.LIGHTBULB_STYPE
    } else {
      return types.SWITCH_STYPE
    }
  },

  getServices: function() {
    var that = this;
    var services = [{
      sType: types.ACCESSORY_INFORMATION_STYPE,
      characteristics: this.informationCharacteristics(),
    },
    {
      sType: this.sType(),
      characteristics: this.controlCharacteristics(that)
    }];
    this.log("Loaded services for " + this.name)
    return services;
  }
};

module.exports.accessory = DomoticzAccessory;
module.exports.platform = DomoticzPlatform;<|endoftext|>


<commit_before>var buster = (function (setTimeout, B) {
    var isNode = typeof require == "function" && typeof module == "object";
    var div = typeof document != "undefined" && document.createElement("div");
    var F = function () {};

    var buster = {
        bind: function bind(obj, methOrProp) {
            var method = typeof methOrProp == "string" ? obj[methOrProp] : methOrProp;
            var args = Array.prototype.slice.call(arguments, 2);
            return function () {
                var allArgs = args.concat(Array.prototype.slice.call(arguments));
                return method.apply(obj, allArgs);
            };
        },

        partial: function partial(fn) {
            var args = [].slice.call(arguments, 1);
            return function () {
                return fn.apply(this, args.concat([].slice.call(arguments)));
            };
        },

        create: function create(object) {
            F.prototype = object;
            return new F();
        },

        extend: function extend(target) {
            if (!target) { return; }
            for (var i = 1, l = arguments.length, prop; i < l; ++i) {
                for (prop in arguments[i]) {
                    target[prop] = arguments[i][prop];
                }
            }
            return target;
        },

        nextTick: function nextTick(callback) {
            if (typeof process != "undefined" && process.nextTick) {
                return process.nextTick(callback);
            }
            setTimeout(callback, 0);
        },

        functionName: function functionName(func) {
            if (!func) return "";
            if (func.displayName) return func.displayName;
            if (func.name) return func.name;
            var matches = func.toString().match(/function\s+([^\(]+)/m);
            return matches && matches[1] || "";
        },

        isNode: function isNode(obj) {
            if (!div) return false;
            try {
                obj.appendChild(div);
                obj.removeChild(div);
            } catch (e) {
                return false;
            }
            return true;
        },

        isElement: function isElement(obj) {
            return obj && obj.nodeType === 1 && buster.isNode(obj);
        },

        isArray: function isArray(arr) {
            return Object.prototype.toString.call(arr) == "[object Array]";
        },

        flatten: function flatten(arr) {
            var result = [], arr = arr || [];
            for (var i = 0, l = arr.length; i < l; ++i) {
                result = result.concat(buster.isArray(arr[i]) ? flatten(arr[i]) : arr[i]);
            }
            return result;
        },

        each: function each(arr, callback) {
            for (var i = 0, l = arr.length; i < l; ++i) {
                callback(arr[i]);
            }
        },

        map: function map(arr, callback) {
            var results = [];
            for (var i = 0, l = arr.length; i < l; ++i) {
                results.push(callback(arr[i]));
            }
            return results;
        },

        parallel: function parallel(fns, callback) {
            function cb(err, res) {
                if (typeof callback == "function") {
                    callback(err, res);
                    callback = null;
                }
            }
            if (fns.length == 0) { return cb(null, []); }
            var remaining = fns.length, results = [];
            function makeDone(num) {
                return function done(err, result) {
                    if (err) { return cb(err); }
                    results[num] = result;
                    if (--remaining == 0) { cb(null, results); }
                };
            }
            for (var i = 0, l = fns.length; i < l; ++i) {
                fns[i](makeDone(i));
            }
        },

        series: function series(fns, callback) {
            function cb(err, res) {
                if (typeof callback == "function") {
                    callback(err, res);
                }
            }
            var remaining = fns.slice();
            var results = [];
            function callNext() {
                if (remaining.length == 0) return cb(null, results);
                var promise = remaining.shift()(next);
                if (promise && typeof promise.then == "function") {
                    promise.then(buster.partial(next, null), next);
                }
            }
            function next(err, result) {
                if (err) return cb(err);
                results.push(result);
                callNext();
            }
            callNext();
        },

        countdown: function countdown(num, done) {
            return function () {
                if (--num == 0) done();
            };
        }
    };

    if (typeof process === "object") {
        var crypto = require("crypto");
        var path = require("path");

        buster.tmpFile = function (fileName) {
            var hashed = crypto.createHash("sha1");
            hashed.update(fileName);
            var tmpfileName = hashed.digest("hex");

            if (process.platform == "win32") {
                return path.join(process.env["TEMP"], tmpfileName);
            } else {
                return path.join("/tmp", tmpfileName);
            }
        };
    }

    if (Array.prototype.some) {
        buster.some = function (arr, fn, thisp) {
            return arr.some(fn, thisp);
        };
    } else {
        // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/some
        buster.some = function (arr, fun, thisp) {
            "use strict";
            if (arr == null) { throw new TypeError(); }
            arr = Object(arr);
            var len = arr.length >>> 0;
            if (typeof fun !== "function") { throw new TypeError(); }

            for (var i = 0; i < len; i++) {
                if (arr.hasOwnProperty(i) && fun.call(thisp, arr[i], i, arr)) {
                    return true;
                }
            }

            return false;
        };
    }

    if (Array.prototype.filter) {
        buster.filter = function (arr, fn, thisp) {
            return arr.filter(fn, thisp);
        };
    } else {
        // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/filter
        buster.filter = function (fn, thisp) {
            "use strict";
            if (this == null) { throw new TypeError(); }

            var t = Object(this);
            var len = t.length >>> 0;
            if (typeof fn != "function") { throw new TypeError(); }

            var res = [];
            for (var i = 0; i < len; i++) {
                if (i in t) {
                    var val = t[i]; // in case fun mutates this
                    if (fn.call(thisp, val, i, t)) { res.push(val); }
                }
            }

            return res;
        };
    }

    if (isNode) {
        module.exports = buster;
        buster.eventEmitter = require("./buster-event-emitter");
        Object.defineProperty(buster, "defineVersionGetter", {
            get: function () {
                return require("./define-version-getter");
            }
        });
    }

    return buster.extend(B || {}, buster);
}(setTimeout, buster));
<commit_msg>Stronger Node.JS inference<commit_after>var buster = (function (setTimeout, B) {
    var isNode = typeof require == "function" && typeof module == "object";
    var div = typeof document != "undefined" && document.createElement("div");
    var F = function () {};

    var buster = {
        bind: function bind(obj, methOrProp) {
            var method = typeof methOrProp == "string" ? obj[methOrProp] : methOrProp;
            var args = Array.prototype.slice.call(arguments, 2);
            return function () {
                var allArgs = args.concat(Array.prototype.slice.call(arguments));
                return method.apply(obj, allArgs);
            };
        },

        partial: function partial(fn) {
            var args = [].slice.call(arguments, 1);
            return function () {
                return fn.apply(this, args.concat([].slice.call(arguments)));
            };
        },

        create: function create(object) {
            F.prototype = object;
            return new F();
        },

        extend: function extend(target) {
            if (!target) { return; }
            for (var i = 1, l = arguments.length, prop; i < l; ++i) {
                for (prop in arguments[i]) {
                    target[prop] = arguments[i][prop];
                }
            }
            return target;
        },

        nextTick: function nextTick(callback) {
            if (typeof process != "undefined" && process.nextTick) {
                return process.nextTick(callback);
            }
            setTimeout(callback, 0);
        },

        functionName: function functionName(func) {
            if (!func) return "";
            if (func.displayName) return func.displayName;
            if (func.name) return func.name;
            var matches = func.toString().match(/function\s+([^\(]+)/m);
            return matches && matches[1] || "";
        },

        isNode: function isNode(obj) {
            if (!div) return false;
            try {
                obj.appendChild(div);
                obj.removeChild(div);
            } catch (e) {
                return false;
            }
            return true;
        },

        isElement: function isElement(obj) {
            return obj && obj.nodeType === 1 && buster.isNode(obj);
        },

        isArray: function isArray(arr) {
            return Object.prototype.toString.call(arr) == "[object Array]";
        },

        flatten: function flatten(arr) {
            var result = [], arr = arr || [];
            for (var i = 0, l = arr.length; i < l; ++i) {
                result = result.concat(buster.isArray(arr[i]) ? flatten(arr[i]) : arr[i]);
            }
            return result;
        },

        each: function each(arr, callback) {
            for (var i = 0, l = arr.length; i < l; ++i) {
                callback(arr[i]);
            }
        },

        map: function map(arr, callback) {
            var results = [];
            for (var i = 0, l = arr.length; i < l; ++i) {
                results.push(callback(arr[i]));
            }
            return results;
        },

        parallel: function parallel(fns, callback) {
            function cb(err, res) {
                if (typeof callback == "function") {
                    callback(err, res);
                    callback = null;
                }
            }
            if (fns.length == 0) { return cb(null, []); }
            var remaining = fns.length, results = [];
            function makeDone(num) {
                return function done(err, result) {
                    if (err) { return cb(err); }
                    results[num] = result;
                    if (--remaining == 0) { cb(null, results); }
                };
            }
            for (var i = 0, l = fns.length; i < l; ++i) {
                fns[i](makeDone(i));
            }
        },

        series: function series(fns, callback) {
            function cb(err, res) {
                if (typeof callback == "function") {
                    callback(err, res);
                }
            }
            var remaining = fns.slice();
            var results = [];
            function callNext() {
                if (remaining.length == 0) return cb(null, results);
                var promise = remaining.shift()(next);
                if (promise && typeof promise.then == "function") {
                    promise.then(buster.partial(next, null), next);
                }
            }
            function next(err, result) {
                if (err) return cb(err);
                results.push(result);
                callNext();
            }
            callNext();
        },

        countdown: function countdown(num, done) {
            return function () {
                if (--num == 0) done();
            };
        }
    };

    if (typeof process === "object" && typeof require === "function") {
        var crypto = require("crypto");
        var path = require("path");

        buster.tmpFile = function (fileName) {
            var hashed = crypto.createHash("sha1");
            hashed.update(fileName);
            var tmpfileName = hashed.digest("hex");

            if (process.platform == "win32") {
                return path.join(process.env["TEMP"], tmpfileName);
            } else {
                return path.join("/tmp", tmpfileName);
            }
        };
    }

    if (Array.prototype.some) {
        buster.some = function (arr, fn, thisp) {
            return arr.some(fn, thisp);
        };
    } else {
        // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/some
        buster.some = function (arr, fun, thisp) {
            "use strict";
            if (arr == null) { throw new TypeError(); }
            arr = Object(arr);
            var len = arr.length >>> 0;
            if (typeof fun !== "function") { throw new TypeError(); }

            for (var i = 0; i < len; i++) {
                if (arr.hasOwnProperty(i) && fun.call(thisp, arr[i], i, arr)) {
                    return true;
                }
            }

            return false;
        };
    }

    if (Array.prototype.filter) {
        buster.filter = function (arr, fn, thisp) {
            return arr.filter(fn, thisp);
        };
    } else {
        // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/filter
        buster.filter = function (fn, thisp) {
            "use strict";
            if (this == null) { throw new TypeError(); }

            var t = Object(this);
            var len = t.length >>> 0;
            if (typeof fn != "function") { throw new TypeError(); }

            var res = [];
            for (var i = 0; i < len; i++) {
                if (i in t) {
                    var val = t[i]; // in case fun mutates this
                    if (fn.call(thisp, val, i, t)) { res.push(val); }
                }
            }

            return res;
        };
    }

    if (isNode) {
        module.exports = buster;
        buster.eventEmitter = require("./buster-event-emitter");
        Object.defineProperty(buster, "defineVersionGetter", {
            get: function () {
                return require("./define-version-getter");
            }
        });
    }

    return buster.extend(B || {}, buster);
}(setTimeout, buster));
<|endoftext|>


<commit_before>const Q = require('q')
const geolib = require('geolib')
const deviceGeo = require('./get-location')
const querystring = require('../get-url-parameter')
const supportedCities = require('./supportedCities')
const browser = require('../browser')
const cookies = require('../cookies')
const modal = require('./modal')

import { getByCoords } from './postcodes'
import * as storage from '../storage'

const myLocationId = 'my-location'

const getNearest = (position) => {
  const currLatitude = position.coords.latitude
  const currLongitude = position.coords.longitude

  supportedCities.locations
    .filter((c) => c.isPublic)
    .forEach((c) => {
      const distanceInMetres = geolib.getDistance(
        { latitude: currLatitude, longitude: currLongitude },
        { latitude: c.latitude, longitude: c.longitude }
      )
      c.distance = distanceInMetres
    })
  const sorted = supportedCities.locations
    .sort((a, b) => {
      if (a.distance < b.distance) return -1
      if (a.distance > b.distance) return 1
      return 0
    })

  return sorted[0]
}

const _userSelect = (deferred) => {
  modal.init(exportedObj)
  deferred.resolve()
}

const _useMyLocation = (deferred) => {
  const defaultResolution = () => {
    let cityId = myLocationId
    const saved = cookies.get(cookies.keys.location)
    if (saved !== undefined && saved.length > 0) {
      cityId = supportedCities.get(saved).id
    }
    deferred.resolve({
      id: cityId,
      findHelpId: myLocationId,
      isSelected: true,
      latitude: 0,
      longitude: 0,
      name: 'my location',
      geoLocationUnavailable: true
    })
  }
  deviceGeo.location()
    .then((userLocation) => {
      let cityId = 'my-location'
      const saved = cookies.get(cookies.keys.location)
      if (cookies.get(cookies.keys.location) !== undefined && saved.length > 0) {
        cityId = supportedCities.get(saved).id
      }
      getByCoords(userLocation.coords, (postcode) => {
        deferred.resolve({
          id: cityId,
          findHelpId: myLocationId,
          isSelected: true,
          latitude: userLocation.coords.latitude,
          longitude: userLocation.coords.longitude,
          name: 'my location',
          postcode: postcode,
          nearestSupported: getNearest(userLocation)
        })
      }, defaultResolution)
    }, () => {
      defaultResolution()
    })
}

const _useRequested = (deferred, locationInQueryString) => {
  const requestedCity = supportedCities.get(locationInQueryString)
  if (requestedCity !== undefined) {
    deferred.resolve(requestedCity)
  } else {
    _userSelect(deferred)
  }
}

const _useSaved = (deferred) => {
  const saved = cookies.get(cookies.keys.location)
  if (saved === 'elsewhere' && deviceGeo.isAvailable()) {
    _useMyLocation(deferred)
  } else if (saved !== undefined && saved.length > 0 && saved !== myLocationId) {
    deferred.resolve(supportedCities.get(saved))
  } else {
    _userSelect(deferred)
  }
}

const _determineLocationRetrievalMethod = () => {
  let method = _useSaved
  let id = ''

  const locationInQueryString = querystring.parameter('location')
  if (locationInQueryString === myLocationId && deviceGeo.isAvailable()) {
    method = _useMyLocation
  } else if (locationInQueryString !== 'undefined' && locationInQueryString.length > 0 && locationInQueryString !== myLocationId) {
    method = _useRequested
    id = locationInQueryString
  } else {
    const locationInPath = browser.location().pathname.split('/')[1]
    const cities = supportedCities.locations.map((l) => l.id)
    if (locationInPath !== 'undefined' && locationInPath.length > 0 && cities.indexOf(locationInPath) > -1) {
      method = _useRequested
      id = locationInPath

      setCurrent(id)
    }
  }

  return {
    method: method,
    id: id
  }
}

const getSelectedLocationId = () => {
  const saved = cookies.get(cookies.keys.location)
  if (cookies.get(cookies.keys.location) !== undefined && saved.length > 0) {
    return supportedCities.get(saved).id
  }
  modal.init(exportedObj)
}

const getCurrent = () => {
  const deferred = Q.defer()
  const getLocation = _determineLocationRetrievalMethod()
  getLocation.method(deferred, getLocation.id)
  return deferred.promise
}

const getPreviouslySetPostcode = () => {
  const deferred = Q.defer()
  const userLocationState = storage.get(storage.keys.userLocationState)
  if (userLocationState) {
    deferred.resolve({
      'id': 'my-location',
      'findHelpId': 'my-location',
      'name': 'my selected postocde',
      'longitude': userLocationState.longitude,
      'latitude': userLocationState.latitude,
      'isPublic': true,
      'isSelectableInBody': false,
      'postcode': userLocationState.postcode
    })
  } else {
    const getLocation = _determineLocationRetrievalMethod()
    getLocation.method(deferred, getLocation.id)
  }

  return deferred.promise
}

const setCurrent = (newCity) => {
  if (newCity.length > 0) {
    document.cookie = `${cookies.keys.location}=${newCity};expires=Fri, 31 Dec 9999 23:59:59 GMT;path=/`
  }
}

const getViewModel = (current) => {
  const cities = supportedCities.locations.map((l) => {
    const newLocation = l
    newLocation.isSelected = l.id === current.id
    return newLocation
  })
  return cities
}

const getViewModelAll = (current) => {
  const cities = supportedCities.locations.map((l) => {
    l.isSelected = l.id === current.id
    return l
  })
  cities.push({
    id: '',
    isSelected: querystring.parameter('location') === '',
    name: 'All'
  })
  return cities
}

/**
 * initialise location dropdown with selectorId inject a callback when location selector changes
 * @param {function} onChangeLocationCallback
 * @param {string} selectorId
 */
const onChange = (onChangeLocationCallback, selectorId = '.js-location-select') => {
  const locationSelector = document.querySelector(selectorId)
  locationSelector.addEventListener('change', () => {
    var selectedLocation = locationSelector.options[locationSelector.selectedIndex].value
    setCurrent(selectedLocation)
    onChangeLocationCallback(selectedLocation)
  })
}

const exportedObj = {
  getSelectedLocationId: getSelectedLocationId,
  getPreviouslySetPostcode: getPreviouslySetPostcode,
  getCurrent: getCurrent,
  setCurrent: setCurrent,
  getViewModel: getViewModel,
  getViewModelAll: getViewModelAll,
  handler: onChange
}

module.exports = exportedObj
<commit_msg>implement missing locationSelector.setPostcode()<commit_after>const Q = require('q')
const geolib = require('geolib')
const deviceGeo = require('./get-location')
const querystring = require('../get-url-parameter')
const supportedCities = require('./supportedCities')
const browser = require('../browser')
const cookies = require('../cookies')
const modal = require('./modal')

import * as postcodes from './postcodes'
import * as storage from '../storage'

const myLocationId = 'my-location'

const getNearest = (position) => {
  const currLatitude = position.coords.latitude
  const currLongitude = position.coords.longitude

  supportedCities.locations
    .filter((c) => c.isPublic)
    .forEach((c) => {
      const distanceInMetres = geolib.getDistance(
        { latitude: currLatitude, longitude: currLongitude },
        { latitude: c.latitude, longitude: c.longitude }
      )
      c.distance = distanceInMetres
    })
  const sorted = supportedCities.locations
    .sort((a, b) => {
      if (a.distance < b.distance) return -1
      if (a.distance > b.distance) return 1
      return 0
    })

  return sorted[0]
}

const _userSelect = (deferred) => {
  modal.init(exportedObj)
  deferred.resolve()
}

const _useMyLocation = (deferred) => {
  const defaultResolution = () => {
    let cityId = myLocationId
    const saved = cookies.get(cookies.keys.location)
    if (saved !== undefined && saved.length > 0) {
      cityId = supportedCities.get(saved).id
    }
    deferred.resolve({
      id: cityId,
      findHelpId: myLocationId,
      isSelected: true,
      latitude: 0,
      longitude: 0,
      name: 'my location',
      geoLocationUnavailable: true
    })
  }
  deviceGeo.location()
    .then((userLocation) => {
      let cityId = 'my-location'
      const saved = cookies.get(cookies.keys.location)
      if (cookies.get(cookies.keys.location) !== undefined && saved.length > 0) {
        cityId = supportedCities.get(saved).id
      }
      postcodes.getByCoords(userLocation.coords, (postcode) => {
        deferred.resolve({
          id: cityId,
          findHelpId: myLocationId,
          isSelected: true,
          latitude: userLocation.coords.latitude,
          longitude: userLocation.coords.longitude,
          name: 'my location',
          postcode: postcode,
          nearestSupported: getNearest(userLocation)
        })
      }, defaultResolution)
    }, () => {
      defaultResolution()
    })
}

const _useRequested = (deferred, locationInQueryString) => {
  const requestedCity = supportedCities.get(locationInQueryString)
  if (requestedCity !== undefined) {
    deferred.resolve(requestedCity)
  } else {
    _userSelect(deferred)
  }
}

const _useSaved = (deferred) => {
  const saved = cookies.get(cookies.keys.location)
  if (saved === 'elsewhere' && deviceGeo.isAvailable()) {
    _useMyLocation(deferred)
  } else if (saved !== undefined && saved.length > 0 && saved !== myLocationId) {
    deferred.resolve(supportedCities.get(saved))
  } else {
    _userSelect(deferred)
  }
}

const _determineLocationRetrievalMethod = () => {
  let method = _useSaved
  let id = ''

  const locationInQueryString = querystring.parameter('location')
  if (locationInQueryString === myLocationId && deviceGeo.isAvailable()) {
    method = _useMyLocation
  } else if (locationInQueryString !== 'undefined' && locationInQueryString.length > 0 && locationInQueryString !== myLocationId) {
    method = _useRequested
    id = locationInQueryString
  } else {
    const locationInPath = browser.location().pathname.split('/')[1]
    const cities = supportedCities.locations.map((l) => l.id)
    if (locationInPath !== 'undefined' && locationInPath.length > 0 && cities.indexOf(locationInPath) > -1) {
      method = _useRequested
      id = locationInPath

      setCurrent(id)
    }
  }

  return {
    method: method,
    id: id
  }
}

const getSelectedLocationId = () => {
  const saved = cookies.get(cookies.keys.location)
  if (cookies.get(cookies.keys.location) !== undefined && saved.length > 0) {
    return supportedCities.get(saved).id
  }
  modal.init(exportedObj)
}

const getCurrent = () => {
  const deferred = Q.defer()
  const getLocation = _determineLocationRetrievalMethod()
  getLocation.method(deferred, getLocation.id)
  return deferred.promise
}

const buildLocationResult = (userLocationState) => {
  return {
    'id': 'my-location',
    'findHelpId': 'my-location',
    'name': 'my selected postocde',
    'longitude': userLocationState.longitude,
    'latitude': userLocationState.latitude,
    'isPublic': true,
    'isSelectableInBody': false,
    'postcode': userLocationState.postcode
  }
}

const getPreviouslySetPostcode = () => {
  const deferred = Q.defer()
  const userLocationState = storage.get(storage.keys.userLocationState)
  if (userLocationState) {
    deferred.resolve(buildLocationResult(userLocationState))
  } else {
    const getLocation = _determineLocationRetrievalMethod()
    getLocation.method(deferred, getLocation.id)
  }

  return deferred.promise
}

const setPostcode = (postcode, onSuccessCallback, onErrorCallback) => {
  postcodes.getCoords(postcode, (coordsResult) => {
    storage.set(storage.keys.userLocationState, coordsResult)
    onSuccessCallback(buildLocationResult(coordsResult))
  }, (error) => {
    onErrorCallback(error)
  })
}

const setCurrent = (newCity) => {
  if (newCity.length > 0) {
    document.cookie = `${cookies.keys.location}=${newCity};expires=Fri, 31 Dec 9999 23:59:59 GMT;path=/`
  }
}

const getViewModel = (current) => {
  const cities = supportedCities.locations.map((l) => {
    const newLocation = l
    newLocation.isSelected = l.id === current.id
    return newLocation
  })
  return cities
}

const getViewModelAll = (current) => {
  const cities = supportedCities.locations.map((l) => {
    l.isSelected = l.id === current.id
    return l
  })
  cities.push({
    id: '',
    isSelected: querystring.parameter('location') === '',
    name: 'All'
  })
  return cities
}

/**
 * initialise location dropdown with selectorId inject a callback when location selector changes
 * @param {function} onChangeLocationCallback
 * @param {string} selectorId
 */
const onChange = (onChangeLocationCallback, selectorId = '.js-location-select') => {
  const locationSelector = document.querySelector(selectorId)
  locationSelector.addEventListener('change', () => {
    var selectedLocation = locationSelector.options[locationSelector.selectedIndex].value
    setCurrent(selectedLocation)
    onChangeLocationCallback(selectedLocation)
  })
}

const exportedObj = {
  getSelectedLocationId: getSelectedLocationId,
  getPreviouslySetPostcode: getPreviouslySetPostcode,
  setPostcode: setPostcode,
  getCurrent: getCurrent,
  setCurrent: setCurrent,
  getViewModel: getViewModel,
  getViewModelAll: getViewModelAll,
  handler: onChange
}

module.exports = exportedObj
<|endoftext|>


<commit_before>Kamato.register.controller('appActivityCtrl', function ($scope, $http, $modal, ngDialog, $rootScope, $timeout, $routeParams) {

    // ====================== APP管理 top======================
    $scope.app_oper = [
		// {'tip': 'Home', 'icon': 'sa-list-home'},
		{ 'tip': 'Back', 'icon': 'sa-list-back', 'link': '#/platform/APP' },
		{ 'tip': 'Activity', 'icon': 'sa-list-activity', 'link': '#/platform/APP/' + $routeParams.APP + '/APP_activity' },
		{ 'tip': 'Info.', 'icon': 'sa-list-info', 'link': '#/platform/APP/' + $routeParams.APP + '/APP_info' },		// {'tip': 'Upload', 'icon': 'sa-list-upload', 'link': '#/platform/APP/upload'}
 		{ 'tip': 'Folder', 'icon': 'sa-list-folder', 'link': '#/platform/APP/' + $routeParams.APP + '/APP_folder' },
    ];
    // ====================== APP管理 bottom======================
    $scope.app_info = [
        {
            online: 0,
            total: 0,
            network: { in: 0, out: 0 },
            online_history: 0,
            network_history: { in: 0, out: 0 }
        }
    ];
    var users_data = []
    var dataset_users;

    var networks_datain = [];
    var networks_dataout = [];

    var dataset_networks;

    var updateInterval = 1000;
    var start = false;

    $scope.$on("$destroy", function () {
        socket.disconnect();
        socket.removeAllListeners();
    });

    var socket = io('https://simple.tanpopo.cc/' + $routeParams.APP, { autoConnect: false, secure: true });
    socket.on('connect', function () {
    });
    socket.on('disconnect', function (data) {
    });

    // 初始化資料
    socket.on('summary', function (data) {
        if ($('.main-chart').length > 0 && start == false) {
            var netin = data.history.in.reverse();
            var netout = data.history.out.reverse();
            var session = data.history.session.reverse();

            var total = 0;
            for (var i = 0; i < 300; i++) {
                var x = netin[i][0];
                var xx = netin[i][1];
                var y = netout[i][0];
                var yy = netout[i][1];
                var z = session[i][0];
                var zz = session[i][1];

                total += z;

                var netintemp = [xx, x];
                networks_datain.push(netintemp);

                var netouttemp = [yy, y];
                networks_dataout.push(netouttemp);

                var sessiontemp = [zz, z];
                users_data.push(sessiontemp);
            };

            $scope.app_info[0].online = data.current.session[0];
            $scope.app_info[0].network.in = displayByte(data.current.in[0], 'B');
            $scope.app_info[0].network.out = displayByte(data.current.out[0], 'B');
            $scope.app_info[0].total = total;
            $scope.$apply();
            start = true;

        };
    });

    socket.on('data', function (data) {
        if ($('.main-chart').length > 0 && start == true) {
            var din = data.in;
            var dout = data.out;
            var dsession = data.session;

            Get_Data(dsession, din, dout);
            $.plot($("#Users"), dataset_users, options1);
            $.plot($("#Networks"), dataset_networks, options2);
        };
    });

    $scope.init = function () {
        dataset_users = [{ label: "線上用戶", data: users_data }];
        $.plot($("#Users"), dataset_users, options1);
        dataset_networks = [{ label: "網路流量(IN)", data: networks_datain, color: '#08F' }, { label: "網路流量(OUT)", data: networks_dataout, color: '#5C6' }];
        $.plot($("#Networks"), dataset_networks, options2);
        socket.connect();
    };

    function Get_Data(num, nin, nout) {
        var x = nin[0];
        $scope.app_info[0].network.in = displayByte(x, 'B');

        var xx = nin[1];
        var y = nout[0];
        $scope.app_info[0].network.out = displayByte(y, 'B');

        var yy = nout[1];
        var z = num[0];
        $scope.app_info[0].online = z;

        var zz = num[1];

        var tempx = [xx, x];
        var tempy = [yy, y];
        var tempz = [zz, z];

        users_data.shift();
        networks_datain.shift();
        networks_dataout.shift();

        networks_datain.push(tempx);
        networks_dataout.push(tempy);
        users_data.push(tempz);
        $scope.$apply();

    };

    var options1 = {
        series: {
            lines: {
                show: true,
                lineWidth: 1.2,
                fill: true,
                shadowSize: 0
            }
        },
        colors: ['rgba(255,255,255,0.3)'],
        xaxis: {
            mode: "time",
            //tickSize: [10, "second"],
            tickFormatter: function (v, axis) {
                var date = new Date(v);
                if (date.getSeconds() % 10 == 0) {
                    var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
                    var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
                    var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
                    return minutes + ":" + seconds;
                } else {
                    return "";
                };
            },
            font: {
                lineHeight: 13,
                style: "normal",
                color: "rgba(255,255,255,1)",
            }
        },
        yaxis: {
            tickFormatter: function (v, axis) {
                return v + "";
            },
            font: {
                lineHeight: 13,
                style: "normal",
                color: "rgba(255,255,255,1)",
            }
        },
        legend: {
            labelBoxBorderColor: "#fff"
        },
        grid: {
            borderWidth: 1,
            borderColor: 'rgba(255,255,255,0.25)',
            labelMargin: 10,
            mouseActiveRadius: 6,
        },
    };

    var options2 = {
        series: {
            lines: {
                show: true,
                lineWidth: 1.2,
                fill: 1,
                fillColor: { colors: [{ opacity: 0.3 }, { opacity: 0.3 }] }
            }
        },
        xaxis: {
            mode: "time",
            //tickSize: [10, "second"],
            tickFormatter: function (v, axis) {
                var date = new Date(v);
                if (date.getSeconds() % 10 == 0) {
                    var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
                    var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
                    var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
                    return minutes + ":" + seconds;
                } else {
                    return "";
                };
            },
            font: {
                lineHeight: 13,
                style: "normal",
                color: "rgba(255,255,255,1)",
            }
        },
        yaxis: {
            tickFormatter: function (v, axis) {
                var data = displayByte(v, 'B');
                return data[0] + data[1];
            },
            font: {
                lineHeight: 13,
                style: "normal",
                color: "rgba(255,255,255,1)",
            }
        },
        legend: {
            labelBoxBorderColor: "#fff"
        },
        grid: {
            borderWidth: 1,
            borderColor: 'rgba(255,255,255,0.25)',
            labelMargin: 10,
            mouseActiveRadius: 6,
        },
    };

});<commit_msg>Fix des<commit_after>Kamato.register.controller('appActivityCtrl', function ($scope, $http, $modal, ngDialog, $rootScope, $timeout, $routeParams) {

    // ====================== APP管理 top======================
    $scope.app_oper = [
		// {'tip': 'Home', 'icon': 'sa-list-home'},
		{ 'tip': 'Back', 'icon': 'sa-list-back', 'link': '#/platform/APP' },
		{ 'tip': 'Activity', 'icon': 'sa-list-activity', 'link': '#/platform/APP/' + $routeParams.APP + '/APP_activity' },
		{ 'tip': 'Info.', 'icon': 'sa-list-info', 'link': '#/platform/APP/' + $routeParams.APP + '/APP_info' },		// {'tip': 'Upload', 'icon': 'sa-list-upload', 'link': '#/platform/APP/upload'}
 		{ 'tip': 'Folder', 'icon': 'sa-list-folder', 'link': '#/platform/APP/' + $routeParams.APP + '/APP_folder' },
    ];
    // ====================== APP管理 bottom======================
    $scope.app_info = [
        {
            online: 0,
            total: 0,
            network: { in: 0, out: 0 },
            online_history: 0,
            network_history: { in: 0, out: 0 }
        }
    ];
    var users_data = []
    var dataset_users;

    var networks_datain = [];
    var networks_dataout = [];

    var dataset_networks;

    var updateInterval = 1000;
    var start = false;

    $scope.$on("$destroy", function () {
        socket.disconnect();
        socket.removeAllListeners();
    });

    var socket = io('https://simple.tanpopo.cc/' + $routeParams.APP, { autoConnect: false, secure: true });
    socket.on('connect', function () {
    });
    socket.on('disconnect', function (data) {
    });

    // 初始化資料
    socket.on('summary', function (data) {
        if ($('.main-chart').length > 0 && start == false) {
            var netin = data.history.in.reverse();
            var netout = data.history.out.reverse();
            var session = data.history.session.reverse();

            var total = 0;
            for (var i = 0; i < 300; i++) {
                var x = netin[i][0];
                var xx = netin[i][1];
                var y = netout[i][0];
                var yy = netout[i][1];
                var z = session[i][0];
                var zz = session[i][1];

                total += z;

                var netintemp = [xx, x];
                networks_datain.push(netintemp);

                var netouttemp = [yy, y];
                networks_dataout.push(netouttemp);

                var sessiontemp = [zz, z];
                users_data.push(sessiontemp);
            };

            $scope.app_info[0].online = data.current.session[0];
            $scope.app_info[0].network.in = displayByte(data.current.in[0], 'B').join(' ');
            $scope.app_info[0].network.out = displayByte(data.current.out[0], 'B').join(' ');
            $scope.app_info[0].total = total;
            $scope.$apply();
            start = true;

        };
    });

    socket.on('data', function (data) {
        if ($('.main-chart').length > 0 && start == true) {
            var din = data.in;
            var dout = data.out;
            var dsession = data.session;

            Get_Data(dsession, din, dout);
            $.plot($("#Users"), dataset_users, options1);
            $.plot($("#Networks"), dataset_networks, options2);
        };
    });

    $scope.init = function () {
        dataset_users = [{ label: "線上用戶", data: users_data }];
        $.plot($("#Users"), dataset_users, options1);
        dataset_networks = [{ label: "網路流量(IN)", data: networks_datain, color: '#08F' }, { label: "網路流量(OUT)", data: networks_dataout, color: '#5C6' }];
        $.plot($("#Networks"), dataset_networks, options2);
        socket.connect();
    };

    function Get_Data(num, nin, nout) {
        var x = nin[0];
        $scope.app_info[0].network.in = displayByte(x, 'B').join(' ');

        var xx = nin[1];
        var y = nout[0];
        $scope.app_info[0].network.out = displayByte(y, 'B').join(' ');

        var yy = nout[1];
        var z = num[0];
        $scope.app_info[0].online = z;

        var zz = num[1];

        var tempx = [xx, x];
        var tempy = [yy, y];
        var tempz = [zz, z];

        users_data.shift();
        networks_datain.shift();
        networks_dataout.shift();

        networks_datain.push(tempx);
        networks_dataout.push(tempy);
        users_data.push(tempz);
        $scope.$apply();

    };

    var options1 = {
        series: {
            lines: {
                show: true,
                lineWidth: 1.2,
                fill: true,
                shadowSize: 0
            }
        },
        colors: ['rgba(255,255,255,0.3)'],
        xaxis: {
            mode: "time",
            //tickSize: [10, "second"],
            tickFormatter: function (v, axis) {
                var date = new Date(v);
                if (date.getSeconds() % 10 == 0) {
                    var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
                    var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
                    var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
                    return minutes + ":" + seconds;
                } else {
                    return "";
                };
            },
            font: {
                lineHeight: 13,
                style: "normal",
                color: "rgba(255,255,255,1)",
            }
        },
        yaxis: {
            tickFormatter: function (v, axis) {
                return v + "";
            },
            font: {
                lineHeight: 13,
                style: "normal",
                color: "rgba(255,255,255,1)",
            }
        },
        legend: {
            labelBoxBorderColor: "#fff"
        },
        grid: {
            borderWidth: 1,
            borderColor: 'rgba(255,255,255,0.25)',
            labelMargin: 10,
            mouseActiveRadius: 6,
        },
    };

    var options2 = {
        series: {
            lines: {
                show: true,
                lineWidth: 1.2,
                fill: 1,
                fillColor: { colors: [{ opacity: 0.3 }, { opacity: 0.3 }] }
            }
        },
        xaxis: {
            mode: "time",
            //tickSize: [10, "second"],
            tickFormatter: function (v, axis) {
                var date = new Date(v);
                if (date.getSeconds() % 10 == 0) {
                    var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
                    var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
                    var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
                    return minutes + ":" + seconds;
                } else {
                    return "";
                };
            },
            font: {
                lineHeight: 13,
                style: "normal",
                color: "rgba(255,255,255,1)",
            }
        },
        yaxis: {
            tickFormatter: function (v, axis) {
                var data = displayByte(v, 'B').join(' ');
                return data;
            },
            font: {
                lineHeight: 13,
                style: "normal",
                color: "rgba(255,255,255,1)",
            }
        },
        legend: {
            labelBoxBorderColor: "#fff"
        },
        grid: {
            borderWidth: 1,
            borderColor: 'rgba(255,255,255,0.25)',
            labelMargin: 10,
            mouseActiveRadius: 6,
        },
    };

});<|endoftext|>


<commit_before>// Copyright 2014 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
//     You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//     See the License for the specific language governing permissions and
// limitations under the License.

(function(shared, scope, testing) {
  var originalRequestAnimationFrame = window.requestAnimationFrame;
  var rafCallbacks = [];
  window.requestAnimationFrame = function(f) {
    if (rafCallbacks.length == 0 && !WEB_ANIMATIONS_TESTING) {
      originalRequestAnimationFrame(processRafCallbacks);
    }
    rafCallbacks.push(f);
  };

  function processRafCallbacks(t) {
    var processing = rafCallbacks;
    rafCallbacks = [];
    tick(t);
    processing.forEach(function(f) { f(t); });
    if (needsRetick)
      tick(t);
    applyPendingEffects();
  }

  scope.Timeline = function() {
    this.players = [];
    this.currentTime = undefined;
  };

  scope.Timeline.prototype = {
    _play: function(source) {
      var player = new scope.Player(source);
      player._timeline = this;
      this.players.push(player);
      scope.restart();
      scope.invalidateEffects();
      return player;
    }
  };

  var ticking = true;
  var hasRestartedThisFrame = false;

  scope.restart = function() {
    if (!ticking) {
      ticking = true;
      requestAnimationFrame(function() {});
      hasRestartedThisFrame = true;
    }
    return hasRestartedThisFrame;
  };

  var needsRetick = false;
  scope.invalidateEffects = function() {
    needsRetick = true;
  };

  var pendingEffects = [];
  function applyPendingEffects() {
    pendingEffects.forEach(function(f) { f(); });
  }

  var originalGetComputedStyle = window.getComputedStyle;
  Object.defineProperty(window, 'getComputedStyle', {
    configurable: true,
    enumerable: true,
    value: function() {
      if (needsRetick) tick(timeline.currentTime);
      applyPendingEffects();
      return originalGetComputedStyle.apply(this, arguments);
    },
  });

  function tick(t) {
    hasRestartedThisFrame = false;
    var timeline = window.document.timeline;
    timeline.currentTime = t;
    timeline.players.sort(function(leftPlayer, rightPlayer) {
      return leftPlayer._sequenceNumber - rightPlayer._sequenceNumber;
    });
    ticking = false;
    var updatingPlayers = timeline.players;
    timeline.players = [];

    var newPendingClears = [];
    var newPendingEffects = [];
    updatingPlayers = updatingPlayers.filter(function(player) {
      player._inTimeline = player._tick(t);

      if (!player._inEffect)
        newPendingClears.push(player._source);
      else
        newPendingEffects.push(player._source);

      if (!player.finished && !player.paused)
        ticking = true;

      return player._inTimeline;
    });

    pendingEffects.length = 0;
    pendingEffects.push.apply(pendingEffects, newPendingClears);
    pendingEffects.push.apply(pendingEffects, newPendingEffects);

    timeline.players.push.apply(timeline.players, updatingPlayers);
    needsRetick = false;

    if (ticking)
      requestAnimationFrame(function() {});
  };

  if (WEB_ANIMATIONS_TESTING) {
    testing.tick = processRafCallbacks;
    testing.isTicking = function() { return ticking; };
    testing.setTicking = function(newVal) { ticking = newVal; };
  }

  var timeline = new scope.Timeline();
  scope.timeline = timeline;
  try {
    Object.defineProperty(window.document, 'timeline', {
      configurable: true,
      get: function() { return timeline; }
    });
  } catch (e) { }
  try {
    window.document.timeline = timeline;
  } catch (e) { }

})(webAnimationsShared, webAnimationsMinifill, webAnimationsTesting);
<commit_msg>Timeline shouldnt be ticking before any animations are started<commit_after>// Copyright 2014 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
//     You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//     See the License for the specific language governing permissions and
// limitations under the License.

(function(shared, scope, testing) {
  var originalRequestAnimationFrame = window.requestAnimationFrame;
  var rafCallbacks = [];
  window.requestAnimationFrame = function(f) {
    if (rafCallbacks.length == 0 && !WEB_ANIMATIONS_TESTING) {
      originalRequestAnimationFrame(processRafCallbacks);
    }
    rafCallbacks.push(f);
  };

  function processRafCallbacks(t) {
    var processing = rafCallbacks;
    rafCallbacks = [];
    tick(t);
    processing.forEach(function(f) { f(t); });
    if (needsRetick)
      tick(t);
    applyPendingEffects();
  }

  scope.Timeline = function() {
    this.players = [];
    this.currentTime = undefined;
  };

  scope.Timeline.prototype = {
    _play: function(source) {
      var player = new scope.Player(source);
      player._timeline = this;
      this.players.push(player);
      scope.restart();
      scope.invalidateEffects();
      return player;
    }
  };

  var ticking = false;
  var hasRestartedThisFrame = false;

  scope.restart = function() {
    if (!ticking) {
      ticking = true;
      requestAnimationFrame(function() {});
      hasRestartedThisFrame = true;
    }
    return hasRestartedThisFrame;
  };

  var needsRetick = false;
  scope.invalidateEffects = function() {
    needsRetick = true;
  };

  var pendingEffects = [];
  function applyPendingEffects() {
    pendingEffects.forEach(function(f) { f(); });
  }

  var originalGetComputedStyle = window.getComputedStyle;
  Object.defineProperty(window, 'getComputedStyle', {
    configurable: true,
    enumerable: true,
    value: function() {
      if (needsRetick) tick(timeline.currentTime);
      applyPendingEffects();
      return originalGetComputedStyle.apply(this, arguments);
    },
  });

  function tick(t) {
    hasRestartedThisFrame = false;
    var timeline = window.document.timeline;
    timeline.currentTime = t;
    timeline.players.sort(function(leftPlayer, rightPlayer) {
      return leftPlayer._sequenceNumber - rightPlayer._sequenceNumber;
    });
    ticking = false;
    var updatingPlayers = timeline.players;
    timeline.players = [];

    var newPendingClears = [];
    var newPendingEffects = [];
    updatingPlayers = updatingPlayers.filter(function(player) {
      player._inTimeline = player._tick(t);

      if (!player._inEffect)
        newPendingClears.push(player._source);
      else
        newPendingEffects.push(player._source);

      if (!player.finished && !player.paused)
        ticking = true;

      return player._inTimeline;
    });

    pendingEffects.length = 0;
    pendingEffects.push.apply(pendingEffects, newPendingClears);
    pendingEffects.push.apply(pendingEffects, newPendingEffects);

    timeline.players.push.apply(timeline.players, updatingPlayers);
    needsRetick = false;

    if (ticking)
      requestAnimationFrame(function() {});
  };

  if (WEB_ANIMATIONS_TESTING) {
    testing.tick = processRafCallbacks;
    testing.isTicking = function() { return ticking; };
    testing.setTicking = function(newVal) { ticking = newVal; };
  }

  var timeline = new scope.Timeline();
  scope.timeline = timeline;
  try {
    Object.defineProperty(window.document, 'timeline', {
      configurable: true,
      get: function() { return timeline; }
    });
  } catch (e) { }
  try {
    window.document.timeline = timeline;
  } catch (e) { }

})(webAnimationsShared, webAnimationsMinifill, webAnimationsTesting);
<|endoftext|>