<commit_before>'use strict';

angular.module('theLawFactory')
.directive('amendements', ['$rootScope', '$timeout', '$sce', '$location', 'api',
function ($rootScope, $timeout, $sce, $location, api) {
    return {
        restrict: 'A',
        replace: false,
        templateUrl: 'modules/amendements/amendements.html',
        controller: function ($scope) {
            $scope.step = 0;
            $scope.mod = "amendements";
            $scope.setHelpText("Chaque boîte représente un amendement dont le pictogramme indique le sort et la couleur le groupe politique de ses auteurs. Cliquez sur un amendement pour en lire le contenu et les détails.");
            $scope.trustedHelpText = $sce.trustAsHtml($scope.helpText);
            $scope.vizTitle = "AMENDEMENTS";

            // Permet le focus sur les amendements par groupe ou par sort
            $scope.focusGroupe = null;
            $scope.focusSort = null;

            // Définit le regroupement et le tri des amendements
            $scope.groupAll = $location.search()['group'] === '1'
            $scope.sortOrder = $location.search()['sort'] || 'sort';

            // Mode 2 colonnes
            $scope.twoColumnMode = false;

            // Largeur des sujets
            $scope.subjectWidth = 0;

            // Gestion du tooltip amendements
            $scope.hoverAmendement = null;

            // Permet l'affichage du contenu d'un amendement
            $scope.loadingAmdt = false;
            $scope.selectedAmdt = null;
            $scope.selectedAmdtData = null;

            var viz = thelawfactory.amendements,
                firstDraw = true,
                refreshInterval = 60000;

            // Redessine les dernières données de l'API (à appeler sur changement de tri/groupement)
            function redraw() {
                if (!$scope.apiData) return;
                viz.transformData($scope);

                $timeout(function() {
                    resize();

                    if ($scope.selectedAmdt) {
                        $('.amendement-' + $scope.selectedAmdt.id_api).addClass('selected');
                    }

                    if (firstDraw) {
                        var $focus = $('.sujet.focus');
                        var $viz = $('#viz');

                        if ($focus.length) {
                            $viz.animate({
                                scrollTop: $focus.offset().top - $viz.offset().top
                            });
                        }

                        var amdtNum = $location.search()['amdt'];
                        if (amdtNum) {
                            var $amdt = $('.amendement-num-' + amdtNum);
                            var $sujet = $amdt.parents('.sujet');

                            $amdt.click();
                            $viz.animate({
                                scrollTop: $sujet.offset().top - $viz.offset().top
                            });
                        }

                        firstDraw = false;
                    }
                }, 0);
            }

            // Redimensionne les conteneurs
            function resize() {
                thelawfactory.utils.setModSize("#viz", 1)();
                thelawfactory.utils.setTextContainerHeight();
                viz.measureViewportSize();
            }

            // Lit les données depuis l'API et déclenche le redessin
            function update() {
                if ($scope.etape != null) {
                    // Anime l'icône "live"
                    var started = Date.now();
                    $rootScope.reloading = true;

                    api.getAmendement($scope.loi, $scope.etape)
                    .then(function (data) {
                        thelawfactory.utils.spinner.stop();
                        $scope.apiData = data;
                        $rootScope.pageTitle = $rootScope.lawTitle + " - Amendements | ";

                        // Active l'autorefresh si step en cours
                        $scope.$watch('steps', function(steps) {
                            if (!steps) return;

                            var step = steps.filter(function(s) { return s.directory === $scope.etape; })[0];

                            if (step && step.enddate === "") {
                                $timeout(update, refreshInterval);
                            }
                        });

                        // Attend que l'animation ait au moins duré 1s
                        $timeout(function() {
                            $rootScope.reloading = false;
                        }, Math.max(0, 1000 - (Date.now() - started)));
                    }, function () {
                        $scope.display_error("impossible de trouver les amendements pour ce texte à cette étape");
                    });
                }
            }

            // Affichage du contenu d'un amendement
            $scope.selectAmdt = function(amdt) {
                $('.amendements .amendement.selected').removeClass('selected');

                if (amdt) {
                    $('.amendement-' + amdt.id_api).addClass('selected');

                    thelawfactory.utils.setTextContainerHeight();
                    thelawfactory.utils.spinner.start('load_amd');

                    $scope.loadingAmdt = true;

                    api.getAmendementContent($scope.apiData.api_root_url, amdt.id_api)
                    .then(function(data) {
                        var amdtContenu = data.amendement;

                        amdtContenu.sujet = thelawfactory.utils.cleanAmdSubject(amdtContenu.sujet);
                        amdtContenu.origine = amdtContenu.url_nosdeputes ? 'an' : 'senat';
                        amdtContenu.url = amdtContenu.url_nosdeputes || amdtContenu.url_nossenateurs;

                        $location.search('amdt', amdt.numero);
                        amdtContenu.tlfurl = $location.absUrl();

                        amdtContenu.trustedExpose = $sce.trustAsHtml(amdtContenu.expose);
                        amdtContenu.trustedTexte = $sce.trustAsHtml(amdtContenu.texte);

                        $scope.loadingAmdt = false;
                        $scope.selectedAmdt = amdt;
                        $scope.selectedAmdtData = amdtContenu;

                        thelawfactory.utils.spinner.stop(function () {
                            $('.text-container').scrollTop(0);
                        }, 'load_amd');
                    }, function() {
                        thelawfactory.utils.spinner.stop('load_amd');
                        $scope.display_error("impossible de trouver le contenu de cet amendement");
                    });
                }
            };

            // Focus sur un sujet
            $scope.focusSubject = function($event, article) {
                var $target = $($event.target);
                if ($target.hasClass('amendement')) {
                    if ($target.parents('.sujet').attr('data-article') === $scope.article) return;
                }

                if ($scope.article === article) {
                    // Re-clic sur un article = désélection
                    article = null;
                }

                if (!article) {
                    $scope.article = null;
                    $scope.focusGroupe = null;
                    $scope.focusSort = null;
                } else {
                    $event.stopPropagation();
                    $scope.article = article;
                }

                $location.search('article', article);
            };

            // Focus sur un groupe ou sort
            $scope.focusAmendements = function(e, groupe, sort) {
                e.stopPropagation();

                if (groupe) {
                    $scope.focusGroupe = groupe;
                    $scope.focusSort = null;
                } else {
                    $scope.focusGroupe = null;
                    $scope.focusSort = sort;
                }
            };

            // Formatage de date
            $scope.formatDate = function(date) {
                if (!date) return;

                var m = date.match(/(\d{4})-(\d{2})-(\d{2})/);
                if (m) {
                    return m[3] + '/' + m[2] + '/' + m[1];
                } else {
                    return date;
                }
            };

            // Gestion du tooltip d'un amendement
            var hideTimeout;

            $scope.showTooltip = function(idxSujet, idxAmdt) {
                // Annuler une éventuelle tempo de hideTooltip
                $timeout.cancel(hideTimeout);

                var amdt = $scope.data.sujets[idxSujet].amendements_snake[idxAmdt];

                var $amdt = $('.amendement-' + amdt.id_api);
                var offset = $amdt.position();

                var $tip = $('#amendement-tooltip');
                $tip.css({ top: offset.top + 'px', left: offset.left + 'px', opacity: 1 });

                $scope.hoverAmendement = amdt;
            };

            $scope.hideTooltip = function() {
                // Tempo pour éviter un clignotement dans le cas où la souris se balade vite
                hideTimeout = $timeout(function() {
                    var $tip = $('#amendement-tooltip');
                    $tip.css({ opacity: 0 });

                    // Laisser finir l'animation css avant d'effacer le contenu
                    hideTimeout = $timeout(function() {
                        $scope.hoverAmendement = null;
                    }, 250);
                }, 50);
            };

            // Déclencheurs de redessin
            $scope.$watchGroup(['apiData', 'groupAll', 'sortOrder'], redraw);

            // Déclencheurs de modification de l'URL
            $scope.$watch('sortOrder', function() {
                var value = $scope.sortOrder;
                $location.search('sort', value === 'sort' ? null : value);
            });

            $scope.$watch('groupAll', function() {
                var value = $scope.groupAll;
                $location.search('group', value ? '1' : null);
            });

            // Redimensionnement automatique
            var resizing;
            $(window).on('resize', function() {
                $timeout.cancel(resizing);
                resizing = $timeout(function() {
                    resize();
                    viz.transformData($scope, true);
                    resizing = false;
                }, 200);
            });

            // Appuis claviers
            var directions = {
                '37': 'left',
                '38': 'up',
                '39': 'right',
                '40': 'down'
            };
            $(window).on('keydown', function(e) {
                if (!$scope.selectedAmdt) return;
                if (!(e.keyCode in directions)) return

                var amdt = $scope.selectedAmdt;
                var $amdt = $('.amendement-' + amdt.id_api);
                var $sujet = $amdt.parents('.sujet');
                var sujet = $sujet.scope().sujet;

                var newid = viz.getOffsetAmendmentId($scope, amdt, sujet, directions[e.keyCode]);
                if (newid) {
                    $('.amendement-' + newid).click();
                    e.preventDefault();
                }
            });

            // Chargement initial
            var initFinished = $scope.$watch('etape', function() {
                // Arrêt du $watch
                initFinished();

                // Déclenchement de la mise à jour des données
                update();

                // Recalcul des dimensions
                resize();

                // Affichage du spinner
                thelawfactory.utils.spinner.start();
            });
        }
    }
}]);<commit_msg>Unregister event handlers on scope destroyed<commit_after>'use strict';

angular.module('theLawFactory')
.directive('amendements', ['$rootScope', '$timeout', '$sce', '$location', 'api',
function ($rootScope, $timeout, $sce, $location, api) {
    return {
        restrict: 'A',
        replace: false,
        templateUrl: 'modules/amendements/amendements.html',
        controller: function ($scope) {
            $scope.step = 0;
            $scope.mod = "amendements";
            $scope.setHelpText("Chaque boîte représente un amendement dont le pictogramme indique le sort et la couleur le groupe politique de ses auteurs. Cliquez sur un amendement pour en lire le contenu et les détails.");
            $scope.trustedHelpText = $sce.trustAsHtml($scope.helpText);
            $scope.vizTitle = "AMENDEMENTS";

            // Permet le focus sur les amendements par groupe ou par sort
            $scope.focusGroupe = null;
            $scope.focusSort = null;

            // Définit le regroupement et le tri des amendements
            $scope.groupAll = $location.search()['group'] === '1'
            $scope.sortOrder = $location.search()['sort'] || 'sort';

            // Mode 2 colonnes
            $scope.twoColumnMode = false;

            // Largeur des sujets
            $scope.subjectWidth = 0;

            // Gestion du tooltip amendements
            $scope.hoverAmendement = null;

            // Permet l'affichage du contenu d'un amendement
            $scope.loadingAmdt = false;
            $scope.selectedAmdt = null;
            $scope.selectedAmdtData = null;

            var viz = thelawfactory.amendements,
                firstDraw = true,
                refreshInterval = 60000;

            // Redessine les dernières données de l'API (à appeler sur changement de tri/groupement)
            function redraw() {
                if (!$scope.apiData) return;
                viz.transformData($scope);

                $timeout(function() {
                    resize();

                    if ($scope.selectedAmdt) {
                        $('.amendement-' + $scope.selectedAmdt.id_api).addClass('selected');
                    }

                    if (firstDraw) {
                        var $focus = $('.sujet.focus');
                        var $viz = $('#viz');

                        if ($focus.length) {
                            $viz.animate({
                                scrollTop: $focus.offset().top - $viz.offset().top
                            });
                        }

                        var amdtNum = $location.search()['amdt'];
                        if (amdtNum) {
                            var $amdt = $('.amendement-num-' + amdtNum);
                            var $sujet = $amdt.parents('.sujet');

                            $amdt.click();
                            $viz.animate({
                                scrollTop: $sujet.offset().top - $viz.offset().top
                            });
                        }

                        firstDraw = false;
                    }
                }, 0);
            }

            // Redimensionne les conteneurs
            function resize() {
                thelawfactory.utils.setModSize("#viz", 1)();
                thelawfactory.utils.setTextContainerHeight();
                viz.measureViewportSize();
            }

            // Lit les données depuis l'API et déclenche le redessin
            function update() {
                if ($scope.etape != null) {
                    // Anime l'icône "live"
                    var started = Date.now();
                    $rootScope.reloading = true;

                    api.getAmendement($scope.loi, $scope.etape)
                    .then(function (data) {
                        thelawfactory.utils.spinner.stop();
                        $scope.apiData = data;
                        $rootScope.pageTitle = $rootScope.lawTitle + " - Amendements | ";

                        // Active l'autorefresh si step en cours
                        $scope.$watch('steps', function(steps) {
                            if (!steps) return;

                            var step = steps.filter(function(s) { return s.directory === $scope.etape; })[0];

                            if (step && step.enddate === "") {
                                $timeout(update, refreshInterval);
                            }
                        });

                        // Attend que l'animation ait au moins duré 1s
                        $timeout(function() {
                            $rootScope.reloading = false;
                        }, Math.max(0, 1000 - (Date.now() - started)));
                    }, function () {
                        $scope.display_error("impossible de trouver les amendements pour ce texte à cette étape");
                    });
                }
            }

            // Affichage du contenu d'un amendement
            $scope.selectAmdt = function(amdt) {
                $('.amendements .amendement.selected').removeClass('selected');

                if (amdt) {
                    $('.amendement-' + amdt.id_api).addClass('selected');

                    thelawfactory.utils.setTextContainerHeight();
                    thelawfactory.utils.spinner.start('load_amd');

                    $scope.loadingAmdt = true;

                    api.getAmendementContent($scope.apiData.api_root_url, amdt.id_api)
                    .then(function(data) {
                        var amdtContenu = data.amendement;

                        amdtContenu.sujet = thelawfactory.utils.cleanAmdSubject(amdtContenu.sujet);
                        amdtContenu.origine = amdtContenu.url_nosdeputes ? 'an' : 'senat';
                        amdtContenu.url = amdtContenu.url_nosdeputes || amdtContenu.url_nossenateurs;

                        $location.search('amdt', amdt.numero);
                        amdtContenu.tlfurl = $location.absUrl();

                        amdtContenu.trustedExpose = $sce.trustAsHtml(amdtContenu.expose);
                        amdtContenu.trustedTexte = $sce.trustAsHtml(amdtContenu.texte);

                        $scope.loadingAmdt = false;
                        $scope.selectedAmdt = amdt;
                        $scope.selectedAmdtData = amdtContenu;

                        thelawfactory.utils.spinner.stop(function () {
                            $('.text-container').scrollTop(0);
                        }, 'load_amd');
                    }, function() {
                        thelawfactory.utils.spinner.stop('load_amd');
                        $scope.display_error("impossible de trouver le contenu de cet amendement");
                    });
                }
            };

            // Focus sur un sujet
            $scope.focusSubject = function($event, article) {
                var $target = $($event.target);
                if ($target.hasClass('amendement')) {
                    if ($target.parents('.sujet').attr('data-article') === $scope.article) return;
                }

                if ($scope.article === article) {
                    // Re-clic sur un article = désélection
                    article = null;
                }

                if (!article) {
                    $scope.article = null;
                    $scope.focusGroupe = null;
                    $scope.focusSort = null;
                } else {
                    $event.stopPropagation();
                    $scope.article = article;
                }

                $location.search('article', article);
            };

            // Focus sur un groupe ou sort
            $scope.focusAmendements = function(e, groupe, sort) {
                e.stopPropagation();

                if (groupe) {
                    $scope.focusGroupe = groupe;
                    $scope.focusSort = null;
                } else {
                    $scope.focusGroupe = null;
                    $scope.focusSort = sort;
                }
            };

            // Formatage de date
            $scope.formatDate = function(date) {
                if (!date) return;

                var m = date.match(/(\d{4})-(\d{2})-(\d{2})/);
                if (m) {
                    return m[3] + '/' + m[2] + '/' + m[1];
                } else {
                    return date;
                }
            };

            // Gestion du tooltip d'un amendement
            var hideTimeout;

            $scope.showTooltip = function(idxSujet, idxAmdt) {
                // Annuler une éventuelle tempo de hideTooltip
                $timeout.cancel(hideTimeout);

                var amdt = $scope.data.sujets[idxSujet].amendements_snake[idxAmdt];

                var $amdt = $('.amendement-' + amdt.id_api);
                var offset = $amdt.position();

                var $tip = $('#amendement-tooltip');
                $tip.css({ top: offset.top + 'px', left: offset.left + 'px', opacity: 1 });

                $scope.hoverAmendement = amdt;
            };

            $scope.hideTooltip = function() {
                // Tempo pour éviter un clignotement dans le cas où la souris se balade vite
                hideTimeout = $timeout(function() {
                    var $tip = $('#amendement-tooltip');
                    $tip.css({ opacity: 0 });

                    // Laisser finir l'animation css avant d'effacer le contenu
                    hideTimeout = $timeout(function() {
                        $scope.hoverAmendement = null;
                    }, 250);
                }, 50);
            };

            // Déclencheurs de redessin
            $scope.$watchGroup(['apiData', 'groupAll', 'sortOrder'], redraw);

            // Déclencheurs de modification de l'URL
            $scope.$watch('sortOrder', function() {
                var value = $scope.sortOrder;
                $location.search('sort', value === 'sort' ? null : value);
            });

            $scope.$watch('groupAll', function() {
                var value = $scope.groupAll;
                $location.search('group', value ? '1' : null);
            });

            // Redimensionnement automatique
            var resizing;
            function handleResize() {
                $timeout.cancel(resizing);
                resizing = $timeout(function() {
                    resize();
                    viz.transformData($scope, true);
                    resizing = false;
                }, 200);
            }

            // Appuis claviers
            var directions = {
                '37': 'left',
                '38': 'up',
                '39': 'right',
                '40': 'down'
            };
            function handleKeyDown(e) {
                if (!$scope.selectedAmdt) return;
                if (!(e.keyCode in directions)) return;

                var amdt = $scope.selectedAmdt;
                var $amdt = $('.amendement-' + amdt.id_api);
                var $sujet = $amdt.parents('.sujet');
                var sujet = $sujet.scope().sujet;

                var newid = viz.getOffsetAmendmentId($scope, amdt, sujet, directions[e.keyCode]);
                if (newid) {
                    $('.amendement-' + newid).click();
                    e.preventDefault();
                }
            }

            $(window).on('keydown', handleKeyDown);
            $(window).on('resize', handleResize);

            $scope.$on('$destroy', function() {
                $(window).off('keydown', handleKeyDown)
                $(window).off('resize', handleResize)
            });

            // Chargement initial
            var initFinished = $scope.$watch('etape', function() {
                // Arrêt du $watch
                initFinished();

                // Déclenchement de la mise à jour des données
                update();

                // Recalcul des dimensions
                resize();

                // Affichage du spinner
                thelawfactory.utils.spinner.start();
            });
        }
    }
}]);<|endoftext|>


<commit_before>// Includes file dependencies
define([
	"jquery",
	"backbone",
    "marionette",
    "text!../templates/patronage-list-item.html",
    "backform",
    "bootstrap-datepicker",
    "moment"
], function( $, Backbone, Marionette, patronage_html, Backform, datepicker, moment ) {

    // Extends Backbone.View
    var View = Backbone.View.extend( {
        initialize: function(options) {
            var view = this;
            view.options = options;
            var momentFormat = 'MM/DD/YYYY';
            var datepickerFormat = 'mm/dd/yyyy';
            var backmodel = view.model.clone();
            backmodel.set("paidOn", moment(backmodel.get("paidOn")).format(momentFormat))
            backmodel.set("expiresOn", moment(backmodel.get("expiresOn")).format(momentFormat))
            view.form = new Backform.Form({
                el: view.$el,
                model: backmodel,
                fields: [
                    {
                        name: "owner.objectId",
                        label: "Owner",
                        control: "input",
                        disabled: true
                    },
                    {
                        name: "paidOn",
                        control: "datepicker",
                        type: "text",
                        options: {
                            autoclose: true,
                            format: datepickerFormat
                        }
                    },
                    {
                        name: "expiresOn",
                        control: "datepicker",
                        type: "text",
                        options: {
                            autoclose: true,
                            format: datepickerFormat
                        }
                    },
                    {
                        name: "submit",
                        control: "button",
                        label: "Save Changes"
                    }
                ],
                events: {
                    "submit": function (e) {
                        var self = this;
                        e.preventDefault();
                        view.model.set({
                            "paidOn": moment(self.model.get("paidOn"), momentFormat).toDate(),
                            "expiresOn": moment(self.model.get("expiresOn"), momentFormat).toDate()
                        })
                        view.model.save().then(function () {
                            self.fields.at(3).set({status: "success", message: "Save completed"});
                        }).fail(function(error) {
                            self.model.errorModel.set("owner", _.escape(error.message));
                        })
                    }
                }
            });
        },
        tagName: 'form',
        render: function() {
            this.form.render();
            this.$el.enhanceWithin();

            return this;
        }
    } );

    // Returns the View class
    return View;

} );<commit_msg>Show selectable users in the patronage form<commit_after>// Includes file dependencies
define([
	"jquery",
	"backbone",
    "marionette",
    "text!../templates/patronage-list-item.html",
    "backform",
    "bootstrap-datepicker",
    "moment"
], function( $, Backbone, Marionette, patronage_html, Backform, datepicker, moment ) {

    // Extends Backbone.View
    var View = Backbone.View.extend( {
        initialize: function(options) {
            var view = this;
            view.options = options;
            var momentFormat = 'MM/DD/YYYY';
            var datepickerFormat = 'mm/dd/yyyy';
            var backmodel = view.model.clone();
            backmodel.set("paidOn", moment(backmodel.get("paidOn")).format(momentFormat))
            backmodel.set("expiresOn", moment(backmodel.get("expiresOn")).format(momentFormat))
            var ownerOptions = options.users.map(function (u) {
                return {
                    label: "" + u.get("username") + " " + u.get("realname") + " " + u.get("email"),
                    value: u.id
                }
            });
            view.form = new Backform.Form({
                el: view.$el,
                model: backmodel,
                fields: [
                    {
                        name: "owner.objectId",
                        label: "Owner",
                        control: "select",
                        options: ownerOptions
                    },
                    {
                        name: "paidOn",
                        label: "Paid on",
                        control: "datepicker",
                        type: "text",
                        options: {
                            autoclose: true,
                            format: datepickerFormat
                        }
                    },
                    {
                        name: "expiresOn",
                        label: "Expires on",
                        control: "datepicker",
                        type: "text",
                        options: {
                            autoclose: true,
                            format: datepickerFormat
                        }
                    },
                    {
                        name: "submit",
                        control: "button",
                        label: "Save Changes"
                    }
                ],
                events: {
                    "submit": function (e) {
                        var self = this;
                        e.preventDefault();
                        view.model.set({
                            "paidOn": moment(self.model.get("paidOn"), momentFormat).toDate(),
                            "expiresOn": moment(self.model.get("expiresOn"), momentFormat).toDate()
                        })
                        view.model.save().then(function () {
                            self.fields.at(3).set({status: "success", message: "Save completed"});
                        }).fail(function(error) {
                            self.model.errorModel.set("owner", _.escape(error.message));
                        })
                    }
                }
            });
        },
        tagName: 'form',
        render: function() {
            this.form.render();
            this.$el.enhanceWithin();

            return this;
        }
    } );

    // Returns the View class
    return View;

} );<|endoftext|>


<commit_before>/*
 * ghetto-profiler
 *
 *
 * Copyright (c) 2012 Alan Clarke
 * Licensed under the MIT license.
 */

var Snitch = function(log){
	this.opts = { log:log };
	this.data = [];
};

Snitch.prototype = {
	next: function(name){
		var s = this;
		var last = s.stop();
		s.data.push({ name:name, start:s._capture()});
		return last;
	},
	stop: function(){
		var s = this;
		if(s.data.length){
			var last = s.data[s.data.length-1];
				if(!last.stop){
				last.stop = s._capture();
				last.ms = last.stop.time- last.start.time;

				if(s.opts.log){
					console.log(last);
				}
				return last;
			}
		}
	},
	_capture:function(){
		var e = new Error();
		var index = 3;
		var callee_stack =  e.stack.split('\n');
		for(var i =0;i<callee_stack.length;i++){
			if(callee_stack[i].indexOf(__filename.replace(/^.*\//,''))>=0){
				index = i+1;
			}
		}
		callee_stack = callee_stack[index].split(':');
		return { time: new Date().valueOf(), file:callee_stack[0].replace(/^.*\//,''), line:callee_stack[1] };
	},
	summarize: function(){
		var s = this;
		var last = s.stop();
		var data = s.data.sort(function(a,b){ return b.ms - a.ms; });
		if(s.opts.log){
			console.log(data);
		}
		return data;
	},
	summarise: function(){
		return this.summarize();
	}
};

module.exports = Snitch;

<commit_msg>The summarize() function should not sort by time<commit_after>/*
 * ghetto-profiler
 *
 *
 * Copyright (c) 2012 Alan Clarke
 * Licensed under the MIT license.
 */

var Snitch = function (log) {
    this.opts = {
        log: log
    };
    this.data = [];
};

Snitch.prototype = {
    next: function (name) {
        var s = this;
        var last = s.stop();
        s.data.push({
            name: name,
            start: s._capture()
        });
        return last;
    },
    stop: function () {
        var s = this;
        if (s.data.length) {
            var last = s.data[s.data.length - 1];
            if (!last.stop) {
                last.stop = s._capture();
                last.ms = last.stop.time - last.start.time;

                if (s.opts.log) {
                    console.log(last);
                }
                return last;
            }
        }
    },
    _capture: function () {
        var e = new Error();
        var index = 3;
        var callee_stack = e.stack.split('\n');
        for (var i = 0; i < callee_stack.length; i++) {
            if (callee_stack[i].indexOf(__filename.replace(/^.*\//, '')) >= 0) {
                index = i + 1;
            }
        }
        callee_stack = callee_stack[index].split(':');
        return {
            time: new Date().valueOf(),
            file: callee_stack[0].replace(/^.*\//, ''),
            line: callee_stack[1]
        };
    },
    summarize: function () {
        var s = this;
        var last = s.stop();
        var data = s.data;
        if (s.opts.log) {
            console.log(data);
        }
        return data;
    },
    summarise: function () {
        return this.summarize();
    },
    sortedSummary: function () {
        var s = this;
        var last = s.stop();
        var data = s.data.sort(function (a, b) {
            return b.ms - a.ms;
        });
        if (s.opts.log) {
            console.log(data);
        }
        return data;
    }
};

module.exports = Snitch;<|endoftext|>


<commit_before>VISH.Editor.Tools = (function(V,$,undefined){

	var toolbarEventsLoaded = false;
	var INCREASE_SIZE = 1.05; //Constant to multiply or divide the actual size of the element

	/*
	 * Toolbar is divided in three zones.
	 * 1) Menu
	 * 1) Presentation toolbar (always visible and updated when current slide changed)
	 * 3) Element toolbar
	 */

	var init = function(){
		cleanToolbar();
		cleanZoneTools();

		var presentationType = V.Editor.getPresentationType();
		if(presentationType !== V.Constant.PRESENTATION){
			disableToolbar();
			return;
		}

		if(!toolbarEventsLoaded){
			//Add listeners to toolbar buttons
			$.each($("#toolbar_wrapper a.tool_action"), function(index, toolbarButton) {
				$(toolbarButton).on("click", function(event){
					if(typeof V.Editor.Tools[$(toolbarButton).attr("action")] == "function"){
						if(!$(toolbarButton).parent().hasClass("toolbar_presentation_wrapper_disabled")){
							V.Editor.Tools[$(toolbarButton).attr("action")](this);
						}
					}
				});
			});

			//Add key event for Add Url Input
			$(document).on('keydown', '.tools_input_addUrl', _addUrlOnKeyDown);

			toolbarEventsLoaded = true;
		}

		V.Editor.Tools.Menu.init();
	}

	var cleanToolbar = function(){
		loadToolsForSlide(V.Slides.getCurrentSlide());
		_cleanElementToolbar();
	}

	var enableToolbar = function(){
		$("#toolbar_wrapper").show();
	}

	var disableToolbar = function(){
		$("#toolbar_wrapper").hide();
	}

   /*
	* Menu Toolbar and Menu itself
	*/
	//Enable and disable menu methods in VISH.Editor.Tools.Menu.js

   /*
	* Presentation Toolbar
	*/

	/*
	 * Update toolbar when load slide
	 */
	var loadToolsForSlide = function(slide){
		_cleanPresentationToolbar();

		var type = $(slide).attr("type");
		switch(type){
			case V.Constant.STANDARD:
				$("#toolbar_background").parent().addClass("toolbar_presentation_wrapper_disabled");
				break;
			case V.Constant.FLASHCARD:
				break;
			case V.Constant.VTOUR:
				$("#toolbar_background").parent().addClass("toolbar_presentation_wrapper_disabled");
				break;
			default:
				return;
		}
	}

	var _cleanPresentationToolbar = function(){
		//Enable all buttons
		$(".toolbar_presentation_wrapper").removeClass("toolbar_presentation_wrapper_disabled");
	}

   /*
	* Zone Tools
	*/
	var loadToolsForZone = function(zone){
		cleanZoneTools();

		var type = $(zone).clone().attr("type");

		switch(type){
			case "text":
				_loadToolbarForElement(type);
				break;
			case "image":
				_loadToolbarForElement(type);
				break;
			case "video":
				_loadToolbarForElement(type);
				break;
			case "object":
				var object = $(zone).find(".object_wrapper").children()[0];
				loadToolbarForObject(object);
				break;
			case "snapshot":
				_loadToolbarForElement("snapshot");
				break;
			case "quiz":
				_loadToolbarForElement("quiz");
				break;
			case undefined:
				//Add menuselect button
				$(zone).find(".menuselect_hide").show();
				return;
			default:
				break;
		}

		//Add delete content button
		$(zone).find(".delete_content").show();
	};

	var cleanZoneTools = function(zone){
		$(".menuselect_hide").hide();
		$(".delete_content").hide();
		_cleanElementToolbar();
	}

   /*
	* Element Toolbar
	*/

	var _loadToolbarForElement = function(type){
		_cleanElementToolbar();
		if(type=="text" || type=="quiz"){
			_loadTextToolbar();
			return;
		}

		var toolbarClass = "toolbar_" + type;
		$("#toolbar_element").find("img").hide();
		$("#toolbar_element").find("img." + toolbarClass).show();
	}

	var _loadTextToolbar = function(){
		$("#toolbar_element").find("img").hide();
		$("#toolbar_text").show();
	}

	var loadToolbarForObject = function(object){
		var objectInfo = V.Object.getObjectInfo(object);

		switch(objectInfo.type){
			case "web":
				_loadToolbarForElement(objectInfo.type);
				break;
			default:
				_loadToolbarForElement("object");
				//object default toolbar
				break;
		}
	}

	var _cleanElementToolbar = function(){
		//Wysiwyg Toolbar
		$("#toolbar_text").hide();
		//Generic Toolbars
		$("#toolbar_element").find("img").hide();
	}

   /*
	* Presentation actions
    */

    var save = function(){
		V.Editor.Tools.Menu.onSaveButtonClicked();
	}

	var publish = function(){
		V.Editor.Tools.Menu.onPublishButtonClicked();
	}

	var preview = function(){
		V.Editor.Preview.preview();
	}

	var selectTheme = function(){
		$("#hidden_button_to_launch_theme_fancybox").trigger("click");
	}

	var changeBackground = function(){
		$("#hidden_button_to_launch_picture_fancybox_for_flashcard").trigger("click");
	}

   /*
	* Element actions
	*/

	var zoomMore = function(){
    	_changeZoom("+");
	};

	var zoomLess = function(){
    	_changeZoom("-");
	};

	var resizeMore = function(){
		_resize("+");
	};

	var resizeLess = function(){
		_resize("-");
	};

	var _resize = function(action){
		var object, objectInfo, resizeFactor;
		var area = V.Editor.getCurrentArea();
		var type = $(area).attr("type");

		if(action=="+"){
			resizeFactor = INCREASE_SIZE;
		} else {
			resizeFactor = 1/INCREASE_SIZE;
		}

		switch(type){
			case "snapshot":
				var snapshot_wrapper = area.children(":first");
				var proportion = $(snapshot_wrapper).height()/$(snapshot_wrapper).width();
				var originalWidth = $(snapshot_wrapper).width();

				//Change width
				snapshot_wrapper.width(originalWidth*resizeFactor);
				snapshot_wrapper.height(originalWidth*resizeFactor*proportion);

				break;
			case "object":
				var parent = area.children(":first");
				object = parent.children(":first");
				objectInfo = V.Object.getObjectInfo(object);

				var newWidth, newHeight;
				var aspectRatio = parent.width()/parent.height();
				var originalHeight = object.height();
				var originalWidth = object.width();
				var parentoriginalHeight = parent.height();
				var parentoriginalWidth = parent.width();

				//Change width
				$(parent).width(parentoriginalWidth*resizeFactor);
				$(parent).height(parentoriginalHeight*resizeFactor);

				var styleZoom = V.Utils.getZoomFromStyle($(object).attr("style"));
				if(styleZoom!=1){
					newWidth = newWidth/styleZoom;
					newHeight = Math.round(newWidth/aspectRatio);
					newWidth = Math.round(newWidth);
				} else {
					newHeight = parentoriginalHeight*resizeFactor;
					newWidth = parentoriginalWidth*resizeFactor;
				}

				$(object).width(newWidth);
				$(object).height(newHeight);
				break;
			case "image":
				object = $(area).find("img");

				var originalHeight = object.height();
				var originalWidth = object.width();

				//Change width
				object.width(originalWidth*resizeFactor);
				object.height(originalHeight*resizeFactor);

				break;
			case "video":
				object = $(area).find("video");

				var originalHeight = object.height();
				var originalWidth = object.width();

				//Change width
				object.width(originalWidth*resizeFactor);
				object.height(originalHeight*resizeFactor);

				break;
			default:
				break;
		}
	};

	var _changeZoom = function(action){
		var object, objectInfo, zoom;
		var area = V.Editor.getCurrentArea();
		var type = $(area).attr("type");
		switch(type){
			case "object":
				var parent = area.children(":first");
				object = parent.children(":first");
				objectInfo = V.Object.getObjectInfo(object);
				if(objectInfo.type==="web"){
					var iframe = $(area).find("iframe");
					zoom = V.Utils.getZoomFromStyle($(iframe).attr("style"));

					if(action=="+"){
						zoom = zoom + 0.1;
					} else {
						zoom = zoom - 0.1;
					}

					$(iframe).attr("style",V.Editor.Utils.addZoomToStyle($(iframe).attr("style"),zoom));

					//Resize object to fix in its wrapper
					V.Editor.Object.autofixWrapperedObjectAfterZoom(iframe,zoom);
				}
				break;
			default:
				break;
		}
	}

	var addLink = function(){
		$.fancybox(
			$("#tools_addUrl").html(),
			{
				'autoDimensions'	: false,
				'scrolling': 'no',
				'width'         	: 800,
				'height'        	: 215,
				'showCloseButton'	: true,
				'padding' 			: 0,
				'onStart'			: function(){
				},
				'onComplete'		: function(){
					var area = V.Editor.getCurrentArea();
					var hyperlink = $(area).attr("hyperlink");
					if(hyperlink){
						$(".tools_input_addUrl").val(hyperlink);
						$(".removeUrlButton").show();
					} else {
						$(".removeUrlButton").hide();
					}
				},
				'onClosed'	: function(){
					$(".removeUrlButton").hide();
				}
			}
		);
	}

	var _addUrlOnKeyDown = function(event){
		switch (event.keyCode) {
			case 13:
				addUrl();
				break;
			default:
				break;
		}
	}

	var addUrl = function(){
		var url;
		$(".tools_input_addUrl").each(function(index,input){
			if($($(input).parent().parent()).attr("id") !== "tools_addUrl"){
				url = $(input).val();
			}
		});
		if(url){
			url = V.Editor.Utils.autocompleteUrls(url);

			var area = V.Editor.getCurrentArea();
			switch($(area).attr("type")){
				case "image":
					$(area).attr("hyperlink",url);
					break;
				default:
					//Currently only for images
					break;
			}
		}
		$.fancybox.close();
	};

	var removeUrl = function(){
		var area = V.Editor.getCurrentArea();
		$(area).removeAttr("hyperlink");
		$.fancybox.close();
	}

	return {
		init							: init,
		loadToolsForSlide				: loadToolsForSlide,
		loadToolsForZone				: loadToolsForZone,
		loadToolbarForObject			: loadToolbarForObject,
		cleanZoneTools 					: cleanZoneTools,
		cleanToolbar					: cleanToolbar,
		enableToolbar					: enableToolbar,
		disableToolbar					: disableToolbar,
		addLink							: addLink,
		addUrl 							: addUrl,
		removeUrl 						: removeUrl,
		resizeMore						: resizeMore,
		resizeLess						: resizeLess,
		zoomMore 						: zoomMore,
		zoomLess 						: zoomLess,
		save 							: save,
		publish							: publish,
		preview 						: preview,
		selectTheme						: selectTheme,
		changeBackground				: changeBackground
	};

}) (VISH, jQuery);<commit_msg>Toolbar zone actions enabled<commit_after>VISH.Editor.Tools = (function(V,$,undefined){

	var toolbarEventsLoaded = false;
	var INCREASE_SIZE = 1.05; //Constant to multiply or divide the actual size of the element

	/*
	 * Toolbar is divided in three zones.
	 * 1) Menu
	 * 1) Presentation toolbar (always visible and updated when current slide changed)
	 * 3) Element toolbar
	 */

	var init = function(){
		cleanToolbar();
		cleanZoneTools();

		var presentationType = V.Editor.getPresentationType();
		if(presentationType !== V.Constant.PRESENTATION){
			disableToolbar();
			return;
		}

		if(!toolbarEventsLoaded){
			//Add listeners to toolbar buttons
			$.each($("#toolbar_wrapper a.tool_action, img.toolbar_icon"), function(index, toolbarButton) {
				$(toolbarButton).on("click", function(event){
					if(typeof V.Editor.Tools[$(toolbarButton).attr("action")] == "function"){
						if(!$(toolbarButton).parent().hasClass("toolbar_presentation_wrapper_disabled")){
							V.Editor.Tools[$(toolbarButton).attr("action")](this);
						}
					}
				});
			});

			//Add key event for Add Url Input
			$(document).on('keydown', '.tools_input_addUrl', _addUrlOnKeyDown);

			toolbarEventsLoaded = true;
		}

		V.Editor.Tools.Menu.init();
	}

	var cleanToolbar = function(){
		loadToolsForSlide(V.Slides.getCurrentSlide());
		_cleanElementToolbar();
	}

	var enableToolbar = function(){
		$("#toolbar_wrapper").show();
	}

	var disableToolbar = function(){
		$("#toolbar_wrapper").hide();
	}

   /*
	* Menu Toolbar and Menu itself
	*/
	//Enable and disable menu methods in VISH.Editor.Tools.Menu.js

   /*
	* Presentation Toolbar
	*/

	/*
	 * Update toolbar when load slide
	 */
	var loadToolsForSlide = function(slide){
		_cleanPresentationToolbar();

		var type = $(slide).attr("type");
		switch(type){
			case V.Constant.STANDARD:
				$("#toolbar_background").parent().addClass("toolbar_presentation_wrapper_disabled");
				break;
			case V.Constant.FLASHCARD:
				break;
			case V.Constant.VTOUR:
				$("#toolbar_background").parent().addClass("toolbar_presentation_wrapper_disabled");
				break;
			default:
				return;
		}
	}

	var _cleanPresentationToolbar = function(){
		//Enable all buttons
		$(".toolbar_presentation_wrapper").removeClass("toolbar_presentation_wrapper_disabled");
	}

   /*
	* Zone Tools
	*/
	var loadToolsForZone = function(zone){
		cleanZoneTools();

		var type = $(zone).clone().attr("type");

		switch(type){
			case "text":
				_loadToolbarForElement(type);
				break;
			case "image":
				_loadToolbarForElement(type);
				break;
			case "video":
				_loadToolbarForElement(type);
				break;
			case "object":
				var object = $(zone).find(".object_wrapper").children()[0];
				loadToolbarForObject(object);
				break;
			case "snapshot":
				_loadToolbarForElement("snapshot");
				break;
			case "quiz":
				_loadToolbarForElement("quiz");
				break;
			case undefined:
				//Add menuselect button
				$(zone).find(".menuselect_hide").show();
				return;
			default:
				break;
		}

		//Add delete content button
		$(zone).find(".delete_content").show();
	};

	var cleanZoneTools = function(zone){
		$(".menuselect_hide").hide();
		$(".delete_content").hide();
		_cleanElementToolbar();
	}

   /*
	* Element Toolbar
	*/

	var _loadToolbarForElement = function(type){
		_cleanElementToolbar();
		if(type=="text" || type=="quiz"){
			_loadTextToolbar();
			return;
		}

		var toolbarClass = "toolbar_" + type;
		$("#toolbar_element").find("img").hide();
		$("#toolbar_element").find("img." + toolbarClass).show();
	}

	var _loadTextToolbar = function(){
		$("#toolbar_element").find("img").hide();
		$("#toolbar_text").show();
	}

	var loadToolbarForObject = function(object){
		var objectInfo = V.Object.getObjectInfo(object);

		switch(objectInfo.type){
			case "web":
				_loadToolbarForElement(objectInfo.type);
				break;
			default:
				_loadToolbarForElement("object");
				//object default toolbar
				break;
		}
	}

	var _cleanElementToolbar = function(){
		//Wysiwyg Toolbar
		$("#toolbar_text").hide();
		//Generic Toolbars
		$("#toolbar_element").find("img").hide();
	}

   /*
	* Presentation actions
    */

    var save = function(){
		V.Editor.Tools.Menu.onSaveButtonClicked();
	}

	var publish = function(){
		V.Editor.Tools.Menu.onPublishButtonClicked();
	}

	var preview = function(){
		V.Editor.Preview.preview();
	}

	var selectTheme = function(){
		$("#hidden_button_to_launch_theme_fancybox").trigger("click");
	}

	var changeBackground = function(){
		$("#hidden_button_to_launch_picture_fancybox_for_flashcard").trigger("click");
	}

   /*
	* Element actions
	*/

	var zoomMore = function(){
    	_changeZoom("+");
	};

	var zoomLess = function(){
    	_changeZoom("-");
	};

	var resizeMore = function(){
		_resize("+");
	};

	var resizeLess = function(){
		_resize("-");
	};

	var _resize = function(action){
		var object, objectInfo, resizeFactor;
		var area = V.Editor.getCurrentArea();
		var type = $(area).attr("type");

		if(action=="+"){
			resizeFactor = INCREASE_SIZE;
		} else {
			resizeFactor = 1/INCREASE_SIZE;
		}

		switch(type){
			case "snapshot":
				var snapshot_wrapper = area.children(":first");
				var proportion = $(snapshot_wrapper).height()/$(snapshot_wrapper).width();
				var originalWidth = $(snapshot_wrapper).width();

				//Change width
				snapshot_wrapper.width(originalWidth*resizeFactor);
				snapshot_wrapper.height(originalWidth*resizeFactor*proportion);

				break;
			case "object":
				var parent = area.children(":first");
				object = parent.children(":first");
				objectInfo = V.Object.getObjectInfo(object);

				var newWidth, newHeight;
				var aspectRatio = parent.width()/parent.height();
				var originalHeight = object.height();
				var originalWidth = object.width();
				var parentoriginalHeight = parent.height();
				var parentoriginalWidth = parent.width();

				//Change width
				$(parent).width(parentoriginalWidth*resizeFactor);
				$(parent).height(parentoriginalHeight*resizeFactor);

				var styleZoom = V.Utils.getZoomFromStyle($(object).attr("style"));
				if(styleZoom!=1){
					newWidth = newWidth/styleZoom;
					newHeight = Math.round(newWidth/aspectRatio);
					newWidth = Math.round(newWidth);
				} else {
					newHeight = parentoriginalHeight*resizeFactor;
					newWidth = parentoriginalWidth*resizeFactor;
				}

				$(object).width(newWidth);
				$(object).height(newHeight);
				break;
			case "image":
				object = $(area).find("img");

				var originalHeight = object.height();
				var originalWidth = object.width();

				//Change width
				object.width(originalWidth*resizeFactor);
				object.height(originalHeight*resizeFactor);

				break;
			case "video":
				object = $(area).find("video");

				var originalHeight = object.height();
				var originalWidth = object.width();

				//Change width
				object.width(originalWidth*resizeFactor);
				object.height(originalHeight*resizeFactor);

				break;
			default:
				break;
		}
	};

	var _changeZoom = function(action){
		var object, objectInfo, zoom;
		var area = V.Editor.getCurrentArea();
		var type = $(area).attr("type");
		switch(type){
			case "object":
				var parent = area.children(":first");
				object = parent.children(":first");
				objectInfo = V.Object.getObjectInfo(object);
				if(objectInfo.type==="web"){
					var iframe = $(area).find("iframe");
					zoom = V.Utils.getZoomFromStyle($(iframe).attr("style"));

					if(action=="+"){
						zoom = zoom + 0.1;
					} else {
						zoom = zoom - 0.1;
					}

					$(iframe).attr("style",V.Editor.Utils.addZoomToStyle($(iframe).attr("style"),zoom));

					//Resize object to fix in its wrapper
					V.Editor.Object.autofixWrapperedObjectAfterZoom(iframe,zoom);
				}
				break;
			default:
				break;
		}
	}

	var addLink = function(){
		$.fancybox(
			$("#tools_addUrl").html(),
			{
				'autoDimensions'	: false,
				'scrolling': 'no',
				'width'         	: 800,
				'height'        	: 215,
				'showCloseButton'	: true,
				'padding' 			: 0,
				'onStart'			: function(){
				},
				'onComplete'		: function(){
					var area = V.Editor.getCurrentArea();
					var hyperlink = $(area).attr("hyperlink");
					if(hyperlink){
						$(".tools_input_addUrl").val(hyperlink);
						$(".removeUrlButton").show();
					} else {
						$(".removeUrlButton").hide();
					}
				},
				'onClosed'	: function(){
					$(".removeUrlButton").hide();
				}
			}
		);
	}

	var _addUrlOnKeyDown = function(event){
		switch (event.keyCode) {
			case 13:
				addUrl();
				break;
			default:
				break;
		}
	}

	var addUrl = function(){
		var url;
		$(".tools_input_addUrl").each(function(index,input){
			if($($(input).parent().parent()).attr("id") !== "tools_addUrl"){
				url = $(input).val();
			}
		});
		if(url){
			url = V.Editor.Utils.autocompleteUrls(url);

			var area = V.Editor.getCurrentArea();
			switch($(area).attr("type")){
				case "image":
					$(area).attr("hyperlink",url);
					break;
				default:
					//Currently only for images
					break;
			}
		}
		$.fancybox.close();
	};

	var removeUrl = function(){
		var area = V.Editor.getCurrentArea();
		$(area).removeAttr("hyperlink");
		$.fancybox.close();
	}

	return {
		init							: init,
		loadToolsForSlide				: loadToolsForSlide,
		loadToolsForZone				: loadToolsForZone,
		loadToolbarForObject			: loadToolbarForObject,
		cleanZoneTools 					: cleanZoneTools,
		cleanToolbar					: cleanToolbar,
		enableToolbar					: enableToolbar,
		disableToolbar					: disableToolbar,
		addLink							: addLink,
		addUrl 							: addUrl,
		removeUrl 						: removeUrl,
		resizeMore						: resizeMore,
		resizeLess						: resizeLess,
		zoomMore 						: zoomMore,
		zoomLess 						: zoomLess,
		save 							: save,
		publish							: publish,
		preview 						: preview,
		selectTheme						: selectTheme,
		changeBackground				: changeBackground
	};

}) (VISH, jQuery);<|endoftext|>


<commit_before>'use strict';
/**
 * Created by chregi on 2/28/15.
 */

 // parse a date in yyyy-mm-dd format
function parseDate(input) {
  var parts = input.match(/(\d+)/g);
  // new Date(year, month [, date [, hours[, minutes[, seconds[, ms]]]]])
  return new Date(parts[0], parts[1]-1, parts[2]); // months are 0-based
}

var getSchedule = function() {

	var id = jQuery('#srs-schedule').attr('data-teamid');

	$.ajax({
	    url: "http://api.swissrugbystats.ch/teams/"+id+"/games.json",
	    success: function(data){

            /* build schedule table
             * TODO:
             * - kickoff vs result
             * - provided by rugbygear.ch claim
            */
            var tableStr = "";
            tableStr = "

Datum	Host	Guest	Kickoff / Result

";
            for (var i = 0; i < data.length; i++) {
                // parse the date
                var d = parseDate(data[i].date);
                var dStr = ("0" + d.getDate()).slice(-2) +"."+ ("0"+d.getMonth()).slice(-2) +"."+ d.getFullYear();
                tableStr += "
" + dStr + "	" + data[i].host.team.name + "	" + data[i].guest.team.name + "
";
            }

            tableStr += "

";
            jQuery("#srs-schedule").html(tableStr);
	    }
	});

}

var getNextGame = function() {

	var id = jQuery('#srs-nextGame').attr('data-teamid');

	$.ajax({
	    url: "http://api.swissrugbystats.ch/nextGameByTeamId/"+id+"/.json",
	    success: function(data){
	      jQuery('#srs-nextGame').html("Host: " + data.host.team.name + "
Guest: " + data.guest.team.name);
	    }
	});
}

getSchedule();
getNextGame();<commit_msg>missed two $<commit_after>'use strict';
/**
 * Created by chregi on 2/28/15.
 */

 // parse a date in yyyy-mm-dd format
function parseDate(input) {
  var parts = input.match(/(\d+)/g);
  // new Date(year, month [, date [, hours[, minutes[, seconds[, ms]]]]])
  return new Date(parts[0], parts[1]-1, parts[2]); // months are 0-based
}

var getSchedule = function() {

	var id = jQuery('#srs-schedule').attr('data-teamid');

	jQuery.ajax({
	    url: "http://api.swissrugbystats.ch/teams/"+id+"/games.json",
	    success: function(data){

            /* build schedule table
             * TODO:
             * - kickoff vs result
             * - provided by rugbygear.ch claim
            */
            var tableStr = "";
            tableStr = "

Datum	Host	Guest	Kickoff / Result

";
            for (var i = 0; i < data.length; i++) {
                // parse the date
                var d = parseDate(data[i].date);
                var dStr = ("0" + d.getDate()).slice(-2) +"."+ ("0"+d.getMonth()).slice(-2) +"."+ d.getFullYear();
                tableStr += "
" + dStr + "	" + data[i].host.team.name + "	" + data[i].guest.team.name + "
";
            }

            tableStr += "

";
            jQuery("#srs-schedule").html(tableStr);
	    }
	});

}

var getNextGame = function() {

	var id = jQuery('#srs-nextGame').attr('data-teamid');

	jQuery.ajax({
	    url: "http://api.swissrugbystats.ch/nextGameByTeamId/"+id+"/.json",
	    success: function(data){
	      jQuery('#srs-nextGame').html("Host: " + data.host.team.name + "
Guest: " + data.guest.team.name);
	    }
	});
}

getSchedule();
getNextGame();<|endoftext|>


<commit_before>'use strict';
/**
 * Created by chregi on 2/28/15.
 * v0.2 - 17.9.2015
 * - new: season id needed for schedule
 * - new: next game endpoint changed
 * - fixed: removed ".json" from all API calls
 * v0.1 - 13.4.2015
 * - fixed: Kickoff time daylight saving independent
 * - new: put Day in schedule table
 */

 // parse a date in yyyy-mm-dd format
function parseDate(input) {
  if (input instanceof Date) {
    return input;
  } else {
      var parts = input.match(/(\d+)/g);
      // new Date(year, month [, date [, hours[, minutes[, seconds[, ms]]]]])
      return new Date(parts[0], parts[1]-1, parts[2], parts[3], parts[4]); // months are 0-based
  }
}

function getDateString(date){
    return ('0' + date.getDate()).slice(-2) +'.'+ ('0'+(date.getMonth()+1)).slice(-2) +'.'+ date.getFullYear();
}

function getKickoffTimeString(date){
    if (!(date instanceof Date)) {
        date = parseDate(date);
    }
    return (date.getHours() + getHourCorrection(date)) + ':'+ ('0' + date.getMinutes()).slice(-2) + ' Uhr';
}

// get hours to add / subtract to date to fix timezone errors
function getHourCorrection(date) {
    return - (date.getTimezoneOffset() / 60);
}

// Get day of week from a date as String
function getDayOfWeek(date) {
    var dow = ['So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa'];
    return dow[date.getDay()];
}

var getSchedule = function(team_id, season_id) {
    var selector = '.srs-schedule[data-teamid='+team_id+'][data-seasonid='+season_id+']';

	jQuery.ajax({
	    url: 'http://api.swissrugbystats.ch/teams/'+team_id+'/games/season/'+season_id,
	    success: function(data){

            /* build schedule table
             * TODO:
             * - set links
            */
            var tableStr = '';
            tableStr = "

Datum	Host	Guest	Kickoff / Result

";
            for (var i = 0; i < data.length; i++) {
                // parse the date
                var d = parseDate(data[i].date);
                var dStr = getDateString(d);

                // game result
                if ((data[i].host.score != null) && (data[i].guest.score != null)) {
                    var result = data[i].host.score + " : " + data[i].guest.score;
                } else {
                    var result = getKickoffTimeString(data[i].date);
                }

                tableStr += "
" + getDayOfWeek(d) +", "+ dStr + "	" + data[i].host.team.name + "	" + data[i].guest.team.name + "	" + result + "
";
            }

            tableStr += "

";
            jQuery(selector).html(tableStr);

            jQuery(selector).append("

All game data provided by Swiss Rugby Stats");
	    }
	});
}

var getSchedules = function() {

    var scheduleTags = jQuery('.srs-schedule');
    jQuery('.srs-schedule').each(function( index ) {
        var team_id = jQuery( this ).attr('data-teamid');
        var season_id = jQuery( this ).attr('data-seasonid');
        getSchedule(team_id, season_id);
    });
}

var getNextGame = function() {

	var id = jQuery('.srs-next_game').attr('data-teamid');

	jQuery.ajax({
	    url: "http://api.swissrugbystats.ch/teams/"+id+"/games/next",
	    success: function(data){
          var d = parseDate(data.date);
          var dStr = getDayOfWeek(d) +", "+getDateString(d) + ", " +getKickoffTimeString(d);
	      jQuery('.srs-next_game').html(dStr + "
" + data.host.team.name + " vs " + data.guest.team.name);
	    }
	});
}

var getNextGames = function() {

    var nextGameTags = jQuery('.srs-next_game');
    jQuery('.srs-next_game').each(function( index ) {
        var team_id = jQuery( this ).attr('data-teamid');
        getNextGame(team_id);
    });
}

/* execute as soon as DOM is ready
 * TODO: check for existing tags first to reduce ajax calls to minimum
 */
window.onload = function() {

	getSchedules();
	getNextGames();

};<commit_msg>fix selector<commit_after>'use strict';
/**
 * Created by chregi on 2/28/15.
 * v0.2 - 17.9.2015
 * - new: season id needed for schedule
 * - new: next game endpoint changed
 * - fixed: removed ".json" from all API calls
 * v0.1 - 13.4.2015
 * - fixed: Kickoff time daylight saving independent
 * - new: put Day in schedule table
 */

 // parse a date in yyyy-mm-dd format
function parseDate(input) {
  if (input instanceof Date) {
    return input;
  } else {
      var parts = input.match(/(\d+)/g);
      // new Date(year, month [, date [, hours[, minutes[, seconds[, ms]]]]])
      return new Date(parts[0], parts[1]-1, parts[2], parts[3], parts[4]); // months are 0-based
  }
}

function getDateString(date){
    return ('0' + date.getDate()).slice(-2) +'.'+ ('0'+(date.getMonth()+1)).slice(-2) +'.'+ date.getFullYear();
}

function getKickoffTimeString(date){
    if (!(date instanceof Date)) {
        date = parseDate(date);
    }
    return (date.getHours() + getHourCorrection(date)) + ':'+ ('0' + date.getMinutes()).slice(-2) + ' Uhr';
}

// get hours to add / subtract to date to fix timezone errors
function getHourCorrection(date) {
    return - (date.getTimezoneOffset() / 60);
}

// Get day of week from a date as String
function getDayOfWeek(date) {
    var dow = ['So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa'];
    return dow[date.getDay()];
}

var getSchedule = function(team_id, season_id) {
    var selector = '.srs-schedule[data-teamid='+team_id+'][data-seasonid='+season_id+']';

	jQuery.ajax({
	    url: 'http://api.swissrugbystats.ch/teams/'+team_id+'/games/season/'+season_id,
	    success: function(data){

            /* build schedule table
             * TODO:
             * - set links
            */
            var tableStr = '';
            tableStr = "

Datum	Host	Guest	Kickoff / Result

";
            for (var i = 0; i < data.length; i++) {
                // parse the date
                var d = parseDate(data[i].date);
                var dStr = getDateString(d);

                // game result
                if ((data[i].host.score != null) && (data[i].guest.score != null)) {
                    var result = data[i].host.score + " : " + data[i].guest.score;
                } else {
                    var result = getKickoffTimeString(data[i].date);
                }

                tableStr += "
" + getDayOfWeek(d) +", "+ dStr + "	" + data[i].host.team.name + "	" + data[i].guest.team.name + "	" + result + "
";
            }

            tableStr += "

";
            jQuery(selector).html(tableStr);

            jQuery(selector).append("

All game data provided by Swiss Rugby Stats");
	    }
	});
}

var getSchedules = function() {

    var scheduleTags = jQuery('.srs-schedule');
    jQuery('.srs-schedule').each(function( index ) {
        var team_id = jQuery( this ).attr('data-teamid');
        var season_id = jQuery( this ).attr('data-seasonid');
        getSchedule(team_id, season_id);
    });
}

var getNextGame = function() {

	var id = jQuery('.srs-next_game').attr('data-teamid');
    var selector = '.srs-next_game[data-teamid='+id+']';

	jQuery.ajax({
	    url: "http://api.swissrugbystats.ch/teams/"+id+"/games/next",
	    success: function(data){
          var d = parseDate(data.date);
          var dStr = getDayOfWeek(d) +", "+getDateString(d) + ", " +getKickoffTimeString(d);
	      jQuery(selector).html(dStr + "
" + data.host.team.name + " vs " + data.guest.team.name);
	    }
	});
}

var getNextGames = function() {

    var nextGameTags = jQuery('.srs-next_game');
    jQuery('.srs-next_game').each(function( index ) {
        var team_id = jQuery( this ).attr('data-teamid');
        getNextGame(team_id);
    });
}

/* execute as soon as DOM is ready
 * TODO: check for existing tags first to reduce ajax calls to minimum
 */
window.onload = function() {

	getSchedules();
	getNextGames();

};<|endoftext|>


<commit_before>// Product of MCGA

window.PIVisualization = window.PIVisualization || {};

(function (PV) {
    'use strict';

    function init(scope, elem, $rootScope, routeParams, webServices, navHierarchy) {

        scope.updateDisplayNavLinks = updateDisplayNavLinks;
        scope.linkData = null;

        $rootScope.$on('$stateChangeSuccess', updateDisplayNavLinks);

        (function activate() {
            updateDisplayNavLinks();
        })();

        function updateDisplayNavLinks(navItem) {
            var displayId = (navItem && navItem.DisplayId) || routeParams.getDisplayId();
            if (displayId > -1) {
                navHierarchy.addParent(navItem && navItem.LinkURL && navItem);
                webServices.getDisplayForEditing(displayId).then(
                    function (response) {
                        // get initial navigation links from current display
                        scope.linkData = {
                            parents: navHierarchy.parents,
                            parent: navHierarchy.parents[navHierarchy.parents.length - 1],
                            children: getNavLinks(response.data)
                        };
                    },
                    function (errorObject) {
                        // reset on error
                        reset();
                    }
                );
            } else {
                reset();
            }
        }

        function reset() {
            navHierarchy.parents.length = 0;
            scope.linkData = null;
        }

        function getNavLinks(display) {
            var symbols = display.Symbols || [];

            return symbols.filter(function (symbol) {
                // collect symbols wtih navigation links
                return !!(symbol.Configuration && symbol.Configuration.LinkURL);
            }).map(function (symbol) {
                // map the properties we care about
                var config = symbol.Configuration,
                    isDisplay = config.LinkURL.indexOf('./#/Displays/') === 0,
                    displayUrlParts = isDisplay ? config.LinkURL.substring(13).split('/') : null;
                var existsInParents = navHierarchy.parents.some(function(parent) {
                    return parent.LinkURL === config.LinkURL;
                });
                return {
                    DisplayId: isDisplay ? displayUrlParts[0] : null,
                    DisplayName: isDisplay ? displayUrlParts[1] : config.LinkURL,
                    IncludeAsset: config.IncludeAsset,
                    IncludeTimeRange: config.IncludeTimeRange,
                    IsDisplay: isDisplay,
                    LinkURL: config.LinkURL,
                    NewTab: config.NewTab,
                    SymbolName: symbol.Name,
                    IsDisabled: !isDisplay || existsInParents
                };
            });
        }

        return {};
    }

    var def = {
        typeName: 'nav',
        displayName: 'Navigation links',
        getDefaultConfig: function () {
            return {};
        },
        iconUrl: 'Images/chrome.custom_addin_crossed_tools.svg',
        inject: ['$rootScope', 'routeParams', 'webServices', 'navHierarchy'],
        init: init
    };

    PV.toolCatalog.register(def);

})(window.PIVisualization);<commit_msg>Symbol selection<commit_after>// Product of MCGA

window.PIVisualization = window.PIVisualization || {};

(function (PV) {
    'use strict';

    function init(scope, elem, $rootScope, displayProvider, routeParams, webServices, navHierarchy) {

        scope.updateDisplayNavLinks = updateDisplayNavLinks;
        scope.selectSymbol = selectSymbol;
        scope.linkData = null;

        $rootScope.$on('$stateChangeSuccess', updateDisplayNavLinks);

        (function activate() {
            updateDisplayNavLinks();
        })();

        function updateDisplayNavLinks(navItem) {
            var displayId = (navItem && navItem.DisplayId) || routeParams.getDisplayId();
            if (displayId > -1) {
                navHierarchy.addParent(navItem && navItem.LinkURL && navItem);
                webServices.getDisplayForEditing(displayId).then(
                    function (response) {
                        // get initial navigation links from current display
                        scope.linkData = {
                            parents: navHierarchy.parents,
                            parent: navHierarchy.parents[navHierarchy.parents.length - 1],
                            children: getNavLinks(response.data)
                        };
                    },
                    function (errorObject) {
                        // reset on error
                        reset();
                    }
                );
            } else {
                reset();
            }
        }

        function reset() {
            navHierarchy.parents.length = 0;
            scope.linkData = null;
        }

        function getNavLinks(display) {
            var symbols = display.Symbols || [];

            return symbols.filter(function (symbol) {
                // collect symbols wtih navigation links
                return !!(symbol.Configuration && symbol.Configuration.LinkURL);
            }).map(function (symbol) {
                // map the properties we care about
                var config = symbol.Configuration,
                    isDisplay = config.LinkURL.indexOf('./#/Displays/') === 0,
                    displayUrlParts = isDisplay ? config.LinkURL.substring(13).split('/') : null;
                var existsInParents = navHierarchy.parents.some(function(parent) {
                    return parent.LinkURL === config.LinkURL;
                });
                return {
                    DisplayId: isDisplay ? displayUrlParts[0] : null,
                    DisplayName: isDisplay ? displayUrlParts[1] : config.LinkURL,
                    IncludeAsset: config.IncludeAsset,
                    IncludeTimeRange: config.IncludeTimeRange,
                    IsDisplay: isDisplay,
                    LinkURL: config.LinkURL,
                    NewTab: config.NewTab,
                    SymbolName: symbol.Name,
                    IsDisabled: !isDisplay || existsInParents
                };
            });
        }

        function selectSymbol(link) {
            displayProvider.selectSymbol(link.SymbolName);
        }

        return {};
    }

    var def = {
        typeName: 'nav',
        displayName: 'Navigation links',
        getDefaultConfig: function () {
            return {};
        },
        iconUrl: 'Images/chrome.custom_addin_crossed_tools.svg',
        inject: ['$rootScope', 'displayProvider', 'routeParams', 'webServices', 'navHierarchy'],
        init: init
    };

    PV.toolCatalog.register(def);

})(window.PIVisualization);
<|endoftext|>


<commit_before><commit_msg>Complete JavaScript file<commit_after>// test0.js //
(function() {
  var main, test;

  test = function(i, j) {
    return i * j;
  };

  main = function() {
    var i, j, k;
    i = 2;
    j = 3;
    k = test(i, j);
    if (k > 5) {
      print(">5");
    } else {
      print("<=5");
    }
  };

  main();

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


<commit_before>import CatalogueDataObjectFactory from '../src/catalogue-factory/CatalogueDataObjectFactory'
import CatalogueDataObject from '../src/catalogue-factory/CatalogueDataObject'
import RuntimeConstraint from '../src/catalogue-factory/RuntimeConstraint'
import {CatalogueObjectType} from '../src/catalogue-factory/CatalogueDataObject'
import {DataObjectSourceLanguage} from '../src/catalogue-factory/CatalogueDataObject'
import {HypertyType} from '../src/catalogue-factory/HypertyDescriptor'

import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';

let expect = chai.expect;
chai.use(chaiAsPromised);

//Testing the CatalogueDataObject-Factory
describe('CatalogueDataObjectFactory', function () {

    let catalogueDataObjectFactory;

    describe('constructor()', function () {

        it('should create a CatalogueDataObject-Factory object without error', function (done) {
            catalogueDataObjectFactory = new CatalogueDataObjectFactory("false", '{}');
            done();
        });

        it('should validate', function (done) {
            expect(catalogueDataObjectFactory.validate()).to.be.true;
            done();
        });
    });
    describe('createHypertyDescriptorObject()', function () {

        let hypertyDescriptor;

        it('should generate HypertyDescriptor', function (done) {
            hypertyDescriptor = catalogueDataObjectFactory.createHypertyDescriptorObject(
                "525f4671-ebd8-4b35-b062-5a126bf44628", "My awesome Hyperty", "Description of Hyperty", DataObjectSourceLanguage.JAVASCRIPT_ECMA6,
                "https://example.org/my-awesome-hyperty/source", HypertyType.COMMUNICATOR, {});
            expect(hypertyDescriptor).not.to.be.empty;
            done();
        });

        it('should be of type HYPERTY', function (done) {
            expect(hypertyDescriptor.type).to.eql(CatalogueObjectType.HYPERTY);
            done();
        });

        it('testing getters/setters (name, type, messageSchema)', function (done) {
            let name = "My amazing Hyperty";
            let messageSchema = "test";
            let type = CatalogueObjectType.POLICY_ENFORCER;

            hypertyDescriptor.name = name;
            hypertyDescriptor.type = type;
            hypertyDescriptor.messageSchema = messageSchema;

            expect(hypertyDescriptor.name).to.eql(name);
            expect(hypertyDescriptor.type).to.eql(type);
            expect(hypertyDescriptor.messageSchema).to.eql(messageSchema);

            done();
        });

        it('should have valid GUID', function (done) {
            let guid = hypertyDescriptor.guid;
            expect(guidCheck(guid)).to.be.true;
            done();
        })
    });

    describe('createProtoStubDescriptorObject()', function () {
        let protocolStubDescriptor;

        it('should generate ProtocolStubDescriptor', function (done) {
            protocolStubDescriptor = catalogueDataObjectFactory.createProtoStubDescriptorObject(
                "3339515e-e457-4fe0-b780-68263ca216db", "My awesome Hyperty 2", "Description of Hyperty 2",
                DataObjectSourceLanguage.JAVASCRIPT_ECMA6, "https://example.org/my-awesome-hyperty-2/source", {}, {},
                new RuntimeConstraint());
            expect(protocolStubDescriptor).not.to.be.empty;
            done();
        });

        it('should be of type PROTOSTUB', function (done) {
            expect(protocolStubDescriptor.type).to.eql(CatalogueObjectType.PROTOSTUB);
            done();
        });

        it('should have valid GUID', function (done) {
            let guid = protocolStubDescriptor.guid;
            expect(guidCheck(guid)).to.be.true;
            done();
        })
    });

    describe('createPolicyEnforcerObject()', function () {
        let policyEnforcerDescriptor;

        it('should generate PolicyEnforcerDescriptor', function (done) {
            policyEnforcerDescriptor = catalogueDataObjectFactory.createPolicyEnforcerDescriptorObject(
                "5dc08572-56e5-4ad1-99c8-79c49578a5b0", "My awesome Hyperty 3", "Description of Hyperty 2",
                DataObjectSourceLanguage.PYTHON, "https://example.com/my-awesome-hyperty-3/source", {},
                []);
            expect(policyEnforcerDescriptor).not.to.be.empty;
            done();
        });

        it('should be of type POLICY_ENFORCER', function (done) {
            expect(policyEnforcerDescriptor.type).to.eql(CatalogueObjectType.POLICY_ENFORCER);
            done();
        });

        it('should have valid GUID', function (done) {
            let guid = policyEnforcerDescriptor.guid;
            expect(guidCheck(guid)).to.be.true;
            done();
        })
    });

    describe('createSourcePackage()', function () {
        let sourcePackage;

        it('should generate SourcePackage', function (done) {
            sourcePackage = catalogueDataObjectFactory.createSourcePackage("MyClassName", {});
            expect(sourcePackage).not.to.be.empty;
            done();
        });
    });

    describe('createCatalogueDataObject()', function () {

        let catalogueDataObject;

        it('should generate CatalogueDataObject of type HypertyDescriptor', function (done) {
            catalogueDataObject = catalogueDataObjectFactory.createCatalogueDataObject(
                "df7c7237-03e4-4547-89ca-c0c8b8d88f63", CatalogueObjectType.HYPERTY, "My awesome Hyperty 4",
                "Description of Hyperty 4", DataObjectSourceLanguage.JAVASCRIPT_ECMA6,
                "https://example.org/my-awesome-hyperty/source");
            expect(catalogueDataObject).not.to.be.empty;
            done();
        });

        it('should be of type HYPERTY', function (done) {
            expect(catalogueDataObject.type).to.eql(CatalogueObjectType.HYPERTY);
            done();
        });

        it('should have valid GUID', function (done) {
            let guid = catalogueDataObject.guid;
            expect(guidCheck(guid)).to.be.true;
            done();
        })
    });

    describe('createHypertyRuntimeDescriptorObject()', function () {
        let hypertyRuntimeDescriptor;

        it('should generate HypertyRuntimeDescriptor', function (done) {
            hypertyRuntimeDescriptor = catalogueDataObjectFactory.createHypertyRuntimeDescriptorObject(
                "b36392c3-73d4-4a63-942b-4a9c2c663eea", "My awesome Hyperty 5", "Description of Hyperty 5",
                DataObjectSourceLanguage.JAVASCRIPT_ECMA6, "https://example.org/my-awesome-hyperty-5/source", {}, {},
                {});
            expect(hypertyRuntimeDescriptor).not.to.be.empty;
            done();
        });

        it('should be of type HYPERTY_RUNTIME', function (done) {
            expect(hypertyRuntimeDescriptor.type).to.eql(CatalogueObjectType.HYPERTY_RUNTIME);
            done();
        });

        it('should have valid GUID', function (done) {
            let guid = hypertyRuntimeDescriptor.guid;
            expect(guidCheck(guid)).to.be.true;
            done();
        })
    });

    describe('createDataObjectSchema()', function () {
        let dataObjectSchema;

        it('should generate DataObjectSchema', function (done) {
            dataObjectSchema = catalogueDataObjectFactory.createDataObjectSchema(
                "b36392c3-73d4-4a63-942b-4a9c2c663eea", "My awesome Schema",
                "Description of Schema",
                DataObjectSourceLanguage.JAVASCRIPT_ECMA6, "https://example.org/my-awesome-schema/source");
            expect(dataObjectSchema).not.to.be.empty;
            done();
        });

        it('should be of type DATA_SCHEMA', function (done) {
            expect(dataObjectSchema.type).to.eql(CatalogueObjectType.DATA_SCHEMA);
            done();
        });

        it('should have valid GUID', function (done) {
            let guid = dataObjectSchema.guid;
            expect(guidCheck(guid)).to.be.true;
            done();
        })
    });

    function guidCheck(guid) {
        if (typeof guid === "undefined") return false;
        else {
            //GUID should match standard RFC4122
            var match = guid.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i);
            return match !== null && match.length === 1;
        }
    }
});

<commit_msg>chai done() not needed for sync-calls<commit_after>import CatalogueDataObjectFactory from '../src/catalogue-factory/CatalogueDataObjectFactory'
import CatalogueDataObject from '../src/catalogue-factory/CatalogueDataObject'
import RuntimeConstraint from '../src/catalogue-factory/RuntimeConstraint'
import {CatalogueObjectType} from '../src/catalogue-factory/CatalogueDataObject'
import {DataObjectSourceLanguage} from '../src/catalogue-factory/CatalogueDataObject'
import {HypertyType} from '../src/catalogue-factory/HypertyDescriptor'

import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';

let expect = chai.expect;
chai.use(chaiAsPromised);

//Testing the CatalogueDataObject-Factory
describe('CatalogueDataObjectFactory', function () {

    let catalogueDataObjectFactory;

    describe('constructor()', function () {

        it('should create a CatalogueDataObject-Factory object without error', function () {
            catalogueDataObjectFactory = new CatalogueDataObjectFactory("false", '{}');
        });

        it('should validate', function () {
            expect(catalogueDataObjectFactory.validate()).to.be.true;
        });
    });
    describe('createHypertyDescriptorObject()', function () {

        let hypertyDescriptor;

        it('should generate HypertyDescriptor', function () {
            hypertyDescriptor = catalogueDataObjectFactory.createHypertyDescriptorObject(
                "525f4671-ebd8-4b35-b062-5a126bf44628", "My awesome Hyperty", "Description of Hyperty", DataObjectSourceLanguage.JAVASCRIPT_ECMA6,
                "https://example.org/my-awesome-hyperty/source", HypertyType.COMMUNICATOR, {});
            expect(hypertyDescriptor).not.to.be.empty;
        });

        it('should be of type HYPERTY', function () {
            expect(hypertyDescriptor.type).to.eql(CatalogueObjectType.HYPERTY);
        });

        it('testing getters/setters (name, type, messageSchema)', function () {
            let name = "My amazing Hyperty";
            let messageSchema = "test";
            let type = CatalogueObjectType.POLICY_ENFORCER;

            hypertyDescriptor.name = name;
            hypertyDescriptor.type = type;
            hypertyDescriptor.messageSchema = messageSchema;

            expect(hypertyDescriptor.name).to.eql(name);
            expect(hypertyDescriptor.type).to.eql(type);
            expect(hypertyDescriptor.messageSchema).to.eql(messageSchema);
        });

        it('should have valid GUID', function () {
            let guid = hypertyDescriptor.guid;
            expect(guidCheck(guid)).to.be.true;
        })
    });

    describe('createProtoStubDescriptorObject()', function () {
        let protocolStubDescriptor;

        it('should generate ProtocolStubDescriptor', function () {
            protocolStubDescriptor = catalogueDataObjectFactory.createProtoStubDescriptorObject(
                "3339515e-e457-4fe0-b780-68263ca216db", "My awesome Hyperty 2", "Description of Hyperty 2",
                DataObjectSourceLanguage.JAVASCRIPT_ECMA6, "https://example.org/my-awesome-hyperty-2/source", {}, {},
                new RuntimeConstraint());
            expect(protocolStubDescriptor).not.to.be.empty;
        });

        it('should be of type PROTOSTUB', function () {
            expect(protocolStubDescriptor.type).to.eql(CatalogueObjectType.PROTOSTUB);
        });

        it('should have valid GUID', function () {
            let guid = protocolStubDescriptor.guid;
            expect(guidCheck(guid)).to.be.true;
        })
    });

    describe('createPolicyEnforcerObject()', function () {
        let policyEnforcerDescriptor;

        it('should generate PolicyEnforcerDescriptor', function () {
            policyEnforcerDescriptor = catalogueDataObjectFactory.createPolicyEnforcerDescriptorObject(
                "5dc08572-56e5-4ad1-99c8-79c49578a5b0", "My awesome Hyperty 3", "Description of Hyperty 2",
                DataObjectSourceLanguage.PYTHON, "https://example.com/my-awesome-hyperty-3/source", {},
                []);
            expect(policyEnforcerDescriptor).not.to.be.empty;
        });

        it('should be of type POLICY_ENFORCER', function () {
            expect(policyEnforcerDescriptor.type).to.eql(CatalogueObjectType.POLICY_ENFORCER);
        });

        it('should have valid GUID', function () {
            let guid = policyEnforcerDescriptor.guid;
            expect(guidCheck(guid)).to.be.true;
        })
    });

    describe('createSourcePackage()', function () {
        let sourcePackage;

        it('should generate SourcePackage', function () {
            sourcePackage = catalogueDataObjectFactory.createSourcePackage("MyClassName", {});
            expect(sourcePackage).not.to.be.empty;
        });
    });

    describe('createCatalogueDataObject()', function () {

        let catalogueDataObject;

        it('should generate CatalogueDataObject of type HypertyDescriptor', function () {
            catalogueDataObject = catalogueDataObjectFactory.createCatalogueDataObject(
                "df7c7237-03e4-4547-89ca-c0c8b8d88f63", CatalogueObjectType.HYPERTY, "My awesome Hyperty 4",
                "Description of Hyperty 4", DataObjectSourceLanguage.JAVASCRIPT_ECMA6,
                "https://example.org/my-awesome-hyperty/source");
            expect(catalogueDataObject).not.to.be.empty;
        });

        it('should be of type HYPERTY', function () {
            expect(catalogueDataObject.type).to.eql(CatalogueObjectType.HYPERTY);
        });

        it('should have valid GUID', function () {
            let guid = catalogueDataObject.guid;
            expect(guidCheck(guid)).to.be.true;
        })
    });

    describe('createHypertyRuntimeDescriptorObject()', function () {
        let hypertyRuntimeDescriptor;

        it('should generate HypertyRuntimeDescriptor', function () {
            hypertyRuntimeDescriptor = catalogueDataObjectFactory.createHypertyRuntimeDescriptorObject(
                "b36392c3-73d4-4a63-942b-4a9c2c663eea", "My awesome Hyperty 5", "Description of Hyperty 5",
                DataObjectSourceLanguage.JAVASCRIPT_ECMA6, "https://example.org/my-awesome-hyperty-5/source", {}, {},
                {});
            expect(hypertyRuntimeDescriptor).not.to.be.empty;
        });

        it('should be of type HYPERTY_RUNTIME', function () {
            expect(hypertyRuntimeDescriptor.type).to.eql(CatalogueObjectType.HYPERTY_RUNTIME);
        });

        it('should have valid GUID', function () {
            let guid = hypertyRuntimeDescriptor.guid;
            expect(guidCheck(guid)).to.be.true;
        })
    });

    describe('createDataObjectSchema()', function () {
        let dataObjectSchema;

        it('should generate DataObjectSchema', function () {
            dataObjectSchema = catalogueDataObjectFactory.createDataObjectSchema(
                "b36392c3-73d4-4a63-942b-4a9c2c663eea", "My awesome Schema",
                "Description of Schema",
                DataObjectSourceLanguage.JAVASCRIPT_ECMA6, "https://example.org/my-awesome-schema/source");
            expect(dataObjectSchema).not.to.be.empty;
        });

        it('should be of type DATA_SCHEMA', function () {
            expect(dataObjectSchema.type).to.eql(CatalogueObjectType.DATA_SCHEMA);
        });

        it('should have valid GUID', function () {
            let guid = dataObjectSchema.guid;
            expect(guidCheck(guid)).to.be.true;
        })
    });

    function guidCheck(guid) {
        if (typeof guid === "undefined") return false;
        else {
            //GUID should match standard RFC4122
            var match = guid.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i);
            return match !== null && match.length === 1;
        }
    }
});

<|endoftext|>