<commit_before>/**
 * Returns a score for the password
 *
 * @author Hendrik Rust
 * @param pass Password for evaluation
 * @return score The score of the password
 */
function scorePassword(pass) {

  	var score = 0;
  	if (!pass) return score;
  	var letters = new Object();

	for (var i=0; i<pass.length; i++) {

		letters[pass[i]] = (letters[pass[i]] || 0) + 1;
      		score += 5.0 / letters[pass[i]];

	}

  	var variations = {

		digits: /\d/.test(pass),
      		lower: /[a-z]/.test(pass),
      		upper: /[A-Z]/.test(pass),
      		nonWords: /\W/.test(pass),

	}

  	variationCount = 0;
  	for (var check in variations) variationCount += (variations[check] == true) ? 1 : 0;
  	score += (variationCount - 1) * 10;

  	return parseInt(score);

}

/**
 * Checks a password's strength based on what score it achieved
 *
 * @author Hendrik Rust
 * @param pass Password for evaluation
 * @return html The strength of the password, formatted in HTML
 */
function checkPasswordStrength(pass) {

  	var score = scorePassword(pass);
  	if (score > 80) return "Strong password";
  	if (score > 60) return "Average password";
  	if (score >= 30) return "Weak password";
	return "";

}

/**
 * Checks if a password is strong, and then returns a corresponding boolean
 *
 * @author the_DJDJ
 * @param pass Password for evaluation
 * @return boolean A boolean representing whether or not the password is strong
 */
function pass_isPasswordStrong(pass) {

	var score = scorePassword(pass);

	if (score > 80) return true;
	return false;

}

/**
 * Capitalises the first letter in an array
 *
 * @author the_DJDJ
 * @param pass The array that needs capitalisation
 * @return array The array, with only the first letter capitalised
 */
function pass_capitaliseFirstLetter(pass){

	return pass[0].toUpperCase() + pass.slice(1).toLowerCase();

}

/**
 * Filters out all special and non-alphanumeric characters so that only letters and numbers remain
 *
 * @author the_DJDJ
 * @param data The array of letters to be filtered
 * @return out An array of the filtered characters
 */
function pass_keepLetters(data){

	var out = [];

    	for (var i = 0; i < data.length; i++) if(data[i] != "") out[i] = data[i].replace(/[^a-zA-Z0-9]+/g, "");
    	return out;

}

/**
 * Chooses a strong password based on an array. Also checks for whether or not there are enough words to form a strong password
 *
 * @author the_DJDJ
 * @param data The array of letters from which a password can be selected
 */
function pass_selectWords(data) {

    	var words = pass_keepLetters(data);
    	var usedWords = [];
    	var password = "";
    	var minimumLength = 4; //can be changed

    	var rand = [];
    	var password = "";
    	var count = 0;

    	while (!pass_isPasswordStrong(password)) {

        	rand = words[Math.floor(Math.random() * words.length)];

        	if(usedWords.indexOf(rand) == -1 && rand.length >= minimumLength){

        		password += pass_capitaliseFirstLetter(rand);
        		usedWords.push(rand);

        	}

        	if(count == words.length) pass_generate();
        	count++;

	}

	$("#suggested_password").html("Random password generated for you:
"+password+"
reload
");

}

/**
 * Starts the password generation process. Is only it's own method to allow for id='suggested_password' to have two non-password values
 *
 * @author the_DJDJ
 */
function pass_start(){

	$("#suggested_password").html('Random password generated for you:
  Loading...');

	pass_generate();

}

/**
 * Generates a random URL at which to find the resources that are required to generate a password
 *
 * @author the_DJDJ
 */
function pass_generate(){

	var sections = [//"arts",
			"automobiles",
			//"books",
			"business",
			"dining",
			"education",
			//"fashion",
			"garden",
			//"health",
			//"magazine",
			//"movies",
			//"national",
			//"nyregion",
			"obituaries",
			//"opinion",
			"politics",
			"realestate",
			"science",
			"sports",
			"technology",
			"theater",
			"travel",
			//"world"
			];

	var types =    ["mostemailed",
			"mostshared",
			"mostviewed"];

	var time =     ["1",
			"7",
			"30"];

	var prefix = 'https:';
    	if (window.parent.document.location.protocol != 'https:') prefix = 'http:';

	var key = "c20545b4dc42cab4d83a7ace81ec9ac2:0:69814665";
	var address = prefix + "//api.nytimes.com/svc/mostpopular/v2/" +
		types[Math.floor(Math.random() * types.length)] + "/" +		//randomly select one of the different types
		sections[Math.floor(Math.random() * sections.length)] + "/" +	//randomly select one of the different sections
		time[Math.floor(Math.random() * time.length)] + 		//randomly select the time period (day, week, month)
		".jsonp?api-key=" + key + "&callback=pass_getWords";		//wrap using JSONP and pass_getWords() method

	$.ajax({

		url:		address,
		cache:		false,
		crossOrigin:	true,
		dataType:	'jsonp',
		success:	function(data){

			pass_getWords(data);

		}

	});

}

/**
 * Converts JSON data into an array of words that can be used to generate the password. Also checks for blank documents
 *
 * @author the_DJDJ
 * @param data The JSON data that needs to be converted
 * @param address The URL at which the data was found, in case that the data is blank
 */
function pass_getWords(data){

	var results = data.results;

	if(results.length == 0) pass_generate();
    	else pass_selectWords(results[Math.floor(Math.random() * data.results.length)].abstract.split(' '));

}
<commit_msg>Update passauto.js<commit_after>/**
 * Returns a score for the password
 *
 * @author Hendrik Rust
 * @param pass Password for evaluation
 * @return score The score of the password
 */
function scorePassword(pass) {

  	var score = 0;
  	if (!pass) return score;
  	var letters = new Object();

	for (var i=0; i<pass.length; i++) {

		letters[pass[i]] = (letters[pass[i]] || 0) + 1;
      		score += 5.0 / letters[pass[i]];

	}

  	var variations = {

		digits: /\d/.test(pass),
      		lower: /[a-z]/.test(pass),
      		upper: /[A-Z]/.test(pass),
      		nonWords: /\W/.test(pass),

	}

  	variationCount = 0;
  	for (var check in variations) variationCount += (variations[check] == true) ? 1 : 0;
  	score += (variationCount - 1) * 10;

  	return parseInt(score);

}

/**
 * Checks a password's strength based on what score it achieved
 *
 * @author Hendrik Rust
 * @param pass Password for evaluation
 * @return html The strength of the password, formatted in HTML
 */
function checkPasswordStrength(pass) {

  	var score = scorePassword(pass);
  	if (score > 80) return "Strong password";
  	if (score > 60) return "Average password";
  	if (score >= 30) return "Weak password";
	return "";

}

/**
 * Checks if a password is strong, and then returns a corresponding boolean
 *
 * @author the_DJDJ
 * @param pass Password for evaluation
 * @return boolean A boolean representing whether or not the password is strong
 */
function pass_isPasswordStrong(pass) {

	var score = scorePassword(pass);

	if (score > 80) return true;
	return false;

}

/**
 * Capitalises the first letter in an array
 *
 * @author the_DJDJ
 * @param pass The array that needs capitalisation
 * @return array The array, with only the first letter capitalised
 */
function pass_capitaliseFirstLetter(pass){

	return pass[0].toUpperCase() + pass.slice(1).toLowerCase();

}

/**
 * Filters out all special and non-alphanumeric characters so that only letters and numbers remain
 *
 * @author the_DJDJ
 * @param data The array of letters to be filtered
 * @return out An array of the filtered characters
 */
function pass_keepLetters(data){

	var out = [];

    	for (var i = 0; i < data.length; i++) if(data[i] != "") out[i] = data[i].replace(/[^a-zA-Z0-9]+/g, "");
    	return out;

}

/**
 * Chooses a strong password based on an array. Also checks for whether or not there are enough words to form a strong password
 *
 * @author the_DJDJ
 * @param data The array of letters from which a password can be selected
 */
function pass_selectWords(data) {

    	var words = pass_keepLetters(data);
    	var usedWords = [];
    	var password = "";
    	var minimumLength = 4; //can be changed

    	var rand = [];
    	var password = "";
    	var count = 0;

    	while (!pass_isPasswordStrong(password)) {

        	rand = words[Math.floor(Math.random() * words.length)];

        	if(usedWords.indexOf(rand) == -1 && rand.length >= minimumLength){

        		password += pass_capitaliseFirstLetter(rand);
        		usedWords.push(rand);

        	}

        	if(count == words.length) pass_generate();
        	count++;

	}

	$("#suggested_password").html("Random password generated for you:
"+password+"
reload
");

}

/**
 * Starts the password generation process. Is only it's own method to allow for id='suggested_password' to have two non-password values
 *
 * @author the_DJDJ
 */
function pass_start(){

	$("#suggested_password").html('Random password generated for you:
  Loading...');

	pass_generate();

}

/**
 * Generates a random URL at which to find the resources that are required to generate a password
 *
 * @author the_DJDJ
 */
function pass_generate(){

	var sections = [//"arts",
			"automobiles",
			//"books",
			"business",
			"dining",
			"education",
			//"fashion",
			"garden",
			//"health",
			//"magazine",
			//"movies",
			//"national",
			//"nyregion",
			"obituaries",
			//"opinion",
			"politics",
			"realestate",
			"science",
			"sports",
			"technology",
			//"theater",
			"travel",
			//"world"
			];

	var types =    ["mostemailed",
			"mostshared",
			"mostviewed"];

	var time =     ["1",
			"7",
			"30"];

	var prefix = 'https:';
    	if (window.parent.document.location.protocol != 'https:') prefix = 'http:';

	var key = "c20545b4dc42cab4d83a7ace81ec9ac2:0:69814665";
	var address = prefix + "//api.nytimes.com/svc/mostpopular/v2/" +
		types[Math.floor(Math.random() * types.length)] + "/" +		//randomly select one of the different types
		sections[Math.floor(Math.random() * sections.length)] + "/" +	//randomly select one of the different sections
		time[Math.floor(Math.random() * time.length)] + 		//randomly select the time period (day, week, month)
		".jsonp?api-key=" + key + "&callback=pass_getWords";		//wrap using JSONP and pass_getWords() method

	$.ajax({

		url:		address,
		cache:		false,
		crossOrigin:	true,
		dataType:	'jsonp',
		success:	function(data){

			pass_getWords(data);

		}

	});

}

/**
 * Converts JSON data into an array of words that can be used to generate the password. Also checks for blank documents
 *
 * @author the_DJDJ
 * @param data The JSON data that needs to be converted
 * @param address The URL at which the data was found, in case that the data is blank
 */
function pass_getWords(data){

	var results = data.results;

	if(results.length == 0) pass_generate();
    	else pass_selectWords(results[Math.floor(Math.random() * data.results.length)].abstract.split(' '));

}
<|endoftext|>


<commit_before>dojo.provide("dojox.editor.plugins.TextColor");

dojo.require("dijit._editor._Plugin");
dojo.require("dijit.TooltipDialog");
dojo.require("dijit.form.Button");
dojo.require("dojox.widget.ColorPicker");

dojo.require("dojo.i18n");
dojo.requireLocalization("dojox.editor.plugins", "TextColor");

dojo.experimental("dojox.editor.plugins.TextColor");

dojo.declare("dojox.editor.plugins._TextColorDropDown", [dijit._Widget, dijit._Templated], {
	// summary:
	//		A smple widget that uses/creates a dropdown with a dojox.widget.ColorPicker.  Also provides
	//		passthroughs to the value of the color picker and convenient hook points.
	// tags:
	//		private

	// templateString: String
	//		The template used to create the ColorPicker.
	templateString: "
" +
		"
" +
			"

" +
			"
" +
			"" +
				"<button dojoType='dijit.form.Button' dojoAttachPoint='_setButton'>${setButtonText}</button>" +
				" " +
				"<button dojoType='dijit.form.Button' dojoAttachPoint='_cancelButton'>${cancelButtonText}</button>" +
			"" +
		"
" +
		"
",

	// widgetsInTemplate: Boolean
	//		Flag denoting widgets are contained in the template.
	widgetsInTemplate: true,

	constructor: function(){
		// summary:
		//		Constructor over-ride so that the translated strings are mixsed in so
		//		the template fills out.
		var strings = dojo.i18n.getLocalization("dojox.editor.plugins", "TextColor");
		dojo.mixin(this, strings);
	},

	startup: function(){
		// summary:
		//		Over-ride of startup to do the basic connect setups and such.
		if(!this._started){
			this.inherited(arguments);
			this.connect(this._setButton, "onClick", dojo.hitch(this, function(){
				this.onChange(this.get("value"));
			}));
			this.connect(this._cancelButton, "onClick", dojo.hitch(this, function(){
				dijit.popup.close(this.dialog);
				this.onCancel();
			}));
			// Fully statred, so go ahead and remove the hide.
			dojo.style(this.domNode, "display", "block");
		}
	},

	_setValueAttr: function(value, priorityChange){
		// summary:
		//		Passthrough function for the color picker value.
		// value: String
		//		The value to set in the color picker
		// priorityChange:
		//		Value to indicate whether or not to trigger an onChange event.
		this._colorPicker.set("value", value, priorityChange);
	},

	_getValueAttr: function(){
		// summary:
		//		Passthrough function for the color picker value.
		return this._colorPicker.get("value");
	},

	onChange: function(value){
		// summary:
		//		Hook point to get the value when the color picker value is selected.
		// value: String
		//		The value from the color picker.
	},

	onCancel: function(){
		// summary:
		//		Hook point to get when the dialog is canceled.
	}
});

dojo.declare("dojox.editor.plugins.TextColor", dijit._editor._Plugin, {
	// summary:
	//		This plugin provides dropdown color pickers for setting text color and background color
	//		and makes use of the nicer-looking (though not entirely accessible), dojox.widget.ColorPicker.
	//
	// description:
	//		The commands provided by this plugin are:
	//		* foreColor - sets the text color
	//		* hiliteColor - sets the background color

	// Override _Plugin.buttonClass to use DropDownButton (with ColorPalette) to control this plugin
	buttonClass: dijit.form.DropDownButton,

	constructor: function(){
		this._picker = new dojox.editor.plugins._TextColorDropDown();
		dojo.body().appendChild(this._picker.domNode);
		this._picker.startup();
		this.dropDown = this._picker.dialog;
		this.connect(this._picker, "onChange", function(color){
			this.editor.execCommand(this.command, color);
		});
		this.connect(this._picker, "onCancel", function(){
			this.editor.focus();
		});
		// We do not want default command/onclick stuff.
		this.useDefaultCommand = false;
	},

	updateState: function(){
		// summary:
		//		Overrides _Plugin.updateState().  This updates the ColorPalette
		//		to show the color of the currently selected text.
		// tags:
		//		protected
		var _e = this.editor;
		var _c = this.command;
		if(!_e || !_e.isLoaded || !_c.length){
			return;
		}

		var value;
		if(this.button){
			try{
				value = _e.queryCommandValue(_c)|| "";
			}catch(e){
				//Firefox may throw error above if the editor is just loaded, ignore it
				value = "";
			}
		}

		if(value == ""){
			value = "#000000";
		}
		if(value == "transparent"){
			value = "#ffffff";
		}

		if(typeof value == "string"){
			//if RGB value, convert to hex value
			if(value.indexOf("rgb")> -1){
				value = dojo.colorFromRgb(value).toHex();
			}
		}else{	//it's an integer(IE returns an MS access #)
			value =((value & 0x0000ff)<< 16)|(value & 0x00ff00)|((value & 0xff0000)>>> 16);
			value = value.toString(16);
			value = "#000000".slice(0, 7 - value.length)+ value;

		}

		if(value !== this._picker.get('value')){
			this._picker.set('value', value, false);
		}
	},

	destroy: function(){
		// summary:
		//		Over-ride cleanup function.
		this.inherited(arguments);
		this._picker.destroyRecursive();
		delete this._picker;
	}
});

// Register this plugin.  Uses the same name as the dijit one, so you
// use one or the other, not both.
dojo.subscribe(dijit._scopeName + ".Editor.getPlugin", null, function(o){
	if(o.plugin){
		return;
	}
	switch(o.args.name){
		case "foreColor":
		case "hiliteColor":
			o.plugin = new dojox.editor.plugins.TextColor({
				command: o.args.name
			});
	}
});
<commit_msg>Set useDefaultCommand in the proto.  refs #11010<commit_after>dojo.provide("dojox.editor.plugins.TextColor");

dojo.require("dijit._editor._Plugin");
dojo.require("dijit.TooltipDialog");
dojo.require("dijit.form.Button");
dojo.require("dojox.widget.ColorPicker");

dojo.require("dojo.i18n");
dojo.requireLocalization("dojox.editor.plugins", "TextColor");

dojo.experimental("dojox.editor.plugins.TextColor");

dojo.declare("dojox.editor.plugins._TextColorDropDown", [dijit._Widget, dijit._Templated], {
	// summary:
	//		A smple widget that uses/creates a dropdown with a dojox.widget.ColorPicker.  Also provides
	//		passthroughs to the value of the color picker and convenient hook points.
	// tags:
	//		private

	// templateString: String
	//		The template used to create the ColorPicker.
	templateString: "
" +
		"
" +
			"

" +
			"
" +
			"" +
				"<button dojoType='dijit.form.Button' dojoAttachPoint='_setButton'>${setButtonText}</button>" +
				" " +
				"<button dojoType='dijit.form.Button' dojoAttachPoint='_cancelButton'>${cancelButtonText}</button>" +
			"" +
		"
" +
		"
",

	// widgetsInTemplate: Boolean
	//		Flag denoting widgets are contained in the template.
	widgetsInTemplate: true,

	constructor: function(){
		// summary:
		//		Constructor over-ride so that the translated strings are mixsed in so
		//		the template fills out.
		var strings = dojo.i18n.getLocalization("dojox.editor.plugins", "TextColor");
		dojo.mixin(this, strings);
	},

	startup: function(){
		// summary:
		//		Over-ride of startup to do the basic connect setups and such.
		if(!this._started){
			this.inherited(arguments);
			this.connect(this._setButton, "onClick", dojo.hitch(this, function(){
				this.onChange(this.get("value"));
			}));
			this.connect(this._cancelButton, "onClick", dojo.hitch(this, function(){
				dijit.popup.close(this.dialog);
				this.onCancel();
			}));
			// Fully statred, so go ahead and remove the hide.
			dojo.style(this.domNode, "display", "block");
		}
	},

	_setValueAttr: function(value, priorityChange){
		// summary:
		//		Passthrough function for the color picker value.
		// value: String
		//		The value to set in the color picker
		// priorityChange:
		//		Value to indicate whether or not to trigger an onChange event.
		this._colorPicker.set("value", value, priorityChange);
	},

	_getValueAttr: function(){
		// summary:
		//		Passthrough function for the color picker value.
		return this._colorPicker.get("value");
	},

	onChange: function(value){
		// summary:
		//		Hook point to get the value when the color picker value is selected.
		// value: String
		//		The value from the color picker.
	},

	onCancel: function(){
		// summary:
		//		Hook point to get when the dialog is canceled.
	}
});

dojo.declare("dojox.editor.plugins.TextColor", dijit._editor._Plugin, {
	// summary:
	//		This plugin provides dropdown color pickers for setting text color and background color
	//		and makes use of the nicer-looking (though not entirely accessible), dojox.widget.ColorPicker.
	//
	// description:
	//		The commands provided by this plugin are:
	//		* foreColor - sets the text color
	//		* hiliteColor - sets the background color

	// Override _Plugin.buttonClass to use DropDownButton (with ColorPalette) to control this plugin
	buttonClass: dijit.form.DropDownButton,

	// useDefaultCommand: Boolean
	//		False as we do not use the default editor command/click behavior.
	useDefaultCommand: false,

	constructor: function(){
		this._picker = new dojox.editor.plugins._TextColorDropDown();
		dojo.body().appendChild(this._picker.domNode);
		this._picker.startup();
		this.dropDown = this._picker.dialog;
		this.connect(this._picker, "onChange", function(color){
			this.editor.execCommand(this.command, color);
		});
		this.connect(this._picker, "onCancel", function(){
			this.editor.focus();
		});
	},

	updateState: function(){
		// summary:
		//		Overrides _Plugin.updateState().  This updates the ColorPalette
		//		to show the color of the currently selected text.
		// tags:
		//		protected
		var _e = this.editor;
		var _c = this.command;
		if(!_e || !_e.isLoaded || !_c.length){
			return;
		}

		var value;
		if(this.button){
			try{
				value = _e.queryCommandValue(_c)|| "";
			}catch(e){
				//Firefox may throw error above if the editor is just loaded, ignore it
				value = "";
			}
		}

		if(value == ""){
			value = "#000000";
		}
		if(value == "transparent"){
			value = "#ffffff";
		}

		if(typeof value == "string"){
			//if RGB value, convert to hex value
			if(value.indexOf("rgb")> -1){
				value = dojo.colorFromRgb(value).toHex();
			}
		}else{	//it's an integer(IE returns an MS access #)
			value =((value & 0x0000ff)<< 16)|(value & 0x00ff00)|((value & 0xff0000)>>> 16);
			value = value.toString(16);
			value = "#000000".slice(0, 7 - value.length)+ value;

		}

		if(value !== this._picker.get('value')){
			this._picker.set('value', value, false);
		}
	},

	destroy: function(){
		// summary:
		//		Over-ride cleanup function.
		this.inherited(arguments);
		this._picker.destroyRecursive();
		delete this._picker;
	}
});

// Register this plugin.  Uses the same name as the dijit one, so you
// use one or the other, not both.
dojo.subscribe(dijit._scopeName + ".Editor.getPlugin", null, function(o){
	if(o.plugin){
		return;
	}
	switch(o.args.name){
		case "foreColor":
		case "hiliteColor":
			o.plugin = new dojox.editor.plugins.TextColor({
				command: o.args.name
			});
	}
});
<|endoftext|>


<commit_before>'use strict';
var server = "http://localhost:9010/";
//var server = "http://server.localhostsro.sk:9010/";

(function () {
    // Declare app level module which depends on views, and components
    angular.module('myApp', [
        'ngRoute',
        'myApp.view1',
        'myApp.view2',
        'myApp.view3',
        'myApp.version',
        'ng-currency',
        'ngLoadingSpinner'
    ]).
        config(['$routeProvider', function ($routeProvider) {
            $routeProvider.otherwise({redirectTo: '/view1'});
        }]);

}());

<commit_msg>changing to production'<commit_after>'use strict';
//var server = "http://localhost:9010/";
var server = "http://server.localhostsro.sk:9010/";

(function () {
    // Declare app level module which depends on views, and components
    angular.module('myApp', [
        'ngRoute',
        'myApp.view1',
        'myApp.view2',
        'myApp.view3',
        'myApp.version',
        'ng-currency',
        'ngLoadingSpinner'
    ]).
        config(['$routeProvider', function ($routeProvider) {
            $routeProvider.otherwise({redirectTo: '/view1'});
        }]);

}());

<|endoftext|>


<commit_before>app.controller('PostingImageController', ['$scope', function($scope) {
	$scope.image_functions={};

	$scope.image_functions.imageTake = function(){
		 if ($scope.phonegap) {
		 	source=navigator.camera.PictureSourceType.CAMERA;
			$scope.image_functions.image(source);
		}
	};
	$scope.image_functions.imageSelect = function(){
		if ($scope.phonegap) {
			 source=navigator.camera.PictureSourceType.PHOTOLIBRARY;
			 $scope.image_functions.image(source);
		}
	};
	$scope.image_functions.image = function(source){
		navigator.camera.getPicture($scope.image_functions.onSuccess, $scope.image_functions.onFail, {
				quality : 75,
			    destinationType : navigator.camera.DestinationType.DATA_URL,
			    sourceType : source,
			    allowEdit : true,
			    encodingType: Camera.EncodingType.JPEG,
			    targetWidth: 640,
			    targetHeight: 480,
			    popoverOptions: CameraPopoverOptions,
			    saveToPhotoAlbum: false
		 });
	};
	$scope.image_functions.onSuccess = function(imageData) {
				    var image = "data:image/jpeg;base64," + imageData;
				    value={
						created : new Date().getTime(),
						msg: '',
						user: {
							id : $scope.user.getId(),
							name : $scope.user.getName()
						},
						type : 'POST'
					};
					$scope.db.post(value, function (err, response) {});

	};
	$scope.image_functions.onFail = function(message) {};
}]);
<commit_msg>FCTWO-196<commit_after>app.controller('PostingImageController', ['$scope', function($scope) {
	$scope.image_functions={};

	$scope.image_functions.imageTake = function(){
		 if ($scope.phonegap) {
		 	source=navigator.camera.PictureSourceType.CAMERA;
			$scope.image_functions.image(source);
		}
	};
	$scope.image_functions.imageSelect = function(){
		if ($scope.phonegap) {
			 source=navigator.camera.PictureSourceType.PHOTOLIBRARY;
			 $scope.image_functions.image(source);
		}
	};
	$scope.image_functions.image = function(source){
		navigator.camera.getPicture($scope.image_functions.onSuccess, $scope.image_functions.onFail, {
				quality : 75,
			    destinationType : navigator.camera.DestinationType.DATA_URL,
			    sourceType : source,
			    allowEdit : true,
			    encodingType: Camera.EncodingType.JPEG,
			    targetWidth: 640,
			    targetHeight: 480,
			    popoverOptions: CameraPopoverOptions,
			    saveToPhotoAlbum: false,
			    correctOrientation :true
		 });
	};
	$scope.image_functions.onSuccess = function(imageData) {
				    var image = "data:image/jpeg;base64," + imageData;
				    value={
						created : new Date().getTime(),
						msg: '',
						user: {
							id : $scope.user.getId(),
							name : $scope.user.getName()
						},
						type : 'POST'
					};
					$scope.db.post(value, function (err, response) {});

	};
	$scope.image_functions.onFail = function(message) {};
}]);
<|endoftext|>


<commit_before>/*! Parker v0.0.0 - MIT license */

var expect = require('chai').expect,
    CssStylesheet = require('../lib/CssStylesheet.js');

describe('The Stylesheet Parser', function() {

    it('should return (n) items of child rules for a stylesheet of (n) declarations', function() {
        var cssStylesheet = new CssStylesheet("body {border: 0} h1 {font-weight: bold;}");
        expect(cssStylesheet.getRules()).to.have.length(2);

        var multipleRules = "body {border: 0;} h1 {font-weight: bold;}"
            + " p {color: #333333; font-size: 1.2em; width: 100%} input {border: 1px solid #333333;"
            + " background-color: 1px solid #CCCCCC; padding: 0.1em; linear-gradient(45deg, #00f, #f00)}";
        cssStylesheet = new CssStylesheet(multipleRules);
        expect(cssStylesheet.getRules()).to.have.length(4);

        var multipleSelectors = "body section :first-child {background: #FFF;}"
            + "form#registration-form > input.username {font-weight: bold;}";
        cssStylesheet = new CssStylesheet(multipleSelectors);
        expect(cssStylesheet.getRules()).to.have.length(2);
    });

    it('should ignore comments', function() {
        var cssStylesheet = new CssStylesheet("body {border: 0;} /* ./* */ a {color: #fff; /* comment */} * {margin: 0;}");
        expect(cssStylesheet.getRules()).to.have.length(3);
    });
});<commit_msg>Added new unit test to test for EOL characters being ignored<commit_after>/*! Parker v0.0.0 - MIT license */

var expect = require('chai').expect,
    CssStylesheet = require('../lib/CssStylesheet.js');

describe('The Stylesheet Parser', function() {

    it('should return (n) items of child rules for a stylesheet of (n) declarations', function() {
        var cssStylesheet = new CssStylesheet("body {border: 0} h1 {font-weight: bold;}");
        expect(cssStylesheet.getRules()).to.have.length(2);

        var multipleRules = "body {border: 0;} h1 {font-weight: bold;}"
            + " p {color: #333333; font-size: 1.2em; width: 100%} input {border: 1px solid #333333;"
            + " background-color: 1px solid #CCCCCC; padding: 0.1em; linear-gradient(45deg, #00f, #f00)}";
        cssStylesheet = new CssStylesheet(multipleRules);
        expect(cssStylesheet.getRules()).to.have.length(4);

        var multipleSelectors = "body section :first-child {background: #FFF;}"
            + "form#registration-form > input.username {font-weight: bold;}";
        cssStylesheet = new CssStylesheet(multipleSelectors);
        expect(cssStylesheet.getRules()).to.have.length(2);
    });

    it('should ignore comments', function () {
        var cssStylesheet = new CssStylesheet("body {border: 0;} /* ./* */ a {color: #fff; /* comment */} * {margin: 0;}");
        expect(cssStylesheet.getRules()).to.have.length(3);
    });

    it('should ignore newline characters', function () {
        var cssStylesheet = new CssStylesheet("body {\nborder: 0;\n}\na{\ncolor: #fff;\n}");
        expect(cssStylesheet.getRules()[0]).to.equal("body {border: 0;}");
        expect(cssStylesheet.getRules()[1]).to.equal("a{color: #fff;}");
        var cssStylesheet = new CssStylesheet("body {\r\nborder: 0;\r\n}\r\na{\r\ncolor: #fff;\r\n}");
        expect(cssStylesheet.getRules()[0]).to.equal("body {border: 0;}");
        expect(cssStylesheet.getRules()[1]).to.equal("a{color: #fff;}");
    });
});<|endoftext|>


<commit_before>import * as macro from '../../../macro';
import vtkOpenGLViewNodeFactory from '../ViewNodeFactory';
import vtkShaderCache from '../ShaderCache';
import vtkViewNode from '../../SceneGraph/ViewNode';
import vtkOpenGLTextureUnitManager from '../TextureUnitManager';

/* global document */

// ----------------------------------------------------------------------------
// vtkOpenGLRenderWindow methods
// ----------------------------------------------------------------------------

export function vtkOpenGLRenderWindow(publicAPI, model) {
  // Set our className
  model.classHierarchy.push('vtkOpenGLRenderWindow');

  // Auto update style
  function updateWindow() {
    // Canvas size
    if (model.renderable) {
      model.canvas.setAttribute('width', model.size[0]);
      model.canvas.setAttribute('height', model.size[1]);
    }
    // Offscreen ?
    model.canvas.style.display = model.useOffScreen ? 'none' : 'block';

    // Cursor type
    if (model.el) {
      model.el.style.cursor = model.cursorVisibility ? model.cursor : 'none';
    }
  }
  publicAPI.onModified(updateWindow);

  // Builds myself.
  publicAPI.build = (prepass) => {
    if (prepass) {
      if (!model.renderable) {
        return;
      }

      publicAPI.prepareNodes();
      publicAPI.addMissingNodes(model.renderable.getRenderers());
      publicAPI.removeUnusedNodes();
    }
  };

  publicAPI.initialize = () => {
    if (!model.initialized) {
      model.context = publicAPI.get3DContext();
      model.textureUnitManager = vtkOpenGLTextureUnitManager.newInstance();
      model.textureUnitManager.setContext(model.context);
      model.shaderCache.setContext(model.context);
      model.initialized = true;
    }
  };

  publicAPI.makeCurrent = () => {
    model.context.makeCurrent();
  };

  publicAPI.frame = () => {
  };

  // Renders myself
  publicAPI.render = (prepass) => {
    if (prepass) {
      publicAPI.initialize();
      model.children.forEach(child => {
        child.setContext(model.context);
      });
    } else {
      publicAPI.frame();
    }
  };

  publicAPI.setContainer = el => {
    if (model.el && model.el !== el) {
      // Remove canvas from previous container
      if (model.canvas.parentNode === model.el) {
        model.el.removeChild(model.canvas);
      } else {
        console.log('Error: canvas parent node does not match container');
      }
    }

    if (model.el !== el) {
      model.el = el;
      model.el.appendChild(model.canvas);

      // Trigger modified()
      publicAPI.modified();
    }
  };

  publicAPI.isInViewport = (x, y, viewport) => {
    const vCoords = viewport.getViewport();
    const size = model.size;
    if ((vCoords[0] * size[0] <= x) &&
        (vCoords[2] * size[0] >= x) &&
        (vCoords[1] * size[1] <= y) &&
        (vCoords[3] * size[1] >= y)) {
      return true;
    }
    return false;
  };

  publicAPI.getViewportSize = viewport => {
    const vCoords = viewport.getViewport();
    const size = model.size;
    return [(vCoords[2] - vCoords[0]) * size[0], (vCoords[3] - vCoords[1]) * size[1]];
  };

  publicAPI.getViewportCenter = viewport => {
    const size = publicAPI.getViewportSize(viewport);
    return [size[0] * 0.5, size[1] * 0.5];
  };

  publicAPI.displayToNormalizedDisplay = (x, y, z) =>
    [x / (model.size[0] - 1), y / (model.size[1] - 1), z];

  publicAPI.normalizedDisplayToDisplay = (x, y, z) =>
    [x * (model.size[0] - 1), y * (model.size[1] - 1), z];

  publicAPI.get2DContext = () => model.canvas.getContext('2d');

  publicAPI.get3DContext = (options = { preserveDrawingBuffer: true, premultipliedAlpha: false }) =>
    model.canvas.getContext('webgl', options) || model.canvas.getContext('experimental-webgl', options);

  publicAPI.activateTexture = texture => {
    // Only add if it isn't already there
    const result = model.textureResourceIds.get(texture);
    if (result !== undefined) {
      model.context.activeTexture(model.context.TEXTURE0 + result);
      return;
    }

    const activeUnit = publicAPI.getTextureUnitManager().allocate();
    if (activeUnit < 0) {
      vtkErrorMacro('Hardware does not support the number of textures defined.');
      return;
    }

    model.textureResourceIds.set(texture, activeUnit);
    model.context.activeTexture(model.context.TEXTURE0 + activeUnit);
  };

  publicAPI.deactivateTexture = texture => {
    // Only deactivate if it isn't already there
    const result = model.textureResourceIds.get(texture);
    if (result !== undefined) {
      publicAPI.getTextureUnitManager().free(result);
      delete model.textureResourceIds.delete(texture);
    }
  };

  publicAPI.getTextureUnitForTexture = texture => {
    const result = model.textureResourceIds.get(texture);
    if (result !== undefined) {
      return result;
    }
    return -1;
  };

  publicAPI.getDefaultTextureInternalFormat = (vtktype, numComps, useFloat) => {
    // currently only supports four types
    switch (numComps) {
      case 1: return model.context.LUMINANCE;
      case 2: return model.context.LUMINANCE_ALPHA;
      case 3: return model.context.RGB;
      case 4:
      default:
        return model.context.RGBA;
    }
  };

  publicAPI.captureImage = (format = 'image/png') => {
    return model.canvas.toDataURL(format);
  };
}

// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------

const DEFAULT_VALUES = {
  shaderCache: null,
  initialized: false,
  context: null,
  canvas: null,
  size: [300, 300],
  cursorVisibility: true,
  cursor: 'pointer',
  textureUnitManager: null,
  textureResourceIds: null,
};

// ----------------------------------------------------------------------------

export function extend(publicAPI, model, initialValues = {}) {
  Object.assign(model, DEFAULT_VALUES, initialValues);

  // Create internal instances
  model.canvas = document.createElement('canvas');

  model.textureResourceIds = new Map();

  // Inheritance
  vtkViewNode.extend(publicAPI, model);

  model.myFactory = vtkOpenGLViewNodeFactory.newInstance();
  model.shaderCache = vtkShaderCache.newInstance();

  // Build VTK API
  macro.get(publicAPI, model, [
    'shaderCache',
    'textureUnitManager',
  ]);

  macro.setGet(publicAPI, model, [
    'initialized',
    'context',
  ]);

  macro.setGetArray(publicAPI, model, [
    'size',
  ], 2);

  // Object methods
  vtkOpenGLRenderWindow(publicAPI, model);
}

// ----------------------------------------------------------------------------

export const newInstance = macro.newInstance(extend);

// ----------------------------------------------------------------------------

export default { newInstance, extend };
<commit_msg>fix(ESLint): Fix OpenGL/RenderWindow arrow function<commit_after>import * as macro from '../../../macro';
import vtkOpenGLViewNodeFactory from '../ViewNodeFactory';
import vtkShaderCache from '../ShaderCache';
import vtkViewNode from '../../SceneGraph/ViewNode';
import vtkOpenGLTextureUnitManager from '../TextureUnitManager';

/* global document */

// ----------------------------------------------------------------------------
// vtkOpenGLRenderWindow methods
// ----------------------------------------------------------------------------

export function vtkOpenGLRenderWindow(publicAPI, model) {
  // Set our className
  model.classHierarchy.push('vtkOpenGLRenderWindow');

  // Auto update style
  function updateWindow() {
    // Canvas size
    if (model.renderable) {
      model.canvas.setAttribute('width', model.size[0]);
      model.canvas.setAttribute('height', model.size[1]);
    }
    // Offscreen ?
    model.canvas.style.display = model.useOffScreen ? 'none' : 'block';

    // Cursor type
    if (model.el) {
      model.el.style.cursor = model.cursorVisibility ? model.cursor : 'none';
    }
  }
  publicAPI.onModified(updateWindow);

  // Builds myself.
  publicAPI.build = (prepass) => {
    if (prepass) {
      if (!model.renderable) {
        return;
      }

      publicAPI.prepareNodes();
      publicAPI.addMissingNodes(model.renderable.getRenderers());
      publicAPI.removeUnusedNodes();
    }
  };

  publicAPI.initialize = () => {
    if (!model.initialized) {
      model.context = publicAPI.get3DContext();
      model.textureUnitManager = vtkOpenGLTextureUnitManager.newInstance();
      model.textureUnitManager.setContext(model.context);
      model.shaderCache.setContext(model.context);
      model.initialized = true;
    }
  };

  publicAPI.makeCurrent = () => {
    model.context.makeCurrent();
  };

  publicAPI.frame = () => {
  };

  // Renders myself
  publicAPI.render = (prepass) => {
    if (prepass) {
      publicAPI.initialize();
      model.children.forEach(child => {
        child.setContext(model.context);
      });
    } else {
      publicAPI.frame();
    }
  };

  publicAPI.setContainer = el => {
    if (model.el && model.el !== el) {
      // Remove canvas from previous container
      if (model.canvas.parentNode === model.el) {
        model.el.removeChild(model.canvas);
      } else {
        console.log('Error: canvas parent node does not match container');
      }
    }

    if (model.el !== el) {
      model.el = el;
      model.el.appendChild(model.canvas);

      // Trigger modified()
      publicAPI.modified();
    }
  };

  publicAPI.isInViewport = (x, y, viewport) => {
    const vCoords = viewport.getViewport();
    const size = model.size;
    if ((vCoords[0] * size[0] <= x) &&
        (vCoords[2] * size[0] >= x) &&
        (vCoords[1] * size[1] <= y) &&
        (vCoords[3] * size[1] >= y)) {
      return true;
    }
    return false;
  };

  publicAPI.getViewportSize = viewport => {
    const vCoords = viewport.getViewport();
    const size = model.size;
    return [(vCoords[2] - vCoords[0]) * size[0], (vCoords[3] - vCoords[1]) * size[1]];
  };

  publicAPI.getViewportCenter = viewport => {
    const size = publicAPI.getViewportSize(viewport);
    return [size[0] * 0.5, size[1] * 0.5];
  };

  publicAPI.displayToNormalizedDisplay = (x, y, z) =>
    [x / (model.size[0] - 1), y / (model.size[1] - 1), z];

  publicAPI.normalizedDisplayToDisplay = (x, y, z) =>
    [x * (model.size[0] - 1), y * (model.size[1] - 1), z];

  publicAPI.get2DContext = () => model.canvas.getContext('2d');

  publicAPI.get3DContext = (options = { preserveDrawingBuffer: true, premultipliedAlpha: false }) =>
    model.canvas.getContext('webgl', options) || model.canvas.getContext('experimental-webgl', options);

  publicAPI.activateTexture = texture => {
    // Only add if it isn't already there
    const result = model.textureResourceIds.get(texture);
    if (result !== undefined) {
      model.context.activeTexture(model.context.TEXTURE0 + result);
      return;
    }

    const activeUnit = publicAPI.getTextureUnitManager().allocate();
    if (activeUnit < 0) {
      vtkErrorMacro('Hardware does not support the number of textures defined.');
      return;
    }

    model.textureResourceIds.set(texture, activeUnit);
    model.context.activeTexture(model.context.TEXTURE0 + activeUnit);
  };

  publicAPI.deactivateTexture = texture => {
    // Only deactivate if it isn't already there
    const result = model.textureResourceIds.get(texture);
    if (result !== undefined) {
      publicAPI.getTextureUnitManager().free(result);
      delete model.textureResourceIds.delete(texture);
    }
  };

  publicAPI.getTextureUnitForTexture = texture => {
    const result = model.textureResourceIds.get(texture);
    if (result !== undefined) {
      return result;
    }
    return -1;
  };

  publicAPI.getDefaultTextureInternalFormat = (vtktype, numComps, useFloat) => {
    // currently only supports four types
    switch (numComps) {
      case 1: return model.context.LUMINANCE;
      case 2: return model.context.LUMINANCE_ALPHA;
      case 3: return model.context.RGB;
      case 4:
      default:
        return model.context.RGBA;
    }
  };

  publicAPI.captureImage = (format = 'image/png') => model.canvas.toDataURL(format);
}

// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------

const DEFAULT_VALUES = {
  shaderCache: null,
  initialized: false,
  context: null,
  canvas: null,
  size: [300, 300],
  cursorVisibility: true,
  cursor: 'pointer',
  textureUnitManager: null,
  textureResourceIds: null,
};

// ----------------------------------------------------------------------------

export function extend(publicAPI, model, initialValues = {}) {
  Object.assign(model, DEFAULT_VALUES, initialValues);

  // Create internal instances
  model.canvas = document.createElement('canvas');

  model.textureResourceIds = new Map();

  // Inheritance
  vtkViewNode.extend(publicAPI, model);

  model.myFactory = vtkOpenGLViewNodeFactory.newInstance();
  model.shaderCache = vtkShaderCache.newInstance();

  // Build VTK API
  macro.get(publicAPI, model, [
    'shaderCache',
    'textureUnitManager',
  ]);

  macro.setGet(publicAPI, model, [
    'initialized',
    'context',
  ]);

  macro.setGetArray(publicAPI, model, [
    'size',
  ], 2);

  // Object methods
  vtkOpenGLRenderWindow(publicAPI, model);
}

// ----------------------------------------------------------------------------

export const newInstance = macro.newInstance(extend);

// ----------------------------------------------------------------------------

export default { newInstance, extend };
<|endoftext|>


<commit_before>$(".nav a").on("click", function(){
   $(".nav").find(".active").removeClass("active");
   $(this).parent().addClass("active");
});
<commit_msg>Delete navbar.js<commit_after><|endoftext|>


<commit_before>
var exec = require('cordova/exec');
var channel = require('cordova/channel');

module.exports = {

  _channels: {},
  createEvent: function(type, data) {
      var event = document.createEvent('Event');
      event.initEvent(type, false, false);
      if (data) {
          for (var i in data) {
              if (data.hasOwnProperty(i)) {
                  event[i] = data[i];
              }
          }
      }
      return event;
  },
    initAirTurn: function (success, error) {
       alert("Initialized AirTurn Device");
        exec(success, error, "airturn", "initAirTurn", null);
    },

    setting: function (success, error) {
        exec(success, error, "airturn", "setting", null);
    },

   isConnected: function (success, error) {
   exec(success, error, "airturn", "isConnected", null);
   },

    getInfo: function (success, error) {
        exec(success, error, "airturn", "getInfo", null);
    },

    killApp: function (success, error) {
        exec(success, error, "airturn", "killApp", null);
    },

    fireEvent: function (type, data) {
     var event = this.createEvent( type, data );
     if (event && (event.type in this._channels)) {
         this._channels[event.type].fire(event);
     }
    },

    addAirTurnEventListener: function (eventname,f) {
     if (!(eventname in this._channels)) {
         var me = this;
         exec( function() {
           me._channels[eventname] = channel.create(eventname);
           me._channels[eventname].subscribe(f);
         }, function(err)  {
           console.log( "ERROR addEventListener: " + err)
         }, "airturn", "addEventListener", [ eventname ]);
     }
     else {
       this._channels[eventname].subscribe(f);
     }
    },

    removeEventListener: function(eventname, f) {
     if (eventname in this._channels) {
        var me = this;
        exec( function() {
          me._channels[eventname].unsubscribe(f);
        }, function(err)  {
          console.log( "ERROR removeEventListener: " + err)
        }, "airturn", "removeEventListener", [ eventname ]);
     }
    }

};

<commit_msg>Update airturn.js<commit_after>
var exec = require('cordova/exec');
var channel = require('cordova/channel');

module.exports = {

  _channels: {},
  createEvent: function(type, data) {
      var event = document.createEvent('Event');
      event.initEvent(type, false, false);
      if (data) {
          for (var i in data) {
              if (data.hasOwnProperty(i)) {
                  event[i] = data[i];
              }
          }
      }
      return event;
  },
    initAirTurn: function (success, error) {
        exec(success, error, "airturn", "initAirTurn", null);
    },

    setting: function (success, error) {
        exec(success, error, "airturn", "setting", null);
    },

   isConnected: function (success, error) {
   exec(success, error, "airturn", "isConnected", null);
   },

    getInfo: function (success, error) {
        exec(success, error, "airturn", "getInfo", null);
    },

    killApp: function (success, error) {
        exec(success, error, "airturn", "killApp", null);
    },

    fireEvent: function (type, data) {
     var event = this.createEvent( type, data );
     if (event && (event.type in this._channels)) {
         this._channels[event.type].fire(event);
     }
    },

    addAirTurnEventListener: function (eventname,f) {
     if (!(eventname in this._channels)) {
         var me = this;
         exec( function() {
           me._channels[eventname] = channel.create(eventname);
           me._channels[eventname].subscribe(f);
         }, function(err)  {
           console.log( "ERROR addEventListener: " + err)
         }, "airturn", "addEventListener", [ eventname ]);
     }
     else {
       this._channels[eventname].subscribe(f);
     }
    },

    removeEventListener: function(eventname, f) {
     if (eventname in this._channels) {
        var me = this;
        exec( function() {
          me._channels[eventname].unsubscribe(f);
        }, function(err)  {
          console.log( "ERROR removeEventListener: " + err)
        }, "airturn", "removeEventListener", [ eventname ]);
     }
    }

};

<|endoftext|>


<commit_before>// View model for the page
function pageViewModel(gvm) {
    // Page specific i18n bindings
    gvm.app  = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("WorksheetNameRapport");}, gvm);
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("HomeRapportTitle");}, gvm);
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectRapportName");}, gvm);
    gvm.homeManual = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("WorksheetRapportManual");}, gvm);

    gvm.tabledata = ko.observableArray([]);

    // Table i18n bindings
    gvm.courseID = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("courseID");}, gvm);
    gvm.courseName = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("courseName");}, gvm);
    gvm.volgStatus = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("volgStatus");}, gvm);
    gvm.courseAction = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("courseAction");}, gvm);

    //get all students
    function getAllStudents() {
        students = [];
        studentsid = [];
        $.getJSON('/api/allstudents', function(data) {
            $.each(data, function(i, item) {
                students.push(item.firstname + " " + item.lastname);
                studentsid.push(item.id);
            });
        });
        return students;
    }

    function initPage() {
        $("#errormessage").hide();

        $('#studentsComplete').autocomplete({ source: getAllStudents() });

        $.getJSON('/api/currentuser', function (data) {
            viewModel.userId = data.id;
            viewModel.updateCourseRapport();
        });
    }
}
<commit_msg>manageStudentPage Maken students ophalen<commit_after>// View model for the page
function pageViewModel(gvm) {
    // Page specific i18n bindings
    gvm.app  = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("WorksheetNameRapport");}, gvm);
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("HomeRapportTitle");}, gvm);
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectRapportName");}, gvm);
    gvm.homeManual = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("WorksheetRapportManual");}, gvm);

    gvm.tabledata = ko.observableArray([]);

    // Table i18n bindings
    gvm.courseID = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("courseID");}, gvm);
    gvm.courseName = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("courseName");}, gvm);
    gvm.volgStatus = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("volgStatus");}, gvm);
    gvm.courseAction = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("courseAction");}, gvm);

    //get all students
    function getAllStudents() {
        alert("hier");
        students = [];
        studentsid = [];
        $.getJSON('/api/allstudents', function(data) {
            $.each(data, function(i, item) {
                students.push(item.firstname + " " + item.lastname);
                studentsid.push(item.id);
            });
        });
        return students;
    }

    function initPage() {
        $("#errormessage").hide();

        $('#studentsComplete').autocomplete({ source: getAllStudents() });

        $.getJSON('/api/currentuser', function (data) {
            viewModel.userId = data.id;
            viewModel.updateCourseRapport();
        });
    }
}
<|endoftext|>


<commit_before>(function(window){
    var pretty = {

    };
    if(typeof define === 'function' && define.amd) {
        define(pretty);
    }
    else {
        window.pretty = pretty;
    }
})(window);<commit_msg>Added JSON parser<commit_after>(function(window){
    var pretty = {
        parse: function(data, data_type) {
            var func_name = 'parse_' + data_type;
            try {
                return '
' + this[func_name](data) + '
';
            }
            catch(e) {
                return false;
            }
        },
        parse_json: function(data) {
            var result = '';
            var value_type = data == null ? 'null' : data.constructor.name.toLowerCase();
            switch(value_type) {
                case 'object':
                    var children = '';
                    var key_num=0, key_count = Object.keys(data).length;
                    for(child in data) {
                        children += '
' + child + ': ' + this.parse_json(data[child]) + (key_num<key_count-1 ? ',' : '') + '
';
                        key_num++;
                    }
                    result = '{' + ((children != '') ? '
' + children + '
' : '') + '}';
                    break;
                case 'array':
                    var elements = '';
                    for(var i=0; i<data.length; i++) {
                        var element = data[i];
                        elements += '
' + this.parse_json(element) + (i<data.length-1 ? ',' : '') + '
';
                    }
                    result = '[' + ((elements != '') ? '
' + elements + '
' : '') + ']';
                    break;
                case 'null':
                    result = 'null';
                    break;
                case 'string':
                    result = '"' + data + '"';
                    break;
                default:
                    result = '' + data + '';
                    break;
            }
            return result;
        }
    };
    if(typeof define === 'function' && define.amd) {
        define(pretty);
    }
    else {
        window.pretty = pretty;
    }
})(window);<|endoftext|>


<commit_before>/**
 * The module exports are used by the [thing-it-node].
 * the first couple before state are mandatory for the device.
 *
 * State will be shown in many default screens and can very easily
 * be accessed in the HTML UI and other places.
 *
 * Services will be exposed in UIs as invocable by the user
 * and they will be exposed for orchestration.
 *
 * Configuration will be displayed when adding a device
 * on www.thing-it.com and in allows the device to access
 * the users' values during device creation on www.thing-it.com
 *
 */

module.exports = {
    metadata: {
        family: "weather",
        plugin: "weather",
        label: "Weather",
        tangible: true,
        discoverable: true,
        dataTypes: {
            sensorType: {
                family: "enumeration",
                values: [{
                    id: "CURRENT",
                    label: "Current Weather"
                }, {
                    id: "FORECAST",
                    label: "Forecast Weather"
                }]
            }
        },
        state: [{
            id: "temperature",
            label: "Temperature",
            type: {
                id: "decimal"
            }
        }, {
            id: "temperatureUnit",
            label: "Temperature Unit",
            type: {
                id: "string"
            }
        }, {
            id: "barometricPressure",
            label: "Barometric Pressure",
            type: {
                id: "decimal"
            }
        }, {
            id: "humidity",
            label: "Humidity",
            type: {
                id: "decimal"
            }
        }, {
            id: "weatherMain",
            label: "Weather Main",
            type: {
                id: "string"
            }
        }, {
            id: "weatherDescription",
            label: "Weather Description",
            type: {
                id: "string"
            }
        }, {
            id: "weatherIconUrl",
            label: "Weather Description",
            type: {
                id: "string"
            }
        }, {
            id: "cityId",
            label: "City Id",
            type: {
                id: "string"
            }
        }, {
            id: "cityName",
            label: "City Name",
            type: {
                id: "string"
            }
        }, {
            id: "clouds",
            label: "Cloud Percentage",
            type: {
                id: "integer"
            }
        }, {
            id: "rainLast3h",
            label: "Rain Last 3h",
            type: {
                id: "integer"
            }
        }, {
            id: "snowLast3h",
            label: "Snow Last 3h",
            type: {
                id: "integer"
            }
        }, {
            id: "windSpeed",
            label: "Wind Speed",
            type: {
                id: "integer"
            }
        }, {
            id: "windSpeedUnit",
            label: "Wind Speed Unit",
            type: {
                id: "string"
            }
        }, {
            id: "windDirection",
            label: "Wind Direction",
            type: {
                id: "integer"
            }
        }, {
            id: "sunrise",
            label: "Sunrise",
            type: {
                id: "integer"
            }
        }, {
            id: "sunset",
            label: "Sunset",
            type: {
                id: "integer"
            }
        }, {
            id: "forecastTimestamp",
            label: "Forecast Timestamp",
            type: {
                id: "any"
            }
        }, {
            id: "forecastTemperature",
            label: "Forecast Temperature",
            type: {
                id: "any"
            }
        }, {
            id: "forecastWeatherMain",
            label: "Forecast Weather Main",
            type: {
                id: "any"
            }
        }, {
            id: "forecastRain",
            label: "Forecast Rain",
            type: {
                id: "any"
            }
        }, {
            id: "forecastSnow",
            label: "Forecast Snow",
            type: {
                id: "any"
            }
        }],
        actorTypes: [],
        sensorTypes: [],
        services: [{
            id: "update",
            label: "Update"
        }],
        configuration: [{
            id: "cityName",
            label: "City Name",
            type: {
                id: "string"
            }
        }, {
            id: "countryCode",
            label: "Country Code",
            type: {
                id: "string"
            }
        }, {
            id: "languageCode",
            label: "Language Code",
            type: {
                id: "string"
            }
        }, {
            id: "units",
            label: "Units",
            type: {
                id: "string"
            }
        }, {
            id: "updateFrequencySeconds",
            label: "Update Frequency Seconds",
            type: {
                id: "integer"
            }
        }, {
            id: "openWeatherMapKey",
            label: "Open Weather Map Key",
            type: {
                id: "string"
            }
        }, {
            label: "Weather Type",
            id: "weatherType",
            type: {
                family: "reference",
                id: "weatherType"
            },
            defaultValue: "CURRENT"
        }]
    },

    /**
     * Invoked during start up to create the instance of
     * Weather for this specific device.
     *
     */
    create: function (device) {
        return new Weather();
    },

    /**
     * Discovery is an advanced function we don't need
     * for our Hello World example.
     *
     */
    discovery: function (options) {
        var discovery = new WeatherDiscovery();
        discovery.options = options;
        return discovery;
    }
};

var q = require('q');
var request;
var https;
//var WorldConnectionAPI;

/**
 * Discovery is an advanced function we don't need
 * for our Hello World example.
 *
 */
function WeatherDiscovery() {
    /**
     *
     */
    WeatherDiscovery.prototype.start = function () {
    };

    /**
     *
     */
    WeatherDiscovery.prototype.stop = function () {
    };
}

/**
 *
 */
function Weather() {

    var updateInterval;

    /**
     * - Makes initial call to weather service
     * - Sets up update every 10 minutes
     * - Simulation mode isn't neded for this device
     *
     */
    Weather.prototype.start = function () {
        var deferred = q.defer();

        if(!this.configuration.weatherType) this.configuration.weatherType = "CURRENT";

        // Initialize state values
        this.state = {
            temperature: null,
            barometricPressure: null,
            humidity: null,
            weatherMain: null,
            weatherDescription: null,
            weatherIconURL: null,
            cityId: null,
            cityName: null,
            clouds: 0,
            rainLast3h: 0,
            snowLast3h: 0,
            windSpeed: 0,
            windDirection: 0,
            sunrise: 0,
            sunset: 0,
            forecastTimestamp: [],
            forecastTemperature: [],
            forecastWeatherMain: [],
            forecastRain: [],
            forecastSnow: []
        };

        this.configError = false;

        if ((typeof this.configuration.openWeatherMapKey === undefined ) || !this.configuration.openWeatherMapKey || ("" == this.configuration.openWeatherMapKey)) {
            this.logError("An OpenWeatherMap Key is required for this device to work.");
            this.configError = true;
        }

        if ((typeof this.configuration.cityName === undefined ) || !this.configuration.cityName || ("" == this.configuration.cityName)) {
            this.configuration.cityName = "Frankfurt am Main";
        }

        if ((typeof this.configuration.countryCode === undefined ) || !this.configuration.countryCode || ("" == this.configuration.countryCode)) {
            this.configuration.countryCode = "de";
        }

        if ("metric" == this.configuration.units) {
            this.state.temperatureUnit = "C";
            this.state.windSpeedUnit = "mps";
        } else if ("imperial" == this.configuration.units) {
            this.state.temperatureUnit = "F";
            this.state.windSpeedUnit = "fps";
        } else {
            this.configuration.units = "metric";
            this.state.temperatureUnit = "C";
            this.state.windSpeedUnit = "mps";
        }

        if ((typeof this.configuration.languageCode === undefined ) || !this.configuration.languageCode || ("" == this.configuration.languageCode)) {
            this.configuration.languageCode = "de";
        }

        if ((typeof this.configuration.updateFrequencySeconds === undefined ) || !this.configuration.updateFrequencySeconds || (0 == this.configuration.updateFrequencySeconds)) {
            this.configuration.updateFrequencySeconds = 600;
        }

        this.logDebug("Configuration", this.configuration);

        if (this.isSimulated()) {
            // ignore, all we need is an internet connection.
        }

        this.logInfo("Starting up Weather.");

        if(this.configuration.weatherType === "CURRENT"){
            this.getWeather();
            this.updateInterval = setInterval(function () {
                this.getWeather();
            }.bind(this), this.configuration.updateFrequencySeconds * 1000);
            deferred.resolve();
        }
        if(this.configuration.weatherType === "FORECAST") {
            this.getForecast();
            this.updateInterval = setInterval(function () {
                this.getForecast();
            }.bind(this), this.configuration.updateFrequencySeconds * 1000);
            deferred.resolve();
        }
        return deferred.promise;
    };

    Weather.prototype.stop = function () {
        clearInterval(this.updateInterval);
    }

    /**
     * - Connects to OpenWeatherMap
     * - Sets the status
     */
    Weather.prototype.getWeather = function () {
        var deferred = q.defer();

        if (this.configError) {
            this.logError("Configuration error - cannot retrieve weather info.");
        } else {
            this.logInfo("Requesting weather update from http://api.openweathermap.org/");

            this.logDebug("Polling weather.", this.configuration);

            var url = "http://api.openweathermap.org/data/2.5/weather?q=" + this.configuration.cityName +
                "," + this.configuration.countryCode + "&units=" + this.configuration.units + "&lang=" +
                this.configuration.languageCode + "&APPID=" + this.configuration.openWeatherMapKey;

            this.logDebug("Request URL", url);

            if (!request) {
                request = require('request');
            }

            request.get({
                url: url
            }, function (error, response, body) {
                if (error) {
                    this.logError("Error communicating to weather service.", error, body);
                    deferred.reject("Error communicating to weather service.");
                }
                else {
                    try {
                        var weatherData = JSON.parse(body);

                        if ((weatherData.cod) && (200 != weatherData.cod)) {
                            var errorMessage = 'Could not get weather. Error code ' + weatherData.cod + ' with message "'
                                + weatherData.message + '".';
                            this.logError(errorMessage);
                            deferred.reject(errorMessage);
                        } else {
                            this.state = {
                                temperatureUnit: this.state.temperatureUnit,
                                temperature: weatherData.main.temp,
                                barometricPressure: weatherData.main.pressure,
                                humidity: weatherData.main.humidity,
                                weatherMain: weatherData.weather[0].main,
                                weatherDescription: weatherData.weather[0].description,
                                weatherIconURL: "http://openweathermap.org/img/w/" + weatherData.weather[0].icon + ".png",
                                cityId: weatherData.id,
                                cityName: weatherData.name,
                                clouds: weatherData.clouds.all,
                                windSpeed: weatherData.wind.speed,
                                windSpeedUnit: this.state.windSpeedUnit,
                                windDirection: weatherData.wind.deg,
                                sunrise: new Date(weatherData.sys.sunrise * 1000),
                                sunset: new Date(weatherData.sys.sunset * 1000)
                            };

                            try {
                                this.state.rainLast3h = weatherData.rain['3h'];
                            } catch (e) {
                                //ignore
                            }

                            try {
                                this.state.snowLast3h = weatherData.snow['3h'];
                            } catch (e) {
                                //ignore
                            }

                            this.publishStateChange();
                            deferred.resolve();
                        }
                    } catch (e) {
                        this.logError(e);
                        deferred.reject(e);
                    }
                }
            }.bind(this));
        }

        return deferred.promise;
    };

    /**
     *
     */

    Weather.prototype.getForecast = function () {
        var deferred = q.defer();

        if (this.configError) {
            this.logError("Configuration error - cannot retrieve weather info.");
        } else {
            this.logInfo("Requesting weather update from http://api.openweathermap.org/");

            this.logDebug("Polling weather.", this.configuration);

            var url = "http://api.openweathermap.org/data/2.5/forecast?q=" + this.configuration.cityName +
                "," + this.configuration.countryCode + "&units=" + this.configuration.units + "&lang=" +
                this.configuration.languageCode + "&APPID=" + this.configuration.openWeatherMapKey;

            this.logDebug("Request URL", url);

            if (!request) {
                request = require('request');
            }

            request.get({
                url: url
            }, function (error, response, body) {
                if (error) {
                    this.logError("Error communicating to weather service.", error, body);
                    deferred.reject("Error communicating to weather service.");
                }
                else {
                    try {
                        var weatherData = JSON.parse(body);

                        if ((weatherData.cod) && (200 != weatherData.cod)) {
                            var errorMessage = 'Could not get weather forecast. Error code ' + weatherData.cod + ' with message "'
                                + weatherData.message + '".';
                            this.logError(errorMessage);
                            deferred.reject(errorMessage);
                        } else {
                            let timeArray = [];
                            let tempArray = [];
                            let weatherMainArray = [];
                            let rainArray = [];
                            let snowArray = [];
                            for(let n in weatherData.list){
                                timeArray.push(new Date(weatherData.list[n].dt*1000));
                                tempArray.push(weatherData.list[n].main.temp);
                                weatherMainArray.push(weatherData.list[n].weather[0].main);
                                try {
                                    if (weatherData.list[n].rain['3h'] === undefined) rainArray.push(0);
                                    else rainArray.push(weatherData.list[n].rain['3h']);
                                }catch (e) {
                                    rainArray.push(0);//ignore
                                }
                                try {
                                    if (weatherData.list[n].snow['3h'] === undefined) snowArray.push(0);
                                    else snowArray.push(weatherData.list[n].snow['3h']);
                                }catch (e) {
                                    snowArray.push(0);//ignore
                                }
                            }

                            this.state = {
                                forecastTimestamp: timeArray,
                                forecastTemperature: tempArray,
                                // barometricPressure: weatherData.main.pressure,
                                // humidity: weatherData.main.humidity,
                                forecastWeatherMain: weatherMainArray,
                                // weatherDescription: weatherData.weather[0].description,
                                // weatherIconURL: "http://openweathermap.org/img/w/" + weatherData.weather[0].icon + ".png",
                                // clouds: weatherData.clouds.all,
                                // windSpeed: weatherData.wind.speed,
                                // windSpeedUnit: this.state.windSpeedUnit,
                                // windDirection: weatherData.wind.deg,
                                forecastRain: rainArray,
                                forecastSnow: snowArray
                            };

                            this.publishStateChange();
                            deferred.resolve();
                        }
                    } catch (e) {
                        this.logError(e);
                        deferred.reject(e);
                    }
                }
            }.bind(this));
        }

        return deferred.promise;
    };

    /**
     *
     */
    Weather.prototype.update = function () {
        this.getWeather();
    }

    /**
     *
     */
    Weather.prototype.setState = function (state) {
        this.state = state;

        this.publishStateChange();
    };

    /**
     *
     */
    Weather.prototype.getState = function () {
        return this.state;
    };

}
<commit_msg>TI-4475 operationalState shoud be OK, only after connection to the device for group 4<commit_after>/**
 * The module exports are used by the [thing-it-node].
 * the first couple before state are mandatory for the device.
 *
 * State will be shown in many default screens and can very easily
 * be accessed in the HTML UI and other places.
 *
 * Services will be exposed in UIs as invocable by the user
 * and they will be exposed for orchestration.
 *
 * Configuration will be displayed when adding a device
 * on www.thing-it.com and in allows the device to access
 * the users' values during device creation on www.thing-it.com
 *
 */

module.exports = {
    metadata: {
        family: "weather",
        plugin: "weather",
        label: "Weather",
        tangible: true,
        discoverable: true,
        dataTypes: {
            sensorType: {
                family: "enumeration",
                values: [{
                    id: "CURRENT",
                    label: "Current Weather"
                }, {
                    id: "FORECAST",
                    label: "Forecast Weather"
                }]
            }
        },
        state: [{
            id: "temperature",
            label: "Temperature",
            type: {
                id: "decimal"
            }
        }, {
            id: "temperatureUnit",
            label: "Temperature Unit",
            type: {
                id: "string"
            }
        }, {
            id: "barometricPressure",
            label: "Barometric Pressure",
            type: {
                id: "decimal"
            }
        }, {
            id: "humidity",
            label: "Humidity",
            type: {
                id: "decimal"
            }
        }, {
            id: "weatherMain",
            label: "Weather Main",
            type: {
                id: "string"
            }
        }, {
            id: "weatherDescription",
            label: "Weather Description",
            type: {
                id: "string"
            }
        }, {
            id: "weatherIconUrl",
            label: "Weather Description",
            type: {
                id: "string"
            }
        }, {
            id: "cityId",
            label: "City Id",
            type: {
                id: "string"
            }
        }, {
            id: "cityName",
            label: "City Name",
            type: {
                id: "string"
            }
        }, {
            id: "clouds",
            label: "Cloud Percentage",
            type: {
                id: "integer"
            }
        }, {
            id: "rainLast3h",
            label: "Rain Last 3h",
            type: {
                id: "integer"
            }
        }, {
            id: "snowLast3h",
            label: "Snow Last 3h",
            type: {
                id: "integer"
            }
        }, {
            id: "windSpeed",
            label: "Wind Speed",
            type: {
                id: "integer"
            }
        }, {
            id: "windSpeedUnit",
            label: "Wind Speed Unit",
            type: {
                id: "string"
            }
        }, {
            id: "windDirection",
            label: "Wind Direction",
            type: {
                id: "integer"
            }
        }, {
            id: "sunrise",
            label: "Sunrise",
            type: {
                id: "integer"
            }
        }, {
            id: "sunset",
            label: "Sunset",
            type: {
                id: "integer"
            }
        }, {
            id: "forecastTimestamp",
            label: "Forecast Timestamp",
            type: {
                id: "any"
            }
        }, {
            id: "forecastTemperature",
            label: "Forecast Temperature",
            type: {
                id: "any"
            }
        }, {
            id: "forecastWeatherMain",
            label: "Forecast Weather Main",
            type: {
                id: "any"
            }
        }, {
            id: "forecastRain",
            label: "Forecast Rain",
            type: {
                id: "any"
            }
        }, {
            id: "forecastSnow",
            label: "Forecast Snow",
            type: {
                id: "any"
            }
        }],
        actorTypes: [],
        sensorTypes: [],
        services: [{
            id: "update",
            label: "Update"
        }],
        configuration: [{
            id: "cityName",
            label: "City Name",
            type: {
                id: "string"
            }
        }, {
            id: "countryCode",
            label: "Country Code",
            type: {
                id: "string"
            }
        }, {
            id: "languageCode",
            label: "Language Code",
            type: {
                id: "string"
            }
        }, {
            id: "units",
            label: "Units",
            type: {
                id: "string"
            }
        }, {
            id: "updateFrequencySeconds",
            label: "Update Frequency Seconds",
            type: {
                id: "integer"
            }
        }, {
            id: "openWeatherMapKey",
            label: "Open Weather Map Key",
            type: {
                id: "string"
            }
        }, {
            label: "Weather Type",
            id: "weatherType",
            type: {
                family: "reference",
                id: "weatherType"
            },
            defaultValue: "CURRENT"
        }]
    },

    /**
     * Invoked during start up to create the instance of
     * Weather for this specific device.
     *
     */
    create: function (device) {
        return new Weather();
    },

    /**
     * Discovery is an advanced function we don't need
     * for our Hello World example.
     *
     */
    discovery: function (options) {
        var discovery = new WeatherDiscovery();
        discovery.options = options;
        return discovery;
    }
};

var q = require('q');
var request;
var https;
//var WorldConnectionAPI;

/**
 * Discovery is an advanced function we don't need
 * for our Hello World example.
 *
 */
function WeatherDiscovery() {
    /**
     *
     */
    WeatherDiscovery.prototype.start = function () {
    };

    /**
     *
     */
    WeatherDiscovery.prototype.stop = function () {
    };
}

/**
 *
 */
function Weather() {

    var updateInterval;

    /**
     * - Makes initial call to weather service
     * - Sets up update every 10 minutes
     * - Simulation mode isn't neded for this device
     *
     */
    Weather.prototype.start = function () {
        var deferred = q.defer();

        this.operationalState = {
            status: 'PENDING',
            message: 'Waiting for initialization...'
        };
        this.publishOperationalStateChange();

        if(!this.configuration.weatherType) this.configuration.weatherType = "CURRENT";

        // Initialize state values
        this.state = {
            temperature: null,
            barometricPressure: null,
            humidity: null,
            weatherMain: null,
            weatherDescription: null,
            weatherIconURL: null,
            cityId: null,
            cityName: null,
            clouds: 0,
            rainLast3h: 0,
            snowLast3h: 0,
            windSpeed: 0,
            windDirection: 0,
            sunrise: 0,
            sunset: 0,
            forecastTimestamp: [],
            forecastTemperature: [],
            forecastWeatherMain: [],
            forecastRain: [],
            forecastSnow: []
        };

        this.configError = false;

        if ((typeof this.configuration.openWeatherMapKey === undefined ) || !this.configuration.openWeatherMapKey || ("" == this.configuration.openWeatherMapKey)) {
            this.logError("An OpenWeatherMap Key is required for this device to work.");
            this.configError = true;
        }

        if ((typeof this.configuration.cityName === undefined ) || !this.configuration.cityName || ("" == this.configuration.cityName)) {
            this.configuration.cityName = "Frankfurt am Main";
        }

        if ((typeof this.configuration.countryCode === undefined ) || !this.configuration.countryCode || ("" == this.configuration.countryCode)) {
            this.configuration.countryCode = "de";
        }

        if ("metric" == this.configuration.units) {
            this.state.temperatureUnit = "C";
            this.state.windSpeedUnit = "mps";
        } else if ("imperial" == this.configuration.units) {
            this.state.temperatureUnit = "F";
            this.state.windSpeedUnit = "fps";
        } else {
            this.configuration.units = "metric";
            this.state.temperatureUnit = "C";
            this.state.windSpeedUnit = "mps";
        }

        if ((typeof this.configuration.languageCode === undefined ) || !this.configuration.languageCode || ("" == this.configuration.languageCode)) {
            this.configuration.languageCode = "de";
        }

        if ((typeof this.configuration.updateFrequencySeconds === undefined ) || !this.configuration.updateFrequencySeconds || (0 == this.configuration.updateFrequencySeconds)) {
            this.configuration.updateFrequencySeconds = 600;
        }

        this.logDebug("Configuration", this.configuration);

        if (this.isSimulated()) {
            // ignore, all we need is an internet connection.
        }

        this.logInfo("Starting up Weather.");

        if(this.configuration.weatherType === "CURRENT"){
            this.getWeather();
            this.updateInterval = setInterval(function () {
                this.getWeather();
            }.bind(this), this.configuration.updateFrequencySeconds * 1000);

            this.operationalState = {
                status: 'OK',
                message: 'Weather successfully initialized'
            }
            this.publishOperationalStateChange();

            deferred.resolve();
        }
        if(this.configuration.weatherType === "FORECAST") {
            this.getForecast();
            this.updateInterval = setInterval(function () {
                this.getForecast();
            }.bind(this), this.configuration.updateFrequencySeconds * 1000);

            this.operationalState = {
                status: 'OK',
                message: 'Weather successfully initialized'
            }
            this.publishOperationalStateChange();

            deferred.resolve();
        }
        return deferred.promise;
    };

    Weather.prototype.stop = function () {
        clearInterval(this.updateInterval);
    }

    /**
     * - Connects to OpenWeatherMap
     * - Sets the status
     */
    Weather.prototype.getWeather = function () {
        var deferred = q.defer();

        if (this.configError) {
            this.logError("Configuration error - cannot retrieve weather info.");
        } else {
            this.logInfo("Requesting weather update from http://api.openweathermap.org/");

            this.logDebug("Polling weather.", this.configuration);

            var url = "http://api.openweathermap.org/data/2.5/weather?q=" + this.configuration.cityName +
                "," + this.configuration.countryCode + "&units=" + this.configuration.units + "&lang=" +
                this.configuration.languageCode + "&APPID=" + this.configuration.openWeatherMapKey;

            this.logDebug("Request URL", url);

            if (!request) {
                request = require('request');
            }

            request.get({
                url: url
            }, function (error, response, body) {
                if (error) {
                    this.logError("Error communicating to weather service.", error, body);
                    deferred.reject("Error communicating to weather service.");
                }
                else {
                    try {
                        var weatherData = JSON.parse(body);

                        if ((weatherData.cod) && (200 != weatherData.cod)) {
                            var errorMessage = 'Could not get weather. Error code ' + weatherData.cod + ' with message "'
                                + weatherData.message + '".';
                            this.logError(errorMessage);
                            deferred.reject(errorMessage);
                        } else {
                            this.state = {
                                temperatureUnit: this.state.temperatureUnit,
                                temperature: weatherData.main.temp,
                                barometricPressure: weatherData.main.pressure,
                                humidity: weatherData.main.humidity,
                                weatherMain: weatherData.weather[0].main,
                                weatherDescription: weatherData.weather[0].description,
                                weatherIconURL: "http://openweathermap.org/img/w/" + weatherData.weather[0].icon + ".png",
                                cityId: weatherData.id,
                                cityName: weatherData.name,
                                clouds: weatherData.clouds.all,
                                windSpeed: weatherData.wind.speed,
                                windSpeedUnit: this.state.windSpeedUnit,
                                windDirection: weatherData.wind.deg,
                                sunrise: new Date(weatherData.sys.sunrise * 1000),
                                sunset: new Date(weatherData.sys.sunset * 1000)
                            };

                            try {
                                this.state.rainLast3h = weatherData.rain['3h'];
                            } catch (e) {
                                //ignore
                            }

                            try {
                                this.state.snowLast3h = weatherData.snow['3h'];
                            } catch (e) {
                                //ignore
                            }

                            this.publishStateChange();
                            deferred.resolve();
                        }
                    } catch (e) {
                        this.logError(e);
                        deferred.reject(e);
                    }
                }
            }.bind(this));
        }

        return deferred.promise;
    };

    /**
     *
     */

    Weather.prototype.getForecast = function () {
        var deferred = q.defer();

        if (this.configError) {
            this.logError("Configuration error - cannot retrieve weather info.");
        } else {
            this.logInfo("Requesting weather update from http://api.openweathermap.org/");

            this.logDebug("Polling weather.", this.configuration);

            var url = "http://api.openweathermap.org/data/2.5/forecast?q=" + this.configuration.cityName +
                "," + this.configuration.countryCode + "&units=" + this.configuration.units + "&lang=" +
                this.configuration.languageCode + "&APPID=" + this.configuration.openWeatherMapKey;

            this.logDebug("Request URL", url);

            if (!request) {
                request = require('request');
            }

            request.get({
                url: url
            }, function (error, response, body) {
                if (error) {
                    this.logError("Error communicating to weather service.", error, body);
                    deferred.reject("Error communicating to weather service.");
                }
                else {
                    try {
                        var weatherData = JSON.parse(body);

                        if ((weatherData.cod) && (200 != weatherData.cod)) {
                            var errorMessage = 'Could not get weather forecast. Error code ' + weatherData.cod + ' with message "'
                                + weatherData.message + '".';
                            this.logError(errorMessage);
                            deferred.reject(errorMessage);
                        } else {
                            let timeArray = [];
                            let tempArray = [];
                            let weatherMainArray = [];
                            let rainArray = [];
                            let snowArray = [];
                            for(let n in weatherData.list){
                                timeArray.push(new Date(weatherData.list[n].dt*1000));
                                tempArray.push(weatherData.list[n].main.temp);
                                weatherMainArray.push(weatherData.list[n].weather[0].main);
                                try {
                                    if (weatherData.list[n].rain['3h'] === undefined) rainArray.push(0);
                                    else rainArray.push(weatherData.list[n].rain['3h']);
                                }catch (e) {
                                    rainArray.push(0);//ignore
                                }
                                try {
                                    if (weatherData.list[n].snow['3h'] === undefined) snowArray.push(0);
                                    else snowArray.push(weatherData.list[n].snow['3h']);
                                }catch (e) {
                                    snowArray.push(0);//ignore
                                }
                            }

                            this.state = {
                                forecastTimestamp: timeArray,
                                forecastTemperature: tempArray,
                                // barometricPressure: weatherData.main.pressure,
                                // humidity: weatherData.main.humidity,
                                forecastWeatherMain: weatherMainArray,
                                // weatherDescription: weatherData.weather[0].description,
                                // weatherIconURL: "http://openweathermap.org/img/w/" + weatherData.weather[0].icon + ".png",
                                // clouds: weatherData.clouds.all,
                                // windSpeed: weatherData.wind.speed,
                                // windSpeedUnit: this.state.windSpeedUnit,
                                // windDirection: weatherData.wind.deg,
                                forecastRain: rainArray,
                                forecastSnow: snowArray
                            };

                            this.publishStateChange();
                            deferred.resolve();
                        }
                    } catch (e) {
                        this.logError(e);
                        deferred.reject(e);
                    }
                }
            }.bind(this));
        }

        return deferred.promise;
    };

    /**
     *
     */
    Weather.prototype.update = function () {
        this.getWeather();
    }

    /**
     *
     */
    Weather.prototype.setState = function (state) {
        this.state = state;

        this.publishStateChange();
    };

    /**
     *
     */
    Weather.prototype.getState = function () {
        return this.state;
    };

}
<|endoftext|>