<commit_before>"use strict";
/**
 * Storm Ajax Json Communicator
 * Client-side code
 */

var Comm_ServerSide = {
    busy: false,
    currentURL: null,
    history: (window.History.Adapter === undefined ?window.history:window.History),
    /* Define hook bind posts */
    hooks: {
        /* Called when busy gets set to true */
        'onBusy': [],
        /* Called when busy gets set to false */
        'onNotBusy': [],
        /* Called after an successful AJAX call, data is passed */
        'onSuccess': [],
        /* Called after an unsuccessful ajax call, data is passed */
        'onError': [],
        /* Called when the load method was successful, data is passed */
        'onLoad': [],
        /* Called when the load method was unsuccessful, data is passed */
        'onLoadError': [],
        /* Called when the form method was successful, form object and data passed */
        'onFormSuccess': [],
        /* Called when the form method was unsuccessful, form object and data passed */
        'onFormUnsuccessful': [],
        /* Called when one or more flash objects have been received, an array of flash(s) is passed */
        'onFlash': []
    }
};

Comm_ServerSide.setBusy = function (busy) {
    if (this.busy !== busy) {
        this.busy = busy;
        this.apply((busy ?'onBusy':'onNotBusy'));
    }

};

/**
 *
 * @param string|jqueryObject form Provide the forms name if passing a string
 * @param string url
 * @param object data
 * @param callable callback
 * @returns undefined
 */
Comm_ServerSide.form = function (form, url, data, callback) {
    var ctx = this;
    if (form !== null && typeof form !== 'object') {
        form = $('form[name=\''+form.replace('\'', '\\\'')+'\']');
    }
    if (url === undefined || url === null) {
        url = form.attr('action');
    }
    if (data === null || data === undefined) {
        data = {};
    }

    var fields = form.serializeArray();
    $.each(fields, function (ix, ob) {
        data[ob.name] = ob.value;
    });

    this.ajax(
        url,
        data,
        function (data) {
            if (callback !== undefined) {
                callback(data);
            }
            ctx.apply('onFormSuccess', [ form, data ]);
        },
        function (data) {
            ctx.apply('onFormError', [ form, data ]);
        }
    );
};

/**
 *
 * @param string url
 * @param object data
 * @param callable callback
 * @returns undefined
 */
Comm_ServerSide.load = function (url, data, callback) {
    this.currentURL = url;
    this.history.pushState(null, null, url);
    var ctx = this;
    this.ajax(
        url,
        data,
        function (data) {
            if (callback !== undefined) {
                callback(data);
            }
            ctx.apply('onLoad', [ data ]);
        },
        function (data) {
            ctx.apply('onLoadError', [ data ]);
        }
    );
};

/**
 *
 * @param callable callback
 * @returns undefined
 */
Comm_ServerSide.reload = function (callback) {
    this.load(this.currentURL, null, callback);
};

/**
 *
 * @param object callback
 * @returns undefined
 */
Comm_ServerSide.findFlash = function (data) {
    if (data.flash !== undefined && data.flash.length > 0) {
        this.apply('onFlash', [ data.flash ]);
    }
};

/**
 *
 * @param string url
 * @param object data
 * @param callable successCallback
 * @param callable errorCallback
 * @returns undefined
 */
Comm_ServerSide.ajax = function (url, data, successCallback, errorCallback) {
    if (this.busy === true) {
        return null;
    }
    this.setBusy(true);
    var ctx = this;
    if (data === undefined || data === null) {
        data = {};
    }
    $.ajax({
        url: url,
        type: 'POST',
        data: JSON.stringify(data),
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        context: ctx,
        success: function (data) {
            this.setBusy(false);
            successCallback(data);
            this.findFlash(data);
            this.apply('onSuccess', [ data ]);
        },
        error: function (data) {
            this.setBusy(false);
            errorCallback(data);
            this.findFlash(data);
            this.apply('onError', [ data ]);
        }
    });
};

/**
 *
 * @param string event
 * @param array param
 * @returns undefined
 */
Comm_ServerSide.apply = function (event, args) {
    if (args === undefined || args === null) {
        args = [];
    }
    if (this.hooks[event+''] !== undefined) {
        var funcs = this.hooks[event+''];
        for(var i = 0;i < funcs.length;i++) {
            funcs[i].apply(null, args);
        }
    }
};

/**
 *
 * @param string event
 * @param callable callback
 * @returns undefined
 */
Comm_ServerSide.hook = function (event, callback) {
    if (this.hooks[event+''] !== undefined) {
        this.hooks[event+''].push(callback);
    }
};

(function(window,undefined){
    if (window.History.Adapter !== undefined) {
        History.Adapter.bind(window,'statechange',function () {
            var url = History.getState().hash;
            if (Comm_ServerSide.currentURL !== url) {
               Comm_ServerSide.load(url);
            }
        });
    } else {
        window.onpopstate = function (event) {
            var hostname = document.location.protocol + '//' + document.location.hostname;
            var url = document.location.href.replace(hostname, '');
            if (Comm_ServerSide.currentURL !== url) {
               Comm_ServerSide.load(url);
            }
        };
    }
})(window);<commit_msg>Added setable static data option<commit_after>"use strict";
/**
 * Storm Ajax Json Communicator
 * Client-side code
 */

var Comm_ServerSide = {
    busy: false,
    currentURL: null,
    staticData: {},
    history: (window.History.Adapter === undefined ?window.history:window.History),
    /* Define hook bind posts */
    hooks: {
        /* Called when busy gets set to true */
        'onBusy': [],
        /* Called when busy gets set to false */
        'onNotBusy': [],
        /* Called after an successful AJAX call, data is passed */
        'onSuccess': [],
        /* Called after an unsuccessful ajax call, data is passed */
        'onError': [],
        /* Called when the load method was successful, data is passed */
        'onLoad': [],
        /* Called when the load method was unsuccessful, data is passed */
        'onLoadError': [],
        /* Called when the form method was successful, form object and data passed */
        'onFormSuccess': [],
        /* Called when the form method was unsuccessful, form object and data passed */
        'onFormUnsuccessful': [],
        /* Called when one or more flash objects have been received, an array of flash(s) is passed */
        'onFlash': []
    }
};

Comm_ServerSide.setBusy = function (busy) {
    if (this.busy !== busy) {
        this.busy = busy;
        this.apply((busy ?'onBusy':'onNotBusy'));
    }

};

/**
 *
 * @param string|jqueryObject form Provide the forms name if passing a string
 * @param string url
 * @param object data
 * @param callable callback
 * @returns undefined
 */
Comm_ServerSide.form = function (form, url, data, callback) {
    var ctx = this;
    if (form !== null && typeof form !== 'object') {
        form = $('form[name=\''+form.replace('\'', '\\\'')+'\']');
    }
    if (url === undefined || url === null) {
        url = form.attr('action');
    }
    if (data === null || data === undefined) {
        data = {};
    }

    var fields = form.serializeArray();
    $.each(fields, function (ix, ob) {
        data[ob.name] = ob.value;
    });

    this.ajax(
        url,
        data,
        function (data) {
            if (callback !== undefined) {
                callback(data);
            }
            ctx.apply('onFormSuccess', [ form, data ]);
        },
        function (data) {
            ctx.apply('onFormError', [ form, data ]);
        }
    );
};

/**
 *
 * @param string url
 * @param object data
 * @param callable callback
 * @returns undefined
 */
Comm_ServerSide.load = function (url, data, callback) {
    this.currentURL = url;
    this.history.pushState(null, null, url);
    var ctx = this;
    this.ajax(
        url,
        data,
        function (data) {
            if (callback !== undefined) {
                callback(data);
            }
            ctx.apply('onLoad', [ data ]);
        },
        function (data) {
            ctx.apply('onLoadError', [ data ]);
        }
    );
};

/**
 *
 * @param callable callback
 * @returns undefined
 */
Comm_ServerSide.reload = function (callback) {
    this.load(this.currentURL, null, callback);
};

/**
 *
 * @param object callback
 * @returns undefined
 */
Comm_ServerSide.findFlash = function (data) {
    if (data.flash !== undefined && data.flash.length > 0) {
        this.apply('onFlash', [ data.flash ]);
    }
};

/**
 *
 * @param string url
 * @param object data
 * @param callable successCallback
 * @param callable errorCallback
 * @returns undefined
 */
Comm_ServerSide.ajax = function (url, data, successCallback, errorCallback) {
    if (this.busy === true) {
        return null;
    }
    this.setBusy(true);
    var ctx = this;
    if (data === undefined || data === null) {
        data = this.staticData;
    } else {
        data = $.extend({}, this.staticData, data);
    }
    $.ajax({
        url: url,
        type: 'POST',
        data: JSON.stringify(data),
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        context: ctx,
        success: function (data) {
            this.setBusy(false);
            successCallback(data);
            this.findFlash(data);
            this.apply('onSuccess', [ data ]);
        },
        error: function (data) {
            this.setBusy(false);
            errorCallback(data);
            this.findFlash(data);
            this.apply('onError', [ data ]);
        }
    });
};

/**
 *
 * @param string event
 * @param array param
 * @returns undefined
 */
Comm_ServerSide.apply = function (event, args) {
    if (args === undefined || args === null) {
        args = [];
    }
    if (this.hooks[event+''] !== undefined) {
        var funcs = this.hooks[event+''];
        for(var i = 0;i < funcs.length;i++) {
            funcs[i].apply(null, args);
        }
    }
};

/**
 *
 * @param string event
 * @param callable callback
 * @returns undefined
 */
Comm_ServerSide.hook = function (event, callback) {
    if (this.hooks[event+''] !== undefined) {
        this.hooks[event+''].push(callback);
    }
};

(function(window,undefined){
    if (window.History.Adapter !== undefined) {
        History.Adapter.bind(window,'statechange',function () {
            var url = History.getState().hash;
            if (Comm_ServerSide.currentURL !== url) {
               Comm_ServerSide.load(url);
            }
        });
    } else {
        window.onpopstate = function (event) {
            var hostname = document.location.protocol + '//' + document.location.hostname;
            var url = document.location.href.replace(hostname, '');
            if (Comm_ServerSide.currentURL !== url) {
               Comm_ServerSide.load(url);
            }
        };
    }
})(window);<|endoftext|>


<commit_before>var userId;

$(document).ready(function() {

	var conf;

	var confRequest = $.getJSON("/conf.json", function(response){
		conf = response;
	});

	$.ajaxSetup({
		crossDomain: true,
		xhrFields: {
			withCredentials: true
		}
	});

	$.getJSON("http://weapon.labeli.org/users/info.json", function(response) {
		$("#access-account").hide();
		$("#my-infos").show();

		loadInfos(response.data);
	}).fail(function(jqXHR) {
		if (jqXHR.status == 403) {
			$("#access-account").show();
		} else {
			$("#access-account").show();
		}
	});

	$("#connect").on("click", ".button", function(){
		var username = $("#connect .username").val();
		var password = $("#connect .password").val();
		$.post("http://weapon.labeli.org/users/login.json", {"data[User][username]" : username, "data[User][password]" : password}, function(response) {
			$("#access-account").hide();
			$("#my-infos").show();
			loadInfos(response.data);

		}, "json")
			.fail(function() {
			$("#connect .errors").text("Oops. Veuillez vérifier vos informations.");
		});
	});

	$("#signup").on("click", ".button", function(){
		var username = $("#signup .username").val();
		var password = $("#signup .password").val();
		var passwordconfirm = $("#signup .passwordconfirm").val();
		var email = $("#signup .email").val();
		var firstname = $("#signup .firstname").val();
		var lastname = $("#signup .lastname").val();

		if(password != passwordconfirm){
			$("#signup .errors").text("Les mots de passe ne sont pas identiques.");
		} else {

			$.post("http://weapon.labeli.org/users.json",
				   {
				"data[User][username]" : username,
				"data[User][password]" : password,
				"data[User][firstName]": firstname,
				"data[User][lastName]": lastname,
				"data[User][email]" : email
			},
				   function(response) {
				$("#access-account").hide();
				$("#my-infos").show();

				$.post("http://weapon.labeli.org/users/login.json", {"data[User][username]" : username, "data[User][password]" : password},function(){
					$.getJSON("http://weapon.labeli.org/events/book/"+conf.event.id+".json", function(response){
						loadInfos(response.data);
					});
				});
			}, "json")
				.fail(function() {
				$("#signup .errors").text("Oops. Veuillez vérifier vos informations.");
			});
		}
	});

	$(".my-tournaments").on("click", ".button", function(){
		$(".requiredInfo").empty();
		$(".addTourn-error").empty();
		$(".modal-body #list-games").html('<option value="null">- Veuillez choisir un jeu -</option>');
		$.getJSON("http://weapon.labeli.org/events/"+conf.event.id+".json", function(response){
			$.each(response.data.Tournament, function (index, value){
				if(value.max > 0){
					var start = new Date(value.start.replace("-", " ", "g"));
					var end = new Date(value.end.replace("-", " ", "g"));
					var when = "De "+start.toLocaleTimeString() + " à "+end.toLocaleTimeString();
					var option = '<option data-game="'+value.idGame+'" data-infos-required="'+value.infoRequired+'" value="'+value.id+'">'+value.name+' - '+when+'</option>';
					$(".modal-body #list-games").append(option);
				}
			});

		});
	});

	$(".modal-body").on("click", ".button-validate-add", function(){
		var tournamentId = $("#list-games").val();
		var required = $("#list-games option:selected").data("infos-required");
		var gameId = $("#list-games option:selected").data("game");
		var usergame = null;

		if(tournamentId != null) {
			if(required){
				usergame = $(".requiredInfo input").val();
			}
			if(required && (usergame == null || usergame == "") ){
				$(".addTourn-error").text("Vous devez compléter les informations pour vous inscrire à ce tournoi.")
			} else {
				if(required){
					$.post("http://weapon.labeli.org/usergames/"+gameId+".json", {
						"data[Usergame][username]" : usergame,
						"data[Usergame][level]" : 0,
						"date[Usergame][grade]" :0
					}, function(){
						$.getJSON("http://weapon.labeli.org/tournaments/book/"+tournamentId+".json", function(){
							window.location = "/mon-compte";
						});
						$('#basicModal').modal('hide');
					});
				} else {
					$.getJSON("http://weapon.labeli.org/tournaments/book/"+tournamentId+".json", function(){
						window.location = "/mon-compte";
					});
					$('#basicModal').modal('hide');
				}
			}
		}
	})

	$(".modal-body").on("click",".button-validate-change-infos", function(){
		var shirtSize = $("#changeInfos #shirtSize").val();
		var macAdress = $("#changeInfos #macAdress").val();
		var hasPizza = $('#changeInfos input[name=hasPizza]:checked').val();

		var params = {"data[User][sizeShirt]" : shirtSize,
					  "data[User][macAddress]" : macAdress,
					  "data[User][data]": hasPizza};

		$.post("http://weapon.labeli.org/users/"+userId+".json", params, function(){
			window.location = "/mon-compte";
		});

	});

	$("#list-games").on("change", function(){
		var required = $(this).children("option:selected").data("infos-required");
		if(required) {
			$(".requiredInfo").html('Nom d\'utilisateur sur ce jeu : <input type="text" id="usergame">');
		} else {
			$(".requiredInfo").empty();

		}
	});

});

function disconnect(){
	$.getJSON("http://weapon.labeli.org/users/logout.json", function(){

		window.location = "/";
	});
}

function loadInfos(data){
	userId = data.User.id;
	$("#my-infos .username").text(data.User.username);
	$("#my-infos .email").text(data.User.email);
	$("#my-infos .firstname").text(data.User.firstName);
	$("#my-infos .lastname").text(data.User.lastName);
	$("#my-infos .shirtSize").text(data.User.sizeShirt);
	$("#my-infos .macAdress").text(data.User.macAddress);
	$("#my-infos .hasPizza").text(data.User.data);

	$("#changeInfos #shirtSize").val(data.User.sizeShirt);
	$("#changeInfos #macAdress").val(data.User.macAddress);
	var $radios = $('input:radio[name=hasPizza]');
	$radios.filter('[value='+data.User.data+']').prop('checked', true);

	$.each(data.Tournament, function(index, value){
		var id=value.idTournament;
		$.getJSON("http://weapon.labeli.org/tournaments/"+id+".json", function(response){
			if(response.data.Tournament.max > 0){
				var start = new Date(response.data.Tournament.start.replace("-", " ", "g"));
				var end = new Date(response.data.Tournament.end.replace("-", " ", "g"));
				var when = "De "+start.toLocaleTimeString() + " à "+end.toLocaleTimeString();
				var row = "
"+response.data.Game.name+" - "+when+"
";
				$(".my-tournaments-list").append(row);
			}
		});
	});
}
<commit_msg>Correction data usergame<commit_after>var userId;

$(document).ready(function() {

	var conf;

	var confRequest = $.getJSON("/conf.json", function(response){
		conf = response;
	});

	$.ajaxSetup({
		crossDomain: true,
		xhrFields: {
			withCredentials: true
		}
	});

	$.getJSON("http://weapon.labeli.org/users/info.json", function(response) {
		$("#access-account").hide();
		$("#my-infos").show();

		loadInfos(response.data);
	}).fail(function(jqXHR) {
		if (jqXHR.status == 403) {
			$("#access-account").show();
		} else {
			$("#access-account").show();
		}
	});

	$("#connect").on("click", ".button", function(){
		var username = $("#connect .username").val();
		var password = $("#connect .password").val();
		$.post("http://weapon.labeli.org/users/login.json", {"data[User][username]" : username, "data[User][password]" : password}, function(response) {
			$("#access-account").hide();
			$("#my-infos").show();
			loadInfos(response.data);

		}, "json")
			.fail(function() {
			$("#connect .errors").text("Oops. Veuillez vérifier vos informations.");
		});
	});

	$("#signup").on("click", ".button", function(){
		var username = $("#signup .username").val();
		var password = $("#signup .password").val();
		var passwordconfirm = $("#signup .passwordconfirm").val();
		var email = $("#signup .email").val();
		var firstname = $("#signup .firstname").val();
		var lastname = $("#signup .lastname").val();

		if(password != passwordconfirm){
			$("#signup .errors").text("Les mots de passe ne sont pas identiques.");
		} else {

			$.post("http://weapon.labeli.org/users.json",
				   {
				"data[User][username]" : username,
				"data[User][password]" : password,
				"data[User][firstName]": firstname,
				"data[User][lastName]": lastname,
				"data[User][email]" : email
			},
				   function(response) {
				$("#access-account").hide();
				$("#my-infos").show();

				$.post("http://weapon.labeli.org/users/login.json", {"data[User][username]" : username, "data[User][password]" : password},function(){
					$.getJSON("http://weapon.labeli.org/events/book/"+conf.event.id+".json", function(response){
						loadInfos(response.data);
					});
				});
			}, "json")
				.fail(function() {
				$("#signup .errors").text("Oops. Veuillez vérifier vos informations.");
			});
		}
	});

	$(".my-tournaments").on("click", ".button", function(){
		$(".requiredInfo").empty();
		$(".addTourn-error").empty();
		$(".modal-body #list-games").html('<option value="null">- Veuillez choisir un jeu -</option>');
		$.getJSON("http://weapon.labeli.org/events/"+conf.event.id+".json", function(response){
			$.each(response.data.Tournament, function (index, value){
				if(value.max > 0){
					var start = new Date(value.start.replace("-", " ", "g"));
					var end = new Date(value.end.replace("-", " ", "g"));
					var when = "De "+start.toLocaleTimeString() + " à "+end.toLocaleTimeString();
					var option = '<option data-game="'+value.idGame+'" data-infos-required="'+value.infoRequired+'" value="'+value.id+'">'+value.name+' - '+when+'</option>';
					$(".modal-body #list-games").append(option);
				}
			});

		});
	});

	$(".modal-body").on("click", ".button-validate-add", function(){
		var tournamentId = $("#list-games").val();
		var required = $("#list-games option:selected").data("infos-required");
		var gameId = $("#list-games option:selected").data("game");
		var usergame = null;

		if(tournamentId != null) {
			if(required){
				usergame = $(".requiredInfo input").val();
			}
			if(required && (usergame == null || usergame == "") ){
				$(".addTourn-error").text("Vous devez compléter les informations pour vous inscrire à ce tournoi.")
			} else {
				if(required){
					$.post("http://weapon.labeli.org/usergames/"+gameId+".json", {
						"data[Usergame][username]" : usergame,
						"data[Usergame][level]" : 30,
						"data[Usergame][grade]" : "unranked"
					}, function(){
						$.getJSON("http://weapon.labeli.org/tournaments/book/"+tournamentId+".json", function(){
							window.location = "/mon-compte";
						});
						$('#basicModal').modal('hide');
					});
				} else {
					$.getJSON("http://weapon.labeli.org/tournaments/book/"+tournamentId+".json", function(){
						window.location = "/mon-compte";
					});
					$('#basicModal').modal('hide');
				}
			}
		}
	})

	$(".modal-body").on("click",".button-validate-change-infos", function(){
		var shirtSize = $("#changeInfos #shirtSize").val();
		var macAdress = $("#changeInfos #macAdress").val();
		var hasPizza = $('#changeInfos input[name=hasPizza]:checked').val();

		var params = {"data[User][sizeShirt]" : shirtSize,
					  "data[User][macAddress]" : macAdress,
					  "data[User][data]": hasPizza};

		$.post("http://weapon.labeli.org/users/"+userId+".json", params, function(){
			window.location = "/mon-compte";
		});

	});

	$("#list-games").on("change", function(){
		var required = $(this).children("option:selected").data("infos-required");
		if(required) {
			$(".requiredInfo").html('Nom d\'utilisateur sur ce jeu : <input type="text" id="usergame">');
		} else {
			$(".requiredInfo").empty();

		}
	});

});

function disconnect(){
	$.getJSON("http://weapon.labeli.org/users/logout.json", function(){

		window.location = "/";
	});
}

function loadInfos(data){
	userId = data.User.id;
	$("#my-infos .username").text(data.User.username);
	$("#my-infos .email").text(data.User.email);
	$("#my-infos .firstname").text(data.User.firstName);
	$("#my-infos .lastname").text(data.User.lastName);
	$("#my-infos .shirtSize").text(data.User.sizeShirt);
	$("#my-infos .macAdress").text(data.User.macAddress);
	$("#my-infos .hasPizza").text(data.User.data);

	$("#changeInfos #shirtSize").val(data.User.sizeShirt);
	$("#changeInfos #macAdress").val(data.User.macAddress);
	var $radios = $('input:radio[name=hasPizza]');
	$radios.filter('[value='+data.User.data+']').prop('checked', true);

	$.each(data.Tournament, function(index, value){
		var id=value.idTournament;
		$.getJSON("http://weapon.labeli.org/tournaments/"+id+".json", function(response){
			if(response.data.Tournament.max > 0){
				var start = new Date(response.data.Tournament.start.replace("-", " ", "g"));
				var end = new Date(response.data.Tournament.end.replace("-", " ", "g"));
				var when = "De "+start.toLocaleTimeString() + " à "+end.toLocaleTimeString();
				var row = "
"+response.data.Game.name+" - "+when+"
";
				$(".my-tournaments-list").append(row);
			}
		});
	});
}
<|endoftext|>


<commit_before>/*
 * @author Priyank Patel
 * @github https://github.com/PR1YANKPAT3L
 * @desc Contains All Main App Angular Module
 */
(function () {
	define(['angular', 'angularAnimate', 'angularMaterial', 'angularRouter', 'angular-cache', 'facebook', 'AuthService'], function (angular, angularAnimate, angularMaterial, angularRouter, angularCache, facebook, AuthService) {
		'use strict';

    // Create CLAPP Module as the main app module
		var app = angular.module('clapp', ['ngAnimate', 'ngMaterial', 'ui.router', 'angular-cache', 'FacebookService']);

		app.config(function ($stateProvider, $urlRouterProvider, CacheFactoryProvider) {
			// Set Max Age for Caching
			angular.extend(CacheFactoryProvider.defaults, {
				maxAge: 15 * 60 * 1000
			});
			//$urlRouterProvider.otherwise('/login');

      // Setup State Providers
			$stateProvider
			.state('login', {
				url: '/login',
				templateUrl: 'partials/login/login.html'
			})
			.state('register', {
				url: '/register',
				templateUrl: 'partials/login/register.html'
			})
			.state('dashboard', {
				url: '/dashboard',
				templateUrl: 'partials/dashboard/base.html'
			})
			.state('dashboard.home', {
				url: '/home',
				templateUrl: 'partials/dashboard/home/home.html'
			});
		});

    app.run(['$rootScope', '$window', 'FacebookService', function($rootScope, $window, FacebookService) {
      $rootScope.user = {}

      FB.init({
        appId      : '955177784536960',
        version    : 'v2.5',
        xfbml      : false,
				cookie		 : true,
				status		 : false
      });

			FacebookService.watchLoginChange();
			FacebookService.getLoginStatus();
    }]);

		app.controller('LoginController', ['$scope', '$http', '$timeout', function($scope, $http, $timeout) {
			$scope.isValidationInProgress = false;

			$scope.loginWithFB = function () {
				FB.login();
			}

			$scope.login = function () {
				$scope.isValidationInProgress = true;
				$scope.loginError = false;

				var payload = {
					email: $scope.login.email,
					pass: $scope.login.password
				};

				$http({
					url: 'http://dashboard.dev/api/v1/login.php',
					method: 'POST',
					data: payload,
					headers: {
						'Content-Type': 'application/json; charset=utf-8'
					}
				}).success(function (response) {
					if(response.valid) {
						$timeout(function () {
							$scope.isValidationInProgress = false;
							$scope.loginError = false;
							$scope.loginErrorMessage = response.message;
						}, 1000);
					} else {
						$timeout(function () {
							$scope.isValidationInProgress = false;
							$scope.loginError = true;
							$scope.loginErrorMessage = response.message;
						}, 1000);
					}
				}).error(function (error) {
					console.log(error);
				});
			}
		}]);

		app.controller('RegisterController', ['$scope', '$http', '$timeout', function($scope, $http, $timeout) {
			$scope.isValidationInProgress = false;

			$scope.register = function () {
				$scope.isValidationInProgress = true;
				$scope.registerError = false;

				var payload = {
					email: $scope.register.email,
					pass: $scope.register.password,
					repeat: $scope.register.repeatpassword
				};
				console.log(payload);
				if(payload.pass === payload.repeat) {
					$http({
						url: 'http://dashboard.dev/api/v1/register.php',
						method: 'POST',
						data: payload,
						headers: {
							'Content-Type': 'application/json; charset=utf-8'
						}
					}).success(function (response) {
						console.log(response)
						if(response.valid) {
							$timeout(function () {
								$scope.isValidationInProgress = false;
								$scope.registerError = false;
								$scope.registerErrorMessage = response.message;
							}, 1000);
						} else {
							$timeout(function () {
								$scope.isValidationInProgress = false;
								$scope.registerError = true;
								$scope.registerErrorMessage = response.message;
							}, 1000);
						}
					}).error(function (error) {
						console.log(error);
					});
				} else {
					$timeout(function () {
						$scope.isValidationInProgress = false;
						$scope.registerError = true;
						$scope.registerErrorMessage = "Password must match!";
					}, 1000);
				}
			}
		}]);

		return app;
	});
}).call(this);
<commit_msg>Fixed Path for API<commit_after>/*
 * @author Priyank Patel
 * @github https://github.com/PR1YANKPAT3L
 * @desc Contains All Main App Angular Module
 */
(function () {
	define(['angular', 'angularAnimate', 'angularMaterial', 'angularRouter', 'angular-cache', 'facebook', 'AuthService'], function (angular, angularAnimate, angularMaterial, angularRouter, angularCache, facebook, AuthService) {
		'use strict';

    // Create CLAPP Module as the main app module
		var app = angular.module('clapp', ['ngAnimate', 'ngMaterial', 'ui.router', 'angular-cache', 'FacebookService']);

		app.config(function ($stateProvider, $urlRouterProvider, CacheFactoryProvider) {
			// Set Max Age for Caching
			angular.extend(CacheFactoryProvider.defaults, {
				maxAge: 15 * 60 * 1000
			});
			//$urlRouterProvider.otherwise('/login');

      // Setup State Providers
			$stateProvider
			.state('login', {
				url: '/login',
				templateUrl: 'partials/login/login.html'
			})
			.state('register', {
				url: '/register',
				templateUrl: 'partials/login/register.html'
			})
			.state('dashboard', {
				url: '/dashboard',
				templateUrl: 'partials/dashboard/base.html'
			})
			.state('dashboard.home', {
				url: '/home',
				templateUrl: 'partials/dashboard/home/home.html'
			});
		});

    app.run(['$rootScope', '$window', 'FacebookService', function($rootScope, $window, FacebookService) {
      $rootScope.user = {}

      FB.init({
        appId      : '955177784536960',
        version    : 'v2.5',
        xfbml      : false,
				cookie		 : true,
				status		 : false
      });

			FacebookService.watchLoginChange();
			FacebookService.getLoginStatus();
    }]);

		app.controller('LoginController', ['$scope', '$http', '$timeout', function($scope, $http, $timeout) {
			$scope.isValidationInProgress = false;

			$scope.loginWithFB = function () {
				FB.login();
			}

			$scope.login = function () {
				$scope.isValidationInProgress = true;
				$scope.loginError = false;

				var payload = {
					email: $scope.login.email,
					pass: $scope.login.password
				};

				$http({
					url: '/api/v1/login.php',
					method: 'POST',
					data: payload,
					headers: {
						'Content-Type': 'application/json; charset=utf-8'
					}
				}).success(function (response) {
					if(response.valid) {
						$timeout(function () {
							$scope.isValidationInProgress = false;
							$scope.loginError = false;
							$scope.loginErrorMessage = response.message;
						}, 1000);
					} else {
						$timeout(function () {
							$scope.isValidationInProgress = false;
							$scope.loginError = true;
							$scope.loginErrorMessage = response.message;
						}, 1000);
					}
				}).error(function (error) {
					console.log(error);
				});
			}
		}]);

		app.controller('RegisterController', ['$scope', '$http', '$timeout', function($scope, $http, $timeout) {
			$scope.isValidationInProgress = false;

			$scope.register = function () {
				$scope.isValidationInProgress = true;
				$scope.registerError = false;

				var payload = {
					email: $scope.register.email,
					pass: $scope.register.password,
					repeat: $scope.register.repeatpassword
				};
				console.log(payload);
				if(payload.pass === payload.repeat) {
					$http({
						url: '/api/v1/register.php',
						method: 'POST',
						data: payload,
						headers: {
							'Content-Type': 'application/json; charset=utf-8'
						}
					}).success(function (response) {
						console.log(response)
						if(response.valid) {
							$timeout(function () {
								$scope.isValidationInProgress = false;
								$scope.registerError = false;
								$scope.registerErrorMessage = response.message;
							}, 1000);
						} else {
							$timeout(function () {
								$scope.isValidationInProgress = false;
								$scope.registerError = true;
								$scope.registerErrorMessage = response.message;
							}, 1000);
						}
					}).error(function (error) {
						console.log(error);
					});
				} else {
					$timeout(function () {
						$scope.isValidationInProgress = false;
						$scope.registerError = true;
						$scope.registerErrorMessage = "Password must match!";
					}, 1000);
				}
			}
		}]);

		return app;
	});
}).call(this);
<|endoftext|>


<commit_before>const MongoClient = require('mongodb').MongoClient;
const roomMap = {
  'C0D2Z96AG': 'hubot-testing',
  'C03AFTJHG': 'general',
  'C4YTEUTJ6': 'generaltsos',
  'CCE6AE5GE': 'investing',
  'CBZU99HCL': 'prayers',
  'CEFH3HW1M': 'whatsplaying'
};

module.exports = function (robot) {

  MongoClient.connect(process.env.MONGODB_URL, {
      useNewUrlParser: true
    },
    function (err, client) {
      if (err) {
        robot.logger.error('Auditor was unable to connect to slack_messages connection!');
        robot.logger.error(err);
      }

      robot.logger.debug('Successfully authenticated with mongo');

      let db = client.db(process.env.MONGODB_DBNAME);
      let collection = db.collection('slack_messages');

      robot.hear(/^.*$/, function (msg) {
        let room = msg.message.room;
        if (room.startsWith('G') || room.startsWith('D')) {
          robot.logger.info('Skipping messages from ignored room.');
          return;
        }
        let savedMessage = {
          'room': roomMap[room],
          'room_id': room,
          'user': msg.message.user.name,
          'user_id': msg.message.user.id,
          'message_id': msg.message.id,
          'text': msg.message.text,
          'timestamp': Date.now()
        };
        collection.insertOne(savedMessage, function (err, res) {
          if (err) {
            robot.logger.error('Auditor was unable to save message!');
            robot.logger.error(err);
          }
        });
      });
    });
};
<commit_msg>Fix emojis in auditor.<commit_after>const MongoClient = require('mongodb').MongoClient;
const roomMap = {
  'C0D2Z96AG': 'hubot-testing',
  'C03AFTJHG': 'general',
  'C4YTEUTJ6': 'generaltsos',
  'CCE6AE5GE': 'investing',
  'CBZU99HCL': 'prayers',
  'CEFH3HW1M': 'whatsplaying'
};

module.exports = function (robot) {

  MongoClient.connect(process.env.MONGODB_URL, {
      useNewUrlParser: true
    },
    function (err, client) {
      if (err) {
        robot.logger.error('Auditor was unable to connect to slack_messages connection!');
        robot.logger.error(err);
      }

      robot.logger.debug('Successfully authenticated with mongo');

      let db = client.db(process.env.MONGODB_DBNAME);
      let collection = db.collection('slack_messages');

      robot.hear(/^.*$/, function (msg) {
        let room = msg.message.room;
        if (room.startsWith('G') || room.startsWith('D')) {
          robot.logger.info('Skipping messages from ignored room.');
          return;
        }
        let savedMessage = {
          'room': roomMap[room],
          'room_id': room,
          'user': msg.message.user.name,
          'user_id': msg.message.user.id,
          'message_id': msg.message.id,
          'text': msg.message.rawText,
          'timestamp': Date.now()
        };
        collection.insertOne(savedMessage, function (err, res) {
          if (err) {
            robot.logger.error('Auditor was unable to save message!');
            robot.logger.error(err);
          }
        });
      });
    });
};
<|endoftext|>


<commit_before>/* Copyright (c) Royal Holloway, University of London | Contact Blake Loring (blake@parsed.uk), Duncan Mitchell (Duncan.Mitchell.2015@rhul.ac.uk), or Johannes Kinder (johannes.kinder@rhul.ac.uk) for details or support | LICENSE.md for license details */

function buildTestList() {
    var testList = [];

    function buildTest(file, expectPaths, expectErrors) {
        testList.push({
            path: file,
            expectPaths: expectPaths,
            expectErrors: expectErrors
        });
    }

    //Core Javascript, no symbex / annotations
    buildTest('core/bools.js', 1, 0);
    buildTest('core/recursion.js', 1, 0);
    buildTest('core/lamda.js', 1, 0);
    buildTest('core/conc_diff.js', 3, 2);
    buildTest('core/spaced name.js', 2, 1);

    //Booleans
    buildTest('bool/hello.js', 2, 0);
    buildTest('bool/basic.js', 4, 1);

    //Pure Symbols
    buildTest('pure/pure_symbol', 8, 0);
    buildTest('pure/two_symbols', 84, 22);

    //Test symbol renaming
    buildTest('renaming/rename_simple', 3, 2);
    buildTest('renaming/rename', 12, 11);

    //Object Tests
    buildTest('objects/constructor', 2, 1);
    buildTest('objects/concrete.js', 1, 0);
    buildTest('objects/pure_object.js', 10, 1);

    //Array tests
    buildTest('arrays/concrete_checks', 1, 0);
    buildTest('arrays/basic', 8, 3);
    buildTest('arrays/pure', 22, 7);
    buildTest('arrays/update', 3, 2);
    buildTest('arrays/manual_push', 7, 1);
    buildTest('arrays/index_of', 2, 1);
    buildTest('arrays/includes', 2, 1);
    buildTest('arrays/string', 3, 1);
    buildTest('arrays/includes_index_of', 3, 1);
    buildTest('arrays/bool', 5, 3);
    buildTest('arrays/push', 2, 1);
    buildTest('arrays/pop', 2, 1);
    buildTest('arrays/push_conc', 1, 0);
    buildTest('arrays/pop_conc', 1, 0);
    buildTest('arrays/enumerate_concrete', 4, 3);

    //Numbers
    buildTest('numbers/abs.js', 2, 0);
    buildTest('numbers/ten.js', 2, 0);
    buildTest('numbers/hello.js', 2, 0);
    buildTest('numbers/lt.js', 3, 0);
    buildTest('numbers/coerce.js', 2, 0);
    buildTest('numbers/mul.js', 2, 0);
    buildTest('numbers/breaker.js', 1, 0);
    buildTest('numbers/infoflow.js', 17, 0);
    buildTest('numbers/floor.js', 3, 2);
    buildTest('numbers/round.js', 2, 2);

    //Eval
    buildTest('eval/test.js', 2, 1);

    //Fractions
    buildTest('fractions/fraction_one.js', 3, 0);

    buildTest('assert/assert.js', 6, 0);

    buildTest('assumes/basic.js', 2, 0);
    buildTest('assumes/wrapped_assume.js', 2, 0);

    //Loops
    buildTest('loops/loop_alot.js', 12, 0);

    //Named methods
    buildTest('named_method/simple.js', 1, 0);

    //Async
    buildTest('async/settimeout.js', 3, 1);

    //Strings
    buildTest('strings/hello_strings.js', 2, 0);
    buildTest('strings/hello_strings2.js', 3, 0);
    buildTest('strings/hello_strings_concat.js', 2, 0);
    buildTest('strings/lowercase.js', 2, 1);
    buildTest('strings/hello_strings_concat2.js', 1, 0);
    buildTest('strings/hello_strings_len.js', 2, 0);
    buildTest('strings/strings_concat.js', 2, 0);
    buildTest('strings/negative_slice.js', 7, 5); //TODO: Some paths are doubled
    buildTest('strings/substr_tests.js', 7, 5);
    buildTest('strings/strings_concat.js', 2, 0);
    buildTest('strings/warning.js', 4, 0);
    buildTest('strings/repeat.js', 3, 2);
    buildTest('strings/trim.js', 3, 1);

    /**
     * Regular Expression Feature Test
     */

    /**
     * Core language tests
     */
    buildTest('regex/core/alternation/simple.js', 4, 4);
    buildTest('regex/core/alternation/many.js', 4, 4);
    buildTest('regex/core/alternation/words.js', 4, 4);
    buildTest('regex/core/alternation/exhaustive_simple.js', 5, 5);
    buildTest('regex/core/alternation/multiple_related.js', 7, 7);
    buildTest('regex/core/johannes', 5, 4);

    buildTest('regex/core/literals/simple_one.js', 2, 1);
    buildTest('regex/core/literals/simple_two.js', 2, 1);
    buildTest('regex/core/literals/long_example.js', 2, 2);
    buildTest('regex/core/literals/empty_example.js', 2, 2);
    buildTest('regex/core/literals/mixed_escaped.js', 3, 3); //TODO: Should this be 2
    buildTest('regex/core/literals/non_alpha.js', 2, 2);
    buildTest('regex/core/literals/multiple.js', 6, 6);

    /**
    *    TODO: Find out of unicode support is possible through some screwing with Z3 strings
    *    buildTest('regex/core/escaping/hex.js', 5, 4);
    *    buildTest('regex/core/escaping/unicode.js', 6, 5);
    *    buildTest('regex/core/escaping/unicode_mode.js', 6, 5);
    */

    buildTest('regex/core/escaping/ranges.js', 8, 8);
    buildTest('regex/core/escaping/negative_ranges.js', 3, 2);
    buildTest('regex/core/escaping/space_class.js', 8, 7);
    buildTest('regex/core/escaping/word.js', 3, 2);
    buildTest('regex/core/escaping/digit.js', 3, 2);

    buildTest('regex/core/star/star.js', 7, 7);
    buildTest('regex/core/star/online.js', 11, 10);
    buildTest('regex/core/star/lazy.js', 7, 7);
    buildTest('regex/core/star/multiple.js', 5, 5);

    buildTest('regex/core/plus/plus.js', 12, 11);
    buildTest('regex/core/plus/lazy.js', 12, 11);
    buildTest('regex/core/plus/online.js', 11, 10);
    buildTest('regex/core/plus/multiple.js', 4, 4);

    buildTest('regex/core/loops/fixed_loop.js', 3, 2);
    buildTest('regex/core/loops/between_loop.js', 9, 8);
    buildTest('regex/core/loops/minimum_loop.js', 6, 5);

    buildTest('regex/core/optional/base.js', 13, 12);
    buildTest('regex/core/optional/combined.js', 9, 8);
    buildTest('regex/core/optional/no_greed.js', 13, 12);
    buildTest('regex/core/optional/range.js', 3, 2);

    /**
     * Lazy Operator Tests
     */

    buildTest('regex/lazy/lazy_1.js', 3, 2);
    buildTest('regex/lazy/lazy_2.js', 2, 1);
    buildTest('regex/lazy/lazy_3.js', 3, 2);
    buildTest('regex/lazy/lazy_4.js', 2, 1);
    buildTest('regex/lazy/lazy_5.js', 3, 2);
    buildTest('regex/lazy/lazy_6.js', 3, 2);

    /**
     * Anchors Tests
     */
    //buildTest('regex/anchors/left.js', 3, 3);
    //buildTest('regex/anchors/right.js', 3, 3); //TODO: An extra query is generated
    //buildTest('regex/anchors/none.js', 4, 4);
    buildTest('regex/anchors/both.js', 2, 1);

    /**
     * Assertion Tests
     */
    buildTest('regex/assertions/ahead.js', 1, 0);
    buildTest('regex/assertions/ahead_2.js', 2, 1);
    buildTest('regex/assertions/ahead_3.js', 2, 1);
    buildTest('regex/assertions/ahead_4.js', 4, 3);
    buildTest('regex/assertions/ahead_5.js', 4, 3);
    buildTest('regex/assertions/ahead_6.js', 2, 1);
    buildTest('regex/assertions/ahead_7.js', 2, 1);
    buildTest('regex/assertions/ahead_8.js', 2, 1);
    buildTest('regex/assertions/ahead_9.js', 2, 1);

    /**
     * Backreference Tests
     */
    buildTest('regex/backreferences/closed.js', 2, 1);
    buildTest('regex/backreferences/closed_limited.js', 2, 1);
    buildTest('regex/backreferences/closed_range.js', 3, 2);
    buildTest('regex/backreferences/closed_limited.js', 3, 1); //Extra path from assume

    //These we can fail because of restrictions on S
    /*buildTest('regex/backreferences/closed_loop.js', 2, 1);
    buildTest('regex/backreferences/closed_loop_minor.js', 2, 1);
    buildTest('regex/backreferences/closed_loop_interleaved.js', 2, 1);
    buildTest('regex/backreferences/closed_loop_complex.js', 3, 2);
    buildTest('regex/backreferences/closed_loop_quantified.js', 4, 2); // We fail this test because of the restrictions in the paper

    //Start of open group tests, these will fail often due to restriction on S
    buildTest('regex/backreferences/open.js', 5, 4);
    buildTest('regex/backreferences/open_two.js', 4, 3);
    buildTest('regex/backreferences/open_three.js', 4, 3);
    buildTest('regex/backreferences/open_four.js', 3, 2);

    buildTest('regex/backreferences/open_unlocked.js', 4, 3);
    buildTest('regex/backreferences/open_unlocked_2.js', 4, 3);
    buildTest('regex/backreferences/open_unlocked_3.js', 5, 4);*/

    /**
     * End of backreference tests
     */

    buildTest('regex/captures/greedy2.js', 3, 2);
    buildTest('regex/captures/greedy_capture.js', 3, 2);
    buildTest('regex/captures/simple.js', 4, 3);
    buildTest('regex/captures/anchors.js', 4, 3);
    buildTest('regex/captures/related.js', 3, 2);
    buildTest('regex/captures/multiple_locked.js', 2, 1);

    //buildTest('regex/exec/greed/anchors.js', 4, 3);
    //buildTest('regex/exec/greed/nested.js', 4, 3);
    //buildTest('regex/exec/greed/optionals.js', 3, 2);
    //buildTest('regex/exec/greed/related.js', 3, 2);

    /**
     * Match Tests
     */

    buildTest('regex/match/captures/greedy2.js', 3, 2);
    buildTest('regex/match/captures/greedy_capture.js', 3, 2);
    buildTest('regex/match/captures/simple.js', 4, 3);
    buildTest('regex/match/captures/anchors.js', 4, 3);
    buildTest('regex/match/captures/related.js', 3, 2);
    buildTest('regex/match/captures/multiple_locked.js', 2, 1);

    buildTest('regex/match/greed/anchors.js', 4, 3);
    //buildTest('regex/match/greed/nested.js', 4, 3);
    buildTest('regex/match/greed/optionals.js', 3, 2);
    buildTest('regex/match/greed/related.js', 3, 2);

    /**
     * Replace application model tests
     */

     /*buildTest('regex/replace/single/single_replace.js', 5, 3);
     buildTest('regex/replace/single/replace_2.js', 4, 3);
     buildTest('regex/replace/single/replace_3.js', 5, 4);*/

     /**
      * Split application model tests
      */

     /*buildTest('regex/split/split_1', 14, 4);
     buildTest('regex/split/split_2', 6, 0);
     buildTest('regex/split/split_3', 15, 3);
     buildTest('regex/split/split_4', 35, 0); //PC seems a bit high but the test works
     buildTest('regex/split/split_hard', 8, 2);*/

    /**
     * Sticky model tests
     */
    //buildTest('regex/test/flags/sticky', 3, 1);

    /**
     * Search application model tests
     */

    buildTest('regex/search/simple.js', 2, 2);
    buildTest('regex/search/ambiguous1.js', 3, 2);
    /*buildTest('regex/search/ambiguous2.js', 3, 1); //One extra path spawned by assume command
    buildTest('regex/search/ambiguous3.js', 3, 2); //One extra path spawned by assume command
    buildTest('regex/search/ambiguous4.js', 7, 3); //TODO: Weird results
    buildTest('regex/search/alt.js', 3, 3);
    buildTest('regex/search/not_at_start.js', 3, 3);
    buildTest('regex/search/test_at_start.js', 5, 4);*/

    /**
     * End of regular expression feature tests
     */

    return testList;
}

exports["default"] = buildTestList();
module.exports = exports["default"];
<commit_msg>Fix failed test<commit_after>/* Copyright (c) Royal Holloway, University of London | Contact Blake Loring (blake@parsed.uk), Duncan Mitchell (Duncan.Mitchell.2015@rhul.ac.uk), or Johannes Kinder (johannes.kinder@rhul.ac.uk) for details or support | LICENSE.md for license details */

function buildTestList() {
    var testList = [];

    function buildTest(file, expectPaths, expectErrors) {
        testList.push({
            path: file,
            expectPaths: expectPaths,
            expectErrors: expectErrors
        });
    }

    //Core Javascript, no symbex / annotations
    buildTest('core/bools.js', 1, 0);
    buildTest('core/recursion.js', 1, 0);
    buildTest('core/lamda.js', 1, 0);
    buildTest('core/conc_diff.js', 3, 2);
    buildTest('core/spaced name.js', 2, 1);

    //Booleans
    buildTest('bool/hello.js', 2, 0);
    buildTest('bool/basic.js', 4, 1);

    //Pure Symbols
    buildTest('pure/pure_symbol', 8, 0);
    buildTest('pure/two_symbols', 84, 22);

    //Test symbol renaming
    buildTest('renaming/rename_simple', 3, 2);
    buildTest('renaming/rename', 12, 11);

    //Object Tests
    buildTest('objects/constructor', 2, 1);
    buildTest('objects/concrete.js', 1, 0);
    buildTest('objects/pure_object.js', 10, 1);

    //Array tests
    buildTest('arrays/concrete_checks', 1, 0);
    buildTest('arrays/basic', 8, 3);
    buildTest('arrays/pure', 22, 7);
    buildTest('arrays/update', 3, 2);
    buildTest('arrays/manual_push', 7, 1);
    buildTest('arrays/index_of', 2, 1);
    buildTest('arrays/includes', 2, 1);
    buildTest('arrays/string', 3, 1);
    buildTest('arrays/includes_index_of', 3, 1);
    buildTest('arrays/bool', 5, 3);
    buildTest('arrays/push', 2, 1);
    buildTest('arrays/pop', 2, 1);
    buildTest('arrays/push_conc', 1, 0);
    buildTest('arrays/pop_conc', 1, 0);
    buildTest('arrays/enumerate_concrete', 4, 3);

    //Numbers
    buildTest('numbers/abs.js', 2, 2);
    buildTest('numbers/ten.js', 2, 0);
    buildTest('numbers/hello.js', 2, 0);
    buildTest('numbers/lt.js', 3, 0);
    buildTest('numbers/coerce.js', 2, 0);
    buildTest('numbers/mul.js', 2, 0);
    buildTest('numbers/breaker.js', 1, 0);
    buildTest('numbers/infoflow.js', 17, 0);
    buildTest('numbers/floor.js', 3, 2);
    buildTest('numbers/round.js', 2, 2);

    //Eval
    buildTest('eval/test.js', 2, 1);

    //Fractions
    buildTest('fractions/fraction_one.js', 3, 0);

    buildTest('assert/assert.js', 6, 0);

    buildTest('assumes/basic.js', 2, 0);
    buildTest('assumes/wrapped_assume.js', 2, 0);

    //Loops
    buildTest('loops/loop_alot.js', 12, 0);

    //Named methods
    buildTest('named_method/simple.js', 1, 0);

    //Async
    buildTest('async/settimeout.js', 3, 1);

    //Strings
    buildTest('strings/hello_strings.js', 2, 0);
    buildTest('strings/hello_strings2.js', 3, 0);
    buildTest('strings/hello_strings_concat.js', 2, 0);
    buildTest('strings/lowercase.js', 2, 1);
    buildTest('strings/hello_strings_concat2.js', 1, 0);
    buildTest('strings/hello_strings_len.js', 2, 0);
    buildTest('strings/strings_concat.js', 2, 0);
    buildTest('strings/negative_slice.js', 7, 5); //TODO: Some paths are doubled
    buildTest('strings/substr_tests.js', 7, 5);
    buildTest('strings/strings_concat.js', 2, 0);
    buildTest('strings/warning.js', 4, 0);
    buildTest('strings/repeat.js', 3, 2);
    buildTest('strings/trim.js', 3, 1);

    /**
     * Regular Expression Feature Test
     */

    /**
     * Core language tests
     */
    buildTest('regex/core/alternation/simple.js', 4, 4);
    buildTest('regex/core/alternation/many.js', 4, 4);
    buildTest('regex/core/alternation/words.js', 4, 4);
    buildTest('regex/core/alternation/exhaustive_simple.js', 5, 5);
    buildTest('regex/core/alternation/multiple_related.js', 7, 7);
    buildTest('regex/core/johannes', 5, 4);

    buildTest('regex/core/literals/simple_one.js', 2, 1);
    buildTest('regex/core/literals/simple_two.js', 2, 1);
    buildTest('regex/core/literals/long_example.js', 2, 2);
    buildTest('regex/core/literals/empty_example.js', 2, 2);
    buildTest('regex/core/literals/mixed_escaped.js', 3, 3); //TODO: Should this be 2
    buildTest('regex/core/literals/non_alpha.js', 2, 2);
    buildTest('regex/core/literals/multiple.js', 6, 6);

    /**
    *    TODO: Find out of unicode support is possible through some screwing with Z3 strings
    *    buildTest('regex/core/escaping/hex.js', 5, 4);
    *    buildTest('regex/core/escaping/unicode.js', 6, 5);
    *    buildTest('regex/core/escaping/unicode_mode.js', 6, 5);
    */

    buildTest('regex/core/escaping/ranges.js', 8, 8);
    buildTest('regex/core/escaping/negative_ranges.js', 3, 2);
    buildTest('regex/core/escaping/space_class.js', 8, 7);
    buildTest('regex/core/escaping/word.js', 3, 2);
    buildTest('regex/core/escaping/digit.js', 3, 2);

    buildTest('regex/core/star/star.js', 7, 7);
    buildTest('regex/core/star/online.js', 11, 10);
    buildTest('regex/core/star/lazy.js', 7, 7);
    buildTest('regex/core/star/multiple.js', 5, 5);

    buildTest('regex/core/plus/plus.js', 12, 11);
    buildTest('regex/core/plus/lazy.js', 12, 11);
    buildTest('regex/core/plus/online.js', 11, 10);
    buildTest('regex/core/plus/multiple.js', 4, 4);

    buildTest('regex/core/loops/fixed_loop.js', 3, 2);
    buildTest('regex/core/loops/between_loop.js', 9, 8);
    buildTest('regex/core/loops/minimum_loop.js', 6, 5);

    buildTest('regex/core/optional/base.js', 13, 12);
    buildTest('regex/core/optional/combined.js', 9, 8);
    buildTest('regex/core/optional/no_greed.js', 13, 12);
    buildTest('regex/core/optional/range.js', 3, 2);

    /**
     * Lazy Operator Tests
     */

    buildTest('regex/lazy/lazy_1.js', 3, 2);
    buildTest('regex/lazy/lazy_2.js', 2, 1);
    buildTest('regex/lazy/lazy_3.js', 3, 2);
    buildTest('regex/lazy/lazy_4.js', 2, 1);
    buildTest('regex/lazy/lazy_5.js', 3, 2);
    buildTest('regex/lazy/lazy_6.js', 3, 2);

    /**
     * Anchors Tests
     */
    //buildTest('regex/anchors/left.js', 3, 3);
    //buildTest('regex/anchors/right.js', 3, 3); //TODO: An extra query is generated
    //buildTest('regex/anchors/none.js', 4, 4);
    buildTest('regex/anchors/both.js', 2, 1);

    /**
     * Assertion Tests
     */
    buildTest('regex/assertions/ahead.js', 1, 0);
    buildTest('regex/assertions/ahead_2.js', 2, 1);
    buildTest('regex/assertions/ahead_3.js', 2, 1);
    buildTest('regex/assertions/ahead_4.js', 4, 3);
    buildTest('regex/assertions/ahead_5.js', 4, 3);
    buildTest('regex/assertions/ahead_6.js', 2, 1);
    buildTest('regex/assertions/ahead_7.js', 2, 1);
    buildTest('regex/assertions/ahead_8.js', 2, 1);
    buildTest('regex/assertions/ahead_9.js', 2, 1);

    /**
     * Backreference Tests
     */
    buildTest('regex/backreferences/closed.js', 2, 1);
    buildTest('regex/backreferences/closed_limited.js', 2, 1);
    buildTest('regex/backreferences/closed_range.js', 3, 2);
    buildTest('regex/backreferences/closed_limited.js', 3, 1); //Extra path from assume

    //These we can fail because of restrictions on S
    /*buildTest('regex/backreferences/closed_loop.js', 2, 1);
    buildTest('regex/backreferences/closed_loop_minor.js', 2, 1);
    buildTest('regex/backreferences/closed_loop_interleaved.js', 2, 1);
    buildTest('regex/backreferences/closed_loop_complex.js', 3, 2);
    buildTest('regex/backreferences/closed_loop_quantified.js', 4, 2); // We fail this test because of the restrictions in the paper

    //Start of open group tests, these will fail often due to restriction on S
    buildTest('regex/backreferences/open.js', 5, 4);
    buildTest('regex/backreferences/open_two.js', 4, 3);
    buildTest('regex/backreferences/open_three.js', 4, 3);
    buildTest('regex/backreferences/open_four.js', 3, 2);

    buildTest('regex/backreferences/open_unlocked.js', 4, 3);
    buildTest('regex/backreferences/open_unlocked_2.js', 4, 3);
    buildTest('regex/backreferences/open_unlocked_3.js', 5, 4);*/

    /**
     * End of backreference tests
     */

    buildTest('regex/captures/greedy2.js', 3, 2);
    buildTest('regex/captures/greedy_capture.js', 3, 2);
    buildTest('regex/captures/simple.js', 4, 3);
    buildTest('regex/captures/anchors.js', 4, 3);
    buildTest('regex/captures/related.js', 3, 2);
    buildTest('regex/captures/multiple_locked.js', 2, 1);

    //buildTest('regex/exec/greed/anchors.js', 4, 3);
    //buildTest('regex/exec/greed/nested.js', 4, 3);
    //buildTest('regex/exec/greed/optionals.js', 3, 2);
    //buildTest('regex/exec/greed/related.js', 3, 2);

    /**
     * Match Tests
     */

    buildTest('regex/match/captures/greedy2.js', 3, 2);
    buildTest('regex/match/captures/greedy_capture.js', 3, 2);
    buildTest('regex/match/captures/simple.js', 4, 3);
    buildTest('regex/match/captures/anchors.js', 4, 3);
    buildTest('regex/match/captures/related.js', 3, 2);
    buildTest('regex/match/captures/multiple_locked.js', 2, 1);

    buildTest('regex/match/greed/anchors.js', 4, 3);
    //buildTest('regex/match/greed/nested.js', 4, 3);
    buildTest('regex/match/greed/optionals.js', 3, 2);
    buildTest('regex/match/greed/related.js', 3, 2);

    /**
     * Replace application model tests
     */

     /*buildTest('regex/replace/single/single_replace.js', 5, 3);
     buildTest('regex/replace/single/replace_2.js', 4, 3);
     buildTest('regex/replace/single/replace_3.js', 5, 4);*/

     /**
      * Split application model tests
      */

     /*buildTest('regex/split/split_1', 14, 4);
     buildTest('regex/split/split_2', 6, 0);
     buildTest('regex/split/split_3', 15, 3);
     buildTest('regex/split/split_4', 35, 0); //PC seems a bit high but the test works
     buildTest('regex/split/split_hard', 8, 2);*/

    /**
     * Sticky model tests
     */
    //buildTest('regex/test/flags/sticky', 3, 1);

    /**
     * Search application model tests
     */

    buildTest('regex/search/simple.js', 2, 2);
    buildTest('regex/search/ambiguous1.js', 3, 2);
    /*buildTest('regex/search/ambiguous2.js', 3, 1); //One extra path spawned by assume command
    buildTest('regex/search/ambiguous3.js', 3, 2); //One extra path spawned by assume command
    buildTest('regex/search/ambiguous4.js', 7, 3); //TODO: Weird results
    buildTest('regex/search/alt.js', 3, 3);
    buildTest('regex/search/not_at_start.js', 3, 3);
    buildTest('regex/search/test_at_start.js', 5, 4);*/

    /**
     * End of regular expression feature tests
     */

    return testList;
}

exports["default"] = buildTestList();
module.exports = exports["default"];
<|endoftext|>


<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

'use strict';

/**
 * @fileoverview ProfilingView glues the View control to
 * TracingController.
 */
base.requireStylesheet('about_tracing.profiling_view');
base.require('about_tracing.tracing_controller');
base.require('tracing.timeline_view');
base.require('tracing.record_selection_dialog');
base.require('ui');
base.require('ui.overlay');

/*
 * Here is where we bring in modules that are used in about:tracing UI only.
 */
base.require('tracing.importer.linux_perf_importer');
base.require('tracing.importer.trace_event_importer');
base.require('tracing.importer.v8_log_importer');
base.require('cc.layer_tree_host_impl_view');

base.exportTo('about_tracing', function() {
  /**
   * ProfilingView
   * @constructor
   * @extends {HTMLDivElement}
   */
  var ProfilingView = ui.define('div');

  ProfilingView.prototype = {
    __proto__: HTMLDivElement.prototype,

    traceEvents_: [],
    systemTraceEvents_: [],

    decorate: function() {
      this.classList.add('profiling-view');

      // make the <list>/add/save/record element
      this.recordBn_ = document.createElement('button');
      this.recordBn_.className = 'record';
      this.recordBn_.textContent = 'Record';
      this.recordBn_.addEventListener('click',
                                      this.onSelectCategories_.bind(this));

      this.saveBn_ = document.createElement('button');
      this.saveBn_.className = 'save';
      this.saveBn_.textContent = 'Save';
      this.saveBn_.addEventListener('click', this.onSave_.bind(this));

      this.loadBn_ = document.createElement('button');
      this.loadBn_.textContent = 'Load';
      this.loadBn_.addEventListener('click', this.onLoad_.bind(this));

      this.timelineView_ = new tracing.TimelineView();
      this.timelineView_.leftControls.appendChild(this.recordBn_);
      this.timelineView_.leftControls.appendChild(this.saveBn_);
      this.timelineView_.leftControls.appendChild(this.loadBn_);
      this.timelineView_.viewTitle = undefined;
      this.appendChild(this.timelineView_);

      document.addEventListener('keypress', this.onKeypress_.bind(this));

      this.onCategoriesCollectedBoundToThis_ =
          this.onCategoriesCollected_.bind(this);
      this.onTraceEndedBoundToThis_ = this.onTraceEnded_.bind(this);

      this.refresh_();
    },

    didSetTracingController_: function(value, oldValue) {
      if (oldValue)
        throw new Error('Can only set tracing controller once.');

      this.refresh_();
    },

    refresh_: function() {
      if (!this.tracingController_)
        return;

      var traceEvents = this.tracingController_.traceEvents;
      var hasEvents = traceEvents && traceEvents.length;
      this.saveBn_.disabled = !hasEvents;

      if (!hasEvents) return;

      var traces = [traceEvents];
      if (this.tracingController_.systemTraceEvents.length)
        traces.push(this.tracingController_.systemTraceEvents);

      var m = new tracing.Model();
      m.importTraces(traces, true);
      this.timelineView_.model = m;
    },

    onKeypress_: function(event) {
      if (event.keyCode === 114 &&  // r
          !this.tracingController_.isTracingEnabled &&
          document.activeElement.nodeName !== 'INPUT') {
        this.onSelectCategories_();
      }
    },

    get timelineView() {
      return this.timelineView_;
    },

    ///////////////////////////////////////////////////////////////////////////

    onSelectCategories_: function() {
      var tc = this.tracingController_;
      tc.collectCategories();
      tc.addEventListener('categoriesCollected',
                          this.onCategoriesCollectedBoundToThis_);
    },

    onCategoriesCollected_: function(event) {
      var tc = this.tracingController_;

      var categories = event.categories;
      var categories_length = categories.length;
      // Do not allow categories with ,'s in their name.
      for (var i = 0; i < categories_length; ++i) {
        var split = categories[i].split(',');
        categories[i] = split.shift();
        if (split.length > 0)
          categories = categories.concat(split);
      }

      var dlg = new tracing.RecordSelectionDialog();
      dlg.categories = categories;
      dlg.settings = this.timelineView_.settings;
      dlg.settings_key = 'record_categories';
      dlg.recordCallback = this.onRecord_.bind(this);
      dlg.showSystemTracing = this.tracingController_.supportsSystemTracing;
      dlg.visible = true;
      this.recordSelectionDialog_ = dlg;

      setTimeout(function() {
        tc.removeEventListener('categoriesCollected',
                               this.onCategoriesCollectedBoundToThis_);
      }, 0);
    },

    onRecord_: function() {
      var tc = this.tracingController_;

      var categories = this.recordSelectionDialog_.categoryFilter();
      console.log('Recording: ' + categories);

      tc.beginTracing(this.recordSelectionDialog_.isSystemTracingEnabled(),
                      this.recordSelectionDialog_.isContinuousTracingEnabled(),
                      categories);

      tc.addEventListener('traceEnded', this.onTraceEndedBoundToThis_);
    },

    onTraceEnded_: function() {
      var tc = this.tracingController_;
      this.refresh_();
      setTimeout(function() {
        tc.removeEventListener('traceEnded', this.onTraceEndedBoundToThis_);
      }, 0);
    },

    ///////////////////////////////////////////////////////////////////////////

    onSave_: function() {
      this.overlayEl_ = new ui.Overlay();
      this.overlayEl_.className = 'profiling-overlay';

      var labelEl = document.createElement('div');
      labelEl.className = 'label';
      labelEl.textContent = 'Saving...';
      this.overlayEl_.appendChild(labelEl);
      this.overlayEl_.visible = true;

      var that = this;
      var tc = this.tracingController_;
      function response() {
        that.overlayEl_.visible = false;
        that.overlayEl_ = undefined;
        setTimeout(function() {
          tc.removeEventListener('saveTraceFileComplete', response);
          tc.removeEventListener('saveTraceFileCanceled', response);
        }, 0);
      }
      tc.addEventListener('saveTraceFileComplete', response);
      tc.addEventListener('saveTraceFileCanceled', response);
      tc.beginSaveTraceFile();
    },

    ///////////////////////////////////////////////////////////////////////////

    onLoad_: function() {
      this.overlayEl_ = new ui.Overlay();
      this.overlayEl_.className = 'profiling-overlay';

      var labelEl = document.createElement('div');
      labelEl.className = 'label';
      labelEl.textContent = 'Loading...';
      this.overlayEl_.appendChild(labelEl);
      this.overlayEl_.visible = true;

      var that = this;
      var tc = this.tracingController_;
      this.tracingController_.beginLoadTraceFile();
      function response(e) {
        that.overlayEl_.visible = false;
        that.overlayEl_ = undefined;
        if (e.type == 'loadTraceFileComplete')
          that.refresh_();
        setTimeout(function() {
          tc.removeEventListener('loadTraceFileComplete', response);
          tc.removeEventListener('loadTraceFileCanceled', response);
        }, 0);
      }

      tc.addEventListener('loadTraceFileComplete', response);
      tc.addEventListener('loadTraceFileCanceled', response);
    }
  };

  base.defineProperty(ProfilingView, 'tracingController', base.PropertyKind.JS,
      ProfilingView.prototype.didSetTracingController_);

  return {
    ProfilingView: ProfilingView
  };
});
<commit_msg>Support dropping of files onto chrome://tracing.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

'use strict';

/**
 * @fileoverview ProfilingView glues the View control to
 * TracingController.
 */
base.requireStylesheet('about_tracing.profiling_view');
base.require('about_tracing.tracing_controller');
base.require('tracing.timeline_view');
base.require('tracing.record_selection_dialog');
base.require('ui');
base.require('ui.overlay');

/*
 * Here is where we bring in modules that are used in about:tracing UI only.
 */
base.require('tracing.importer.linux_perf_importer');
base.require('tracing.importer.trace_event_importer');
base.require('tracing.importer.v8_log_importer');
base.require('cc.layer_tree_host_impl_view');

base.exportTo('about_tracing', function() {
  /**
   * ProfilingView
   * @constructor
   * @extends {HTMLDivElement}
   */
  var ProfilingView = ui.define('div');

  ProfilingView.prototype = {
    __proto__: HTMLDivElement.prototype,

    traceEvents_: [],
    systemTraceEvents_: [],

    decorate: function() {
      this.classList.add('profiling-view');

      // make the <list>/add/save/record element
      this.recordBn_ = document.createElement('button');
      this.recordBn_.className = 'record';
      this.recordBn_.textContent = 'Record';
      this.recordBn_.addEventListener('click',
                                      this.onSelectCategories_.bind(this));

      this.saveBn_ = document.createElement('button');
      this.saveBn_.className = 'save';
      this.saveBn_.textContent = 'Save';
      this.saveBn_.addEventListener('click', this.onSave_.bind(this));

      this.loadBn_ = document.createElement('button');
      this.loadBn_.textContent = 'Load';
      this.loadBn_.addEventListener('click', this.onLoad_.bind(this));

      this.timelineView_ = new tracing.TimelineView();
      this.timelineView_.leftControls.appendChild(this.recordBn_);
      this.timelineView_.leftControls.appendChild(this.saveBn_);
      this.timelineView_.leftControls.appendChild(this.loadBn_);
      this.timelineView_.viewTitle = undefined;
      this.appendChild(this.timelineView_);

      document.addEventListener('keypress', this.onKeypress_.bind(this));

      this.onCategoriesCollectedBoundToThis_ =
          this.onCategoriesCollected_.bind(this);
      this.onTraceEndedBoundToThis_ = this.onTraceEnded_.bind(this);

      document.addEventListener('dragstart', this.ignoreHandler_, false);
      document.addEventListener('dragend', this.ignoreHandler_, false);
      document.addEventListener('dragenter', this.ignoreHandler_, false);
      document.addEventListener('dragleave', this.ignoreHandler_, false);
      document.addEventListener('dragover', this.ignoreHandler_, false);
      document.addEventListener('drop', this.dropHandler_.bind(this), false);

      this.refresh_();
    },

    didSetTracingController_: function(value, oldValue) {
      if (oldValue)
        throw new Error('Can only set tracing controller once.');

      this.refresh_();
    },

    refresh_: function() {
      if (!this.tracingController_)
        return;

      var traceEvents = this.tracingController_.traceEvents;
      var hasEvents = traceEvents && traceEvents.length;
      this.saveBn_.disabled = !hasEvents;

      if (!hasEvents) return;

      var traces = [traceEvents];
      if (this.tracingController_.systemTraceEvents.length)
        traces.push(this.tracingController_.systemTraceEvents);

      var m = new tracing.Model();
      m.importTraces(traces, true);
      this.timelineView_.model = m;
    },

    onKeypress_: function(event) {
      if (event.keyCode === 114 &&  // r
          !this.tracingController_.isTracingEnabled &&
          document.activeElement.nodeName !== 'INPUT') {
        this.onSelectCategories_();
      }
    },

    get timelineView() {
      return this.timelineView_;
    },

    ///////////////////////////////////////////////////////////////////////////

    onSelectCategories_: function() {
      var tc = this.tracingController_;
      tc.collectCategories();
      tc.addEventListener('categoriesCollected',
                          this.onCategoriesCollectedBoundToThis_);
    },

    onCategoriesCollected_: function(event) {
      var tc = this.tracingController_;

      var categories = event.categories;
      var categories_length = categories.length;
      // Do not allow categories with ,'s in their name.
      for (var i = 0; i < categories_length; ++i) {
        var split = categories[i].split(',');
        categories[i] = split.shift();
        if (split.length > 0)
          categories = categories.concat(split);
      }

      var dlg = new tracing.RecordSelectionDialog();
      dlg.categories = categories;
      dlg.settings = this.timelineView_.settings;
      dlg.settings_key = 'record_categories';
      dlg.recordCallback = this.onRecord_.bind(this);
      dlg.showSystemTracing = this.tracingController_.supportsSystemTracing;
      dlg.visible = true;
      this.recordSelectionDialog_ = dlg;

      setTimeout(function() {
        tc.removeEventListener('categoriesCollected',
                               this.onCategoriesCollectedBoundToThis_);
      }, 0);
    },

    onRecord_: function() {
      var tc = this.tracingController_;

      var categories = this.recordSelectionDialog_.categoryFilter();
      console.log('Recording: ' + categories);

      tc.beginTracing(this.recordSelectionDialog_.isSystemTracingEnabled(),
                      this.recordSelectionDialog_.isContinuousTracingEnabled(),
                      categories);

      tc.addEventListener('traceEnded', this.onTraceEndedBoundToThis_);
    },

    onTraceEnded_: function() {
      var tc = this.tracingController_;
      this.refresh_();
      setTimeout(function() {
        tc.removeEventListener('traceEnded', this.onTraceEndedBoundToThis_);
      }, 0);
    },

    ///////////////////////////////////////////////////////////////////////////

    onSave_: function() {
      this.overlayEl_ = new ui.Overlay();
      this.overlayEl_.className = 'profiling-overlay';

      var labelEl = document.createElement('div');
      labelEl.className = 'label';
      labelEl.textContent = 'Saving...';
      this.overlayEl_.appendChild(labelEl);
      this.overlayEl_.visible = true;

      var that = this;
      var tc = this.tracingController_;
      function response() {
        that.overlayEl_.visible = false;
        that.overlayEl_ = undefined;
        setTimeout(function() {
          tc.removeEventListener('saveTraceFileComplete', response);
          tc.removeEventListener('saveTraceFileCanceled', response);
        }, 0);
      }
      tc.addEventListener('saveTraceFileComplete', response);
      tc.addEventListener('saveTraceFileCanceled', response);
      tc.beginSaveTraceFile();
    },

    ///////////////////////////////////////////////////////////////////////////

    onLoad_: function() {
      this.overlayEl_ = new ui.Overlay();
      this.overlayEl_.className = 'profiling-overlay';

      var labelEl = document.createElement('div');
      labelEl.className = 'label';
      labelEl.textContent = 'Loading...';
      this.overlayEl_.appendChild(labelEl);
      this.overlayEl_.visible = true;

      var that = this;
      var tc = this.tracingController_;
      this.tracingController_.beginLoadTraceFile();
      function response(e) {
        that.overlayEl_.visible = false;
        that.overlayEl_ = undefined;
        if (e.type == 'loadTraceFileComplete')
          that.refresh_();
        setTimeout(function() {
          tc.removeEventListener('loadTraceFileComplete', response);
          tc.removeEventListener('loadTraceFileCanceled', response);
        }, 0);
      }

      tc.addEventListener('loadTraceFileComplete', response);
      tc.addEventListener('loadTraceFileCanceled', response);
    },

    ///////////////////////////////////////////////////////////////////////////

    ignoreHandler_: function(e) {
      e.preventDefault();
      return false;
    },

    dropHandler_: function(e) {
      e.stopPropagation();
      e.preventDefault();

      var that = this;
      var files = e.dataTransfer.files;
      var files_len = files.length;
      for (var i = 0; i < files_len; ++i) {
        var reader = new FileReader();
        reader.onload = function(data) {
          try {
            that.tracingController.onLoadTraceFileComplete(data.target.result);
            that.refresh_();
          } catch (e) {
            console.log('Unable to import the provided trace file.', e.message);
          }
        };
        reader.readAsText(files[i]);
      }
      return false;
    }
  };

  base.defineProperty(ProfilingView, 'tracingController', base.PropertyKind.JS,
      ProfilingView.prototype.didSetTracingController_);

  return {
    ProfilingView: ProfilingView
  };
});
<|endoftext|>


<commit_before>/*!
 * Copyright 2016 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.
 */

'use strict';

var path = require('path');
var uniq = require('array-uniq');
var globby = require('globby');
var execSync = require('child_process').execSync;
var extend = require('extend');

require('shelljs/global');

/**
 * google-cloud-node root directory.. useful in case we need to cd
 */
var ROOT_DIR = path.join(__dirname, '..');

module.exports.ROOT_DIR = ROOT_DIR;

/**
 * Helper class to make install dependencies + running tests easier to read
 * and less error prone.
 *
 * @class Module
 * @param {string} name - The module name (e.g. common, bigquery, etc.)
 */
function Module(name) {
  if (!(this instanceof Module)) {
    return new Module(name);
  }

  this.name = name;
  this.directory = path.join(ROOT_DIR, 'packages', name);

  var pkgJson = require(path.join(this.directory, 'package.json'));

  this.packageName = pkgJson.name;
  this.dependencies = Object.keys(pkgJson.devDependencies || {});
}

/**
 * Umbrella module name.
 *
 * @static
 */
Module.UMBRELLA = 'google-cloud';

/**
 * Retrieves a list of modules that are ahead of origin/master. We do this by
 * creating a temporary remote branch that points official master branch.
 * We then do a git diff against the two to get a list of files. From there we
 * only care about either JS or JSON files being changed.
 *
 * @static
 * @return {Module[]} modules - The updated modules.
 */
Module.getUpdated = function() {
  cd(ROOT_DIR);

  run([
    'git remote add temp',
    'https://github.com/GoogleCloudPlatform/google-cloud-node.git'
  ]);

  run('git fetch -q temp');

  var output = run('git diff HEAD temp/master --name-only', {
    stdio: null // prevents piping to the console
  });

  var files = output.trim().split('\n');
  var modules = files.filter(function(file) {
    return /^packages\/.+\.js/.test(file);
  }).map(function(file) {
    return file.split('/')[1];
  });

  return uniq(modules).map(Module);
};

/**
 * Builds docs for all modules
 *
 * @static
 */
Module.buildDocs = function() {
  run('npm run docs', { cwd: ROOT_DIR });
};

/**
 * Returns a list containing ALL the modules.
 *
 * @static
 * @return {Module[]} modules - All of em'!
 */
Module.getAll = function() {
  cd(ROOT_DIR);

  return globby
    .sync('*', { cwd: 'packages' })
    .map(Module);
};

/**
 * Returns a list of modules that are dependent on one or more of the modules
 * specified.
 *
 * @static
 * @param {Module[]} modules - The dependency modules.
 * @return {Module[]} modules - The dependent modules.
 */
Module.getDependents = function(modules) {
  return Module.getAll().filter(function(mod) {
    return mod.hasDeps(modules);
  });
};

/**
 * Installs dependencies for all the modules!
 *
 * @static
 */
Module.installAll = function() {
  run('npm run postinstall', { cwd: ROOT_DIR });
};

/**
 * Generates an lcov coverage report for the specified modules.
 *
 * @static
 */
Module.runCoveralls = function() {
  run('npm run coveralls', { cwd: ROOT_DIR });
};

/**
 * Installs this modules dependencies via `npm install`
 */
Module.prototype.install = function() {
  run('npm install', { cwd: this.directory });
};

/**
 * Creates/uses symlink for a module (depending on if module was provided)
 * via `npm link`
 *
 * @param {Module=} mod - The module to use with `npm link ${mod.packageName}`
 */
Module.prototype.link = function(mod) {
  run(['npm link', mod && mod.packageName || ''], {
    cwd: this.directory
  });
};

/**
 * Runs unit tests for this module via `npm run test`
 */
Module.prototype.runUnitTests = function() {
  run('npm run test', { cwd: this.directory });
};

/**
 * Runs snippet tests for this module.
 */
Module.prototype.runSnippetTests = function() {
  process.env.TEST_MODULE = this.name;
  run('npm run snippet-test', { cwd: ROOT_DIR });
  delete process.env.TEST_MODULE;
};

/**
 * Runs system tests for this module via `npm run system-test`
 */
Module.prototype.runSystemTests = function() {
  run('npm run system-test', { cwd: this.directory });
};

/**
 * Checks to see if this module has one or more of the supplied modules
 * as a dev dependency.
 *
 * @param {Module[]} modules - The modules to check for.
 * @return {boolean}
 */
Module.prototype.hasDeps = function(modules) {
  var packageName;

  for (var i = 0; i < modules.length; i++) {
    packageName = modules[i].packageName;

    if (this.dependencies.indexOf(packageName) > -1) {
      return true;
    }
  }

  return false;
};

module.exports.Module = Module;

/**
 * Exec's command via child_process.execSync.
 * By default all output will be piped to the console unless `stdio`
 * is overridden.
 *
 * @param {string|string[]} command - The command to run.
 * @param {object=} options - Options to pass to `execSync`.
 * @return {string|null} -
 */
function run(command, options) {
  var response;

  options = extend({
    stdio: [0, 1, 2]
  }, options);

  if (Array.isArray(command)) {
    command = command.join(' ');
  }

  echo(command);

  try {
    response = execSync(command, options);
  } catch (e) {
    console.error(e.message);
    exit(1);
  }

  if (response instanceof Buffer) {
    return response.toString();
  }
}

module.exports.run = run;

/**
 * Used to make committing to git easier/etc..
 *
 * @param {string=} cwd - Directory to commit/add/push from.
 */
function Git(cwd) {
  this.cwd = cwd || ROOT_DIR;
}

// We'll use this for cloning/submoduling/pushing purposes on CI
Git.REPO = 'https://${GH_OAUTH_TOKEN}@github.com/${GH_OWNER}/${GH_PROJECT_NAME}';

/**
 * Creates a submodule in the root directory in quiet mode.
 *
 * @param {string} branch - The branch to use.
 * @param {string=} alias - Name of the folder that contains submodule.
 * @return {Git}
 */
Git.prototype.submodule = function(branch, alias) {
  alias = alias || branch;

  run(['git submodule add -q -b', branch, Git.REPO, alias], {
    cwd: this.cwd
  });

  return new Git(path.join(this.cwd, alias));
};

/**
 * Check to see if git has any files it can commit.
 *
 * @return {boolean}
 */
Git.prototype.hasUpdates = function() {
  var output = run('git status --porcelain', {
    cwd: this.cwd,
    stdio: null
  });

  return !!output && output.trim().length > 0;
};

/**
 * Sets git user
 *
 * @param {string} name - User name
 * @param {string} email - User email
 */
Git.prototype.setUser = function(name, email) {
  run(['git config user.name', name], {
    cwd: this.cwd
  });

  run(['git config user.email', email], {
    cwd: this.cwd
  });
};

/**
 * Adds all files passed in via git add
 *
 * @param {...string} file - File to add
 */
Git.prototype.add = function() {
  var files = [].slice.call(arguments);
  var command = ['git add'].concat(files);

  run(command, {
    cwd: this.cwd
  });
};

/**
 * Commits to git via commit message.
 *
 * @param {string} message - The commit message.
 */
Git.prototype.commit = function(message) {
  run(['git commit -m', '"' + message + '"', '[ci skip]'], {
    cwd: this.cwd
  });
};

/**
 * Runs git status and pushes changes in quiet mode.
 *
 * @param {string} branch - The branch to push to.
 */
Git.prototype.push = function(branch) {
  run('git status', {
    cwd: this.cwd
  });

  run(['git push -q', Git.REPO, branch], {
    cwd: this.cwd
  });
};

module.exports.git = new Git();

/**
 * The name of the branch currently being tested.
 *
 * @alias ci.BRANCH
 */
var BRANCH = process.env.TRAVIS_BRANCH || process.env.APPVEYOR_REPO_BRANCH;

/**
 * The pull request number.
 *
 * @alias ci.PR_NUMBER;
 */
var PR_NUMBER = process.env.TRAVIS_PULL_REQUEST ||
  process.env.APPVEYOR_PULL_REQUEST_NUMBER;

/**
 * Checks to see if this is a pull request or not.
 *
 * @alias ci.IS_PR
 */
var IS_PR = !isNaN(parseInt(PR_NUMBER, 10));

/**
 * Returns the tag name (assuming this is a release)
 *
 * @alias ci.getTagName
 * @return {string|null}
 */
function getTagName() {
  return process.env.TRAVIS_TAG || process.env.APPVEYOR_REPO_TAG_NAME;
}

/**
 * Let's us know whether or not this is a release.
 *
 * @alias ci.isReleaseBuild
 * @return {string|null}
 */
function isReleaseBuild() {
  return !!getTagName();
}

/**
 * Returns name/version of release.
 *
 * @alias ci.getRelease
 * @return {object|null}
 */
function getRelease() {
  var tag = getTagName();

  if (!tag) {
    return null;
  }

  var parts = tag.split('-');

  return {
    version: parts.pop(),
    name: parts.pop() || Module.UMBRELLA
  };
}

/**
 * Checks to see if this is a push to master.
 *
 * @alias ci.isPushToMaster
 * @return {boolean}
 */
function isPushToMaster() {
  return BRANCH === 'master' && !IS_PR;
}

/**
 * Checks to see if this the CI's first pass (Travis only)
 *
 * @alias ci.isFirstPass
 * @return {boolean}
 */
function isFirstPass() {
  return /\.1$/.test(process.env.TRAVIS_JOB_NUMBER);
}

module.exports.ci = {
  BRANCH: BRANCH,
  IS_PR: IS_PR,
  PR_NUMBER: PR_NUMBER,
  getTagName: getTagName,
  isReleaseBuild: isReleaseBuild,
  getRelease: getRelease,
  isPushToMaster: isPushToMaster,
  isFirstPass: isFirstPass
};
<commit_msg>testing: change command for getting updated files<commit_after>/*!
 * Copyright 2016 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.
 */

'use strict';

var path = require('path');
var uniq = require('array-uniq');
var globby = require('globby');
var execSync = require('child_process').execSync;
var extend = require('extend');

require('shelljs/global');

/**
 * google-cloud-node root directory.. useful in case we need to cd
 */
var ROOT_DIR = path.join(__dirname, '..');

module.exports.ROOT_DIR = ROOT_DIR;

/**
 * Helper class to make install dependencies + running tests easier to read
 * and less error prone.
 *
 * @class Module
 * @param {string} name - The module name (e.g. common, bigquery, etc.)
 */
function Module(name) {
  if (!(this instanceof Module)) {
    return new Module(name);
  }

  this.name = name;
  this.directory = path.join(ROOT_DIR, 'packages', name);

  var pkgJson = require(path.join(this.directory, 'package.json'));

  this.packageName = pkgJson.name;
  this.dependencies = Object.keys(pkgJson.devDependencies || {});
}

/**
 * Umbrella module name.
 *
 * @static
 */
Module.UMBRELLA = 'google-cloud';

/**
 * Retrieves a list of modules that are ahead of origin/master. We do this by
 * creating a temporary remote branch that points official master branch.
 * We then do a git diff against the two to get a list of files. From there we
 * only care about either JS or JSON files being changed.
 *
 * @static
 * @return {Module[]} modules - The updated modules.
 */
Module.getUpdated = function() {
  cd(ROOT_DIR);

  var output = run('git diff HEAD^ --name-only', {
    stdio: null // prevents piping to the console
  });

  var files = output.trim().split('\n');
  var modules = files.filter(function(file) {
    return /^packages\/.+\.js/.test(file);
  }).map(function(file) {
    return file.split('/')[1];
  });

  return uniq(modules).map(Module);
};

/**
 * Builds docs for all modules
 *
 * @static
 */
Module.buildDocs = function() {
  run('npm run docs', { cwd: ROOT_DIR });
};

/**
 * Returns a list containing ALL the modules.
 *
 * @static
 * @return {Module[]} modules - All of em'!
 */
Module.getAll = function() {
  cd(ROOT_DIR);

  return globby
    .sync('*', { cwd: 'packages' })
    .map(Module);
};

/**
 * Returns a list of modules that are dependent on one or more of the modules
 * specified.
 *
 * @static
 * @param {Module[]} modules - The dependency modules.
 * @return {Module[]} modules - The dependent modules.
 */
Module.getDependents = function(modules) {
  return Module.getAll().filter(function(mod) {
    return mod.hasDeps(modules);
  });
};

/**
 * Installs dependencies for all the modules!
 *
 * @static
 */
Module.installAll = function() {
  run('npm run postinstall', { cwd: ROOT_DIR });
};

/**
 * Generates an lcov coverage report for the specified modules.
 *
 * @static
 */
Module.runCoveralls = function() {
  run('npm run coveralls', { cwd: ROOT_DIR });
};

/**
 * Installs this modules dependencies via `npm install`
 */
Module.prototype.install = function() {
  run('npm install', { cwd: this.directory });
};

/**
 * Creates/uses symlink for a module (depending on if module was provided)
 * via `npm link`
 *
 * @param {Module=} mod - The module to use with `npm link ${mod.packageName}`
 */
Module.prototype.link = function(mod) {
  run(['npm link', mod && mod.packageName || ''], {
    cwd: this.directory
  });
};

/**
 * Runs unit tests for this module via `npm run test`
 */
Module.prototype.runUnitTests = function() {
  run('npm run test', { cwd: this.directory });
};

/**
 * Runs snippet tests for this module.
 */
Module.prototype.runSnippetTests = function() {
  process.env.TEST_MODULE = this.name;
  run('npm run snippet-test', { cwd: ROOT_DIR });
  delete process.env.TEST_MODULE;
};

/**
 * Runs system tests for this module via `npm run system-test`
 */
Module.prototype.runSystemTests = function() {
  run('npm run system-test', { cwd: this.directory });
};

/**
 * Checks to see if this module has one or more of the supplied modules
 * as a dev dependency.
 *
 * @param {Module[]} modules - The modules to check for.
 * @return {boolean}
 */
Module.prototype.hasDeps = function(modules) {
  var packageName;

  for (var i = 0; i < modules.length; i++) {
    packageName = modules[i].packageName;

    if (this.dependencies.indexOf(packageName) > -1) {
      return true;
    }
  }

  return false;
};

module.exports.Module = Module;

/**
 * Exec's command via child_process.execSync.
 * By default all output will be piped to the console unless `stdio`
 * is overridden.
 *
 * @param {string|string[]} command - The command to run.
 * @param {object=} options - Options to pass to `execSync`.
 * @return {string|null} -
 */
function run(command, options) {
  var response;

  options = extend({
    stdio: [0, 1, 2]
  }, options);

  if (Array.isArray(command)) {
    command = command.join(' ');
  }

  echo(command);

  try {
    response = execSync(command, options);
  } catch (e) {
    console.error(e.message);
    exit(1);
  }

  if (response instanceof Buffer) {
    return response.toString();
  }
}

module.exports.run = run;

/**
 * Used to make committing to git easier/etc..
 *
 * @param {string=} cwd - Directory to commit/add/push from.
 */
function Git(cwd) {
  this.cwd = cwd || ROOT_DIR;
}

// We'll use this for cloning/submoduling/pushing purposes on CI
Git.REPO = 'https://${GH_OAUTH_TOKEN}@github.com/${GH_OWNER}/${GH_PROJECT_NAME}';

/**
 * Creates a submodule in the root directory in quiet mode.
 *
 * @param {string} branch - The branch to use.
 * @param {string=} alias - Name of the folder that contains submodule.
 * @return {Git}
 */
Git.prototype.submodule = function(branch, alias) {
  alias = alias || branch;

  run(['git submodule add -q -b', branch, Git.REPO, alias], {
    cwd: this.cwd
  });

  return new Git(path.join(this.cwd, alias));
};

/**
 * Check to see if git has any files it can commit.
 *
 * @return {boolean}
 */
Git.prototype.hasUpdates = function() {
  var output = run('git status --porcelain', {
    cwd: this.cwd,
    stdio: null
  });

  return !!output && output.trim().length > 0;
};

/**
 * Sets git user
 *
 * @param {string} name - User name
 * @param {string} email - User email
 */
Git.prototype.setUser = function(name, email) {
  run(['git config user.name', name], {
    cwd: this.cwd
  });

  run(['git config user.email', email], {
    cwd: this.cwd
  });
};

/**
 * Adds all files passed in via git add
 *
 * @param {...string} file - File to add
 */
Git.prototype.add = function() {
  var files = [].slice.call(arguments);
  var command = ['git add'].concat(files);

  run(command, {
    cwd: this.cwd
  });
};

/**
 * Commits to git via commit message.
 *
 * @param {string} message - The commit message.
 */
Git.prototype.commit = function(message) {
  run(['git commit -m', '"' + message + '"', '[ci skip]'], {
    cwd: this.cwd
  });
};

/**
 * Runs git status and pushes changes in quiet mode.
 *
 * @param {string} branch - The branch to push to.
 */
Git.prototype.push = function(branch) {
  run('git status', {
    cwd: this.cwd
  });

  run(['git push -q', Git.REPO, branch], {
    cwd: this.cwd
  });
};

module.exports.git = new Git();

/**
 * The name of the branch currently being tested.
 *
 * @alias ci.BRANCH
 */
var BRANCH = process.env.TRAVIS_BRANCH || process.env.APPVEYOR_REPO_BRANCH;

/**
 * The pull request number.
 *
 * @alias ci.PR_NUMBER;
 */
var PR_NUMBER = process.env.TRAVIS_PULL_REQUEST ||
  process.env.APPVEYOR_PULL_REQUEST_NUMBER;

/**
 * Checks to see if this is a pull request or not.
 *
 * @alias ci.IS_PR
 */
var IS_PR = !isNaN(parseInt(PR_NUMBER, 10));

/**
 * Returns the tag name (assuming this is a release)
 *
 * @alias ci.getTagName
 * @return {string|null}
 */
function getTagName() {
  return process.env.TRAVIS_TAG || process.env.APPVEYOR_REPO_TAG_NAME;
}

/**
 * Let's us know whether or not this is a release.
 *
 * @alias ci.isReleaseBuild
 * @return {string|null}
 */
function isReleaseBuild() {
  return !!getTagName();
}

/**
 * Returns name/version of release.
 *
 * @alias ci.getRelease
 * @return {object|null}
 */
function getRelease() {
  var tag = getTagName();

  if (!tag) {
    return null;
  }

  var parts = tag.split('-');

  return {
    version: parts.pop(),
    name: parts.pop() || Module.UMBRELLA
  };
}

/**
 * Checks to see if this is a push to master.
 *
 * @alias ci.isPushToMaster
 * @return {boolean}
 */
function isPushToMaster() {
  return BRANCH === 'master' && !IS_PR;
}

/**
 * Checks to see if this the CI's first pass (Travis only)
 *
 * @alias ci.isFirstPass
 * @return {boolean}
 */
function isFirstPass() {
  return /\.1$/.test(process.env.TRAVIS_JOB_NUMBER);
}

module.exports.ci = {
  BRANCH: BRANCH,
  IS_PR: IS_PR,
  PR_NUMBER: PR_NUMBER,
  getTagName: getTagName,
  isReleaseBuild: isReleaseBuild,
  getRelease: getRelease,
  isPushToMaster: isPushToMaster,
  isFirstPass: isFirstPass
};
<|endoftext|>


<commit_before>describe('`dpExpandCollapse` directive', () => {
    const FLUSH_PERIOD = 1;
    let $compile;
    let $rootScope;
    let $interval;
    let content = 'Lorem ipsum dolor sit amet.\n';

    beforeEach(module('dpShared'));

    beforeEach(angular.mock.inject((_$compile_, _$rootScope_, _$interval_) => {
        $compile = _$compile_;
        $rootScope = _$rootScope_;
        $interval = _$interval_;
    }));

    it('Should collapse and expand too lengthy content', () => {
        for (let i = 0; i <= 5; i++) {
            content += content;
        }

        const collapsedElement = $compile(`<p dp-expand-collapse>${content}</p>`)($rootScope);

        collapsedElement.css({
            'max-height': '50px',
            overflow: 'hidden'
        });

        angular.element(document).find('body').append(collapsedElement);

        $interval.flush(FLUSH_PERIOD);
        // $timeout.verifyNoPendingTasks();

        const button = angular.element(document).find('body').find('button');

        expect(button).not.toBeUndefined();
        expect(collapsedElement.scope().collapsed).toBeTruthy();

        button.click();

        expect(collapsedElement.scope().collapsed).toBeFalsy();

        button.click();

        expect(collapsedElement.scope().collapsed).toBeTruthy();
    });

    it('Should leave non-lengthy content', () => {
        const untouchedElement = $compile(`<p dp-expand-collapse>${content}</p>`)($rootScope);

        angular.element(document).find('body').append(untouchedElement);

        $interval.flush(FLUSH_PERIOD);
        // $timeout.verifyNoPendingTasks();

        expect(untouchedElement.scope().collapsed).toBeUndefined();
    });
});
<commit_msg>added unit tests for classes in expand collapse directive tg-4035<commit_after>describe('`dpExpandCollapse` directive', () => {
    const FLUSH_PERIOD = 1;
    let $compile;
    let $rootScope;
    let $interval;
    let content = 'Lorem ipsum dolor sit amet.\n';

    beforeEach(module('dpShared'));

    beforeEach(angular.mock.inject((_$compile_, _$rootScope_, _$interval_) => {
        $compile = _$compile_;
        $rootScope = _$rootScope_;
        $interval = _$interval_;
    }));

    it('Should collapse and expand too lengthy content', () => {
        for (let i = 0; i <= 5; i++) {
            content += content;
        }

        const collapsedElement = $compile(`<p dp-expand-collapse>${content}</p>`)($rootScope);

        collapsedElement.css({
            'max-height': '50px',
            overflow: 'hidden'
        });

        angular.element(document).find('body').append(collapsedElement);

        $interval.flush(FLUSH_PERIOD);

        const button = angular.element(document).find('body').find('button');

        expect(button).not.toBeUndefined();
        expect(collapsedElement.scope().collapsed).toBeTruthy();
        expect(collapsedElement).toHaveClass('c-show-more__container');
        expect(collapsedElement).toHaveClass('c-show-more__container--collapsed');

        button.click();

        expect(collapsedElement.scope().collapsed).toBeFalsy();
        expect(collapsedElement).toHaveClass('c-show-more__container');
        expect(collapsedElement).not.toHaveClass('c-show-more__container--collapsed');

        button.click();

        expect(collapsedElement.scope().collapsed).toBeTruthy();
        expect(collapsedElement).toHaveClass('c-show-more__container');
        expect(collapsedElement).toHaveClass('c-show-more__container--collapsed');
    });

    it('Should leave non-lengthy content', () => {
        const untouchedElement = $compile(`<p dp-expand-collapse>${content}</p>`)($rootScope);

        angular.element(document).find('body').append(untouchedElement);

        $interval.flush(FLUSH_PERIOD);

        expect(untouchedElement.scope().collapsed).toBeUndefined();
        expect(untouchedElement).not.toHaveClass('c-show-more__container');
        expect(untouchedElement).not.toHaveClass('c-show-more__container--collapsed');
    });
});
<|endoftext|>