<commit_before>'use strict';

angular.module('classBrowserUHApp.class', ['ngRoute']).
config(['$routeProvider', function($routeProvider) {
    $routeProvider.when('/class', {
        templateUrl: 'views/class/class.html',
        controller: 'ClassCtrl'
    });
}]).
controller('ClassCtrl', ['$scope', '$http', function ($scope, $http) {
    $scope.selectedCountLimit = 'count > 3';
    $scope.rowCollection = [];

    $scope.departments = {
        availableOptions: []
    };

    var populateDepartments = function() {
        var url = $scope.apiUrl + '/department';
        $http.get(url)
            .success(function (data) {
                console.log("Retrieved " + data.numberOfRows + " departments.");
                console.log(data);
                $scope.departments.availableOptions = data.result;
            })
            .error(function (data) {
                alert("Unable to retrieve the data.");
            })
    };

    populateDepartments();

    $scope.creditHours = {
        availableOptions: [
            {creditHours: 1},
            {creditHours: 1.5},
            {creditHours: 2},
            {creditHours: 3},
            {creditHours: 4},
            {creditHours: 5},
            {creditHours: 6},
            {creditHours: 7},
            {creditHours: 8},
            {creditHours: 9},
            {creditHours: 10}
        ]
    };

    $scope.coreCategories = {
        availableOptions: [
            {categoryNumber: 1, categoryName: "Communication"},
            {categoryNumber: 2, categoryName : "Mathematics"},
            {categoryNumber: 3, categoryName : "Life and Physical Sciences"},
            {categoryNumber: 4, categoryName : "Language, Philosophy & Culture"},
            {categoryNumber: 5, categoryName : "Creative Arts"},
            {categoryNumber: 6, categoryName : "American History"},
            {categoryNumber: 7, categoryName : "Government/Political Science"},
            {categoryNumber: 8, categoryName : "Social & Behavioral Sciences"},
            {categoryNumber: 9, categoryName : "Mathematics/Reasoning"},
            {categoryNumber: 10, categoryName : "Writing in the Disciplines"}
        ]
    };

    var generateMessage = function(model, type, objToPluck) {
        if(model == undefined || model.length == 0) {
            return "";
        }
        else {
            return " " + type + ": " + _.pluck(model, objToPluck).join(', ') + "
";
        }
    };

    $scope.populateClasses = function(){
        $scope.rowCollection = [];
        var apiUrl = buildApiUrlsFromModel($scope.departmentModel, $scope.creditHourModel, $scope.coreModel);
        console.log("Populating Classes...");

        console.log("Retrieved api URLs: " + apiUrl);

        $scope.numberOfRows = 0;
        for(var i = 0; i < apiUrl.length; i++) {
            console.log("Got URL: " + apiUrl[i]);
            $http
                .get(apiUrl[i])
                .success(function (data) {
                    $scope.numberOfRows += data.numberOfRows;
                    $scope.rowCollection = $scope.rowCollection.concat(data.result);
                    populateFields();
                })
                .error(function (data) {
                    alert("Unable to retrieve the data.");
                });
        }
    };

    var populateFields = function(){
        $scope.hasNoResults = false;
        console.log("In populate fields");
        console.log("Row Collection = " + $scope.rowCollection);
        if($scope.rowCollection.length > 0) {
            $scope.showDiv = true;
            if($scope.numberOfRows == 1) {
                $scope.numberOfRowsMessage = "Retrieved " + $scope.numberOfRows + " class.";
            }
            else {
                $scope.numberOfRowsMessage = "Retrieved " + $scope.numberOfRows + " classes.";
            }

            if([$scope.departmentModel, $scope.creditHourModel, $scope.coreModel].allParametersUndefinedOrNull()) {
                $scope.parametersMessage = "No parameters were chosen, so all classes have been retrieved.";
            }
            else {
                $scope.parametersMessage = "";
                $scope.subjectMessage = generateMessage($scope.departmentModel, 'Subjects', 'departmentFullName');
                $scope.creditHoursMessage = generateMessage($scope.creditHourModel, 'Credit Hours', 'creditHours');
                $scope.coreMessage = generateMessage($scope.coreModel, 'Core Categories', 'categoryName');
                $scope.parametersMessage = $scope.subjectMessage +
                $scope.creditHoursMessage +
                $scope.coreMessage;
            }
        }
        else {
            $scope.hasNoResults = true;
        }
    };

    var isArrayIsUndefinedOrNull = function(arr) {
        return !(_.isUndefined(arr) || _.isNull(arr) || _.isEmpty(arr));
    };

    Array.prototype.allParametersUndefinedOrNull = function() {
        for(var i = 0; i < this.length; i++) {
            if(isArrayIsUndefinedOrNull(this[i])) {
                return false;
            }
        }
        return true;
    };

    var buildApiUrlsFromModel = function(department, creditHour, core) {
        console.log("Building API URL...");
        var baseUrl = $scope.apiUrl + '/information?';
        var allParametersFromScope = [department, creditHour, core];

        if(allParametersFromScope.allParametersUndefinedOrNull()) {
            console.log("All parameters are empty...");
            return [baseUrl];
        }

        console.log("User has selected some categories. Preparing API URL.");
        department = _.pluck(department, 'departmentName');
        creditHour = _.pluck(creditHour, 'creditHours');
        core = _.pluck(core, 'categoryNumber');

        console.log("dept " + department);
        console.log("crh " + creditHour);
        console.log("core " + core);

        var expandArrayValues = function(arr, parameter) {
            arr.forEach(function (part, index, arr) {
                arr[index] = parameter + "=" + part;
            });
        };

        if(isArrayIsUndefinedOrNull(department)) {
            expandArrayValues(department, 'department');
        }
        if(isArrayIsUndefinedOrNull(creditHour)) {
            expandArrayValues(creditHour, 'credit-hours');
        }
        if(isArrayIsUndefinedOrNull(core)) {
            expandArrayValues(core, 'core');
        }

        var appendApiUrl = function(arr) {
            arr.forEach(function (part, index, arr) {
                arr[index] = baseUrl + part;
            });
        };

        var allParameters = [department,creditHour,core].filter(nonEmpty).reduce(productAdd);

        appendApiUrl(allParameters);

        function nonEmpty(xs) {
            return xs.length > 0;
        }

        function productAdd(xs, ys) {
            return product(add, xs, ys);
        }

        function add(a, b) {
            return a + "&" + b;
        }

        function product(f, xs, ys) {
            var zs = [];

            var m = xs.length;
            var n = ys.length;

            for (var i = 0; i < m; i++) {
                var x = xs[i];

                for (var j = 0; j < n; j++)
                    zs.push(f(x, ys[j]));
            }

            return zs;
        }

        console.log("Retrieved parameters from cartesian product: " + allParameters);
        return allParameters;
    };

    $scope.goBack = function() {
        console.log('going back');
        $scope.showDiv = false;
    };

    $scope.clearForms = function() {
        $scope.hasNoResults = false;
        console.log('clearing forms...');
        console.log($scope.departmentModel);
        console.log($scope.creditHourModel);
        console.log($scope.coreModel);
        $scope.departmentModel = undefined;
        $scope.creditHourModel = undefined;
        $scope.coreModel = undefined;
        $scope.parametersMessage = undefined;
    };

}]);<commit_msg>Refactored results message and made rowCollection undefined when the clear form button is hit.<commit_after>'use strict';

angular.module('classBrowserUHApp.class', ['ngRoute']).
config(['$routeProvider', function($routeProvider) {
    $routeProvider.when('/class', {
        templateUrl: 'views/class/class.html',
        controller: 'ClassCtrl'
    });
}]).
controller('ClassCtrl', ['$scope', '$http', function ($scope, $http) {
    $scope.selectedCountLimit = 'count > 3';
    $scope.rowCollection = [];

    $scope.departments = {
        availableOptions: []
    };

    var populateDepartments = function() {
        var url = $scope.apiUrl + '/department';
        $http.get(url)
            .success(function (data) {
                console.log("Retrieved " + data.numberOfRows + " departments.");
                console.log(data);
                $scope.departments.availableOptions = data.result;
            })
            .error(function (data) {
                alert("Unable to retrieve the data.");
            })
    };

    populateDepartments();

    $scope.creditHours = {
        availableOptions: [
            {creditHours: 1},
            {creditHours: 1.5},
            {creditHours: 2},
            {creditHours: 3},
            {creditHours: 4},
            {creditHours: 5},
            {creditHours: 6},
            {creditHours: 7},
            {creditHours: 8},
            {creditHours: 9},
            {creditHours: 10}
        ]
    };

    $scope.coreCategories = {
        availableOptions: [
            {categoryNumber: 1, categoryName: "Communication"},
            {categoryNumber: 2, categoryName : "Mathematics"},
            {categoryNumber: 3, categoryName : "Life and Physical Sciences"},
            {categoryNumber: 4, categoryName : "Language, Philosophy & Culture"},
            {categoryNumber: 5, categoryName : "Creative Arts"},
            {categoryNumber: 6, categoryName : "American History"},
            {categoryNumber: 7, categoryName : "Government/Political Science"},
            {categoryNumber: 8, categoryName : "Social & Behavioral Sciences"},
            {categoryNumber: 9, categoryName : "Mathematics/Reasoning"},
            {categoryNumber: 10, categoryName : "Writing in the Disciplines"}
        ]
    };

    var generateMessage = function(model, type, objToPluck) {
        if(model == undefined || model.length == 0) {
            return "";
        }
        else {
            return " " + type + ": " + _.pluck(model, objToPluck).join(', ') + "
";
        }
    };

    $scope.populateClasses = function(){
        $scope.rowCollection = [];
        var apiUrl = buildApiUrlsFromModel($scope.departmentModel, $scope.creditHourModel, $scope.coreModel);
        console.log("Populating Classes...");

        console.log("Retrieved api URLs: " + apiUrl);

        $scope.numberOfRows = 0;
        for(var i = 0; i < apiUrl.length; i++) {
            console.log("Got URL: " + apiUrl[i]);
            $http
                .get(apiUrl[i])
                .success(function (data) {
                    $scope.numberOfRows += data.numberOfRows;
                    $scope.rowCollection = $scope.rowCollection.concat(data.result);
                    populateFields();
                })
                .error(function (data) {
                    alert("Unable to retrieve the data.");
                });
        }
    };

    var populateFields = function(){
        $scope.hasNoResults = false;
        console.log("In populate fields");
        console.log("Row Collection = " + $scope.rowCollection);
        if($scope.rowCollection.length > 0) {
            $scope.showDiv = true;

            $scope.numberOfRowsMessage = "Retrieved " + $scope.numberOfRows + " class";
            $scope.numberOfRowsMessage += $scope.numberOfRows == 1 ? " ." : "es.";

            if([$scope.departmentModel, $scope.creditHourModel, $scope.coreModel].allParametersUndefinedOrNull()) {
                $scope.parametersMessage = "No parameters were chosen, so all classes have been retrieved.";
            }
            else {
                $scope.parametersMessage = "";
                $scope.subjectMessage = generateMessage($scope.departmentModel, 'Subjects', 'departmentFullName');
                $scope.creditHoursMessage = generateMessage($scope.creditHourModel, 'Credit Hours', 'creditHours');
                $scope.coreMessage = generateMessage($scope.coreModel, 'Core Categories', 'categoryName');
                $scope.parametersMessage = $scope.subjectMessage +
                $scope.creditHoursMessage +
                $scope.coreMessage;
            }
        }
        else {
            $scope.hasNoResults = true;
        }
    };

    var isArrayIsUndefinedOrNull = function(arr) {
        return !(_.isUndefined(arr) || _.isNull(arr) || _.isEmpty(arr));
    };

    Array.prototype.allParametersUndefinedOrNull = function() {
        for(var i = 0; i < this.length; i++) {
            if(isArrayIsUndefinedOrNull(this[i])) {
                return false;
            }
        }
        return true;
    };

    var buildApiUrlsFromModel = function(department, creditHour, core) {
        console.log("Building API URL...");
        var baseUrl = $scope.apiUrl + '/information?';
        var allParametersFromScope = [department, creditHour, core];

        if(allParametersFromScope.allParametersUndefinedOrNull()) {
            console.log("All parameters are empty...");
            return [baseUrl];
        }

        console.log("User has selected some categories. Preparing API URL.");
        department = _.pluck(department, 'departmentName');
        creditHour = _.pluck(creditHour, 'creditHours');
        core = _.pluck(core, 'categoryNumber');

        console.log("dept " + department);
        console.log("crh " + creditHour);
        console.log("core " + core);

        var expandArrayValues = function(arr, parameter) {
            arr.forEach(function (part, index, arr) {
                arr[index] = parameter + "=" + part;
            });
        };

        if(isArrayIsUndefinedOrNull(department)) {
            expandArrayValues(department, 'department');
        }
        if(isArrayIsUndefinedOrNull(creditHour)) {
            expandArrayValues(creditHour, 'credit-hours');
        }
        if(isArrayIsUndefinedOrNull(core)) {
            expandArrayValues(core, 'core');
        }

        var appendApiUrl = function(arr) {
            arr.forEach(function (part, index, arr) {
                arr[index] = baseUrl + part;
            });
        };

        var allParameters = [department,creditHour,core].filter(nonEmpty).reduce(productAdd);

        appendApiUrl(allParameters);

        function nonEmpty(xs) {
            return xs.length > 0;
        }

        function productAdd(xs, ys) {
            return product(add, xs, ys);
        }

        function add(a, b) {
            return a + "&" + b;
        }

        function product(f, xs, ys) {
            var zs = [];

            var m = xs.length;
            var n = ys.length;

            for (var i = 0; i < m; i++) {
                var x = xs[i];

                for (var j = 0; j < n; j++)
                    zs.push(f(x, ys[j]));
            }

            return zs;
        }

        console.log("Retrieved parameters from cartesian product: " + allParameters);
        return allParameters;
    };

    $scope.goBack = function() {
        console.log('going back');
        $scope.showDiv = false;
    };

    $scope.clearForms = function() {
        $scope.hasNoResults = false;
        console.log('clearing forms...');
        console.log($scope.departmentModel);
        console.log($scope.creditHourModel);
        console.log($scope.coreModel);
        $scope.departmentModel = undefined;
        $scope.creditHourModel = undefined;
        $scope.coreModel = undefined;
        $scope.parametersMessage = undefined;
        $scope.rowCollection = undefined;
    };

}]);<|endoftext|>


<commit_before>angular.module('cliffhanger.issue', ['ngRoute']).config(['$routeProvider', function ($routeProvider) {
    $routeProvider.when('/issue/:threadId', {
        templateUrl: 'views/issue/issue.html',
        controller: 'IssueCtrl',
        activetab: 'messageboard'
    });
}]).controller('IssueCtrl', function ($rootScope, $log, $scope, $q, issueService, $routeParams) {
    //list of alerts
    $scope.alerts = [];
    $scope.closeAlert = function (index) {
        $scope.alerts.splice(index, 1);
    };
    //TODO load issue/comment data
    //test issue data
    $scope.issue = {
        /*
            subject: "Can't load table testHiveTable"
            , opener: {
                username: "dbatt"
                , role: {
                    roleID: "DEVELOPER"
                }
            }
            , createDate: new Date()
            , open: true
            */
    };
    //test comment data
    $scope.comments = [
        /*
        {
            commentBy: {
                username: "dbatt"
                , role: {
                    roleID: "DEVELOPER"
                }
            }
            , body: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus est leo, congue eu neque id, mattis lacinia metus. Donec tincidunt porta massa. Nunc sed lacus elementum, vulputate enim ut, bibendum tortor. Praesent et est lacus. Quisque vulputate nunc metus, sit amet porttitor ligula tempor sed. Morbi varius tortor in fermentum sagittis. Mauris laoreet scelerisque convallis. Nulla hendrerit mi quis nisi sagittis accumsan. Integer ac cursus risus. Sed tellus ante, feugiat eu enim nec, eleifend fermentum massa. Praesent lorem augue, vehicula vitae hendrerit vel, efficitur et eros. Phasellus aliquet ut purus a cursus. Nullam imperdiet sem in mattis tempor. Integer vel eros eu quam hendrerit consequat."
            , createDate: new Date()
        }
        , {
            commentBy: {
                username: "heather"
                , role: {
                    roleID: "ANALYST"
                }
            }
            , body: "Pellentesque vestibulum sem sit amet lacus suscipit, non porttitor nibh egestas. Maecenas lobortis mattis blandit. Pellentesque id dui nisi. Sed lobortis dolor sed risus eleifend, sit amet finibus leo faucibus. Etiam sed ex dolor. Sed urna risus, congue id tellus et, ultricies convallis tellus. Fusce convallis felis non tristique varius. Etiam hendrerit, libero imperdiet mattis lobortis, mi diam viverra turpis, sed luctus nibh erat faucibus odio."
            , createDate: new Date()
        }
        , {
            commentBy: {
                username: "colton"
                , role: {
                    roleID: "ADMIN"
                }
            }
            , body: "Curabitur ac neque finibus, vulputate libero eu, laoreet orci. Fusce in eleifend tellus. Quisque nec condimentum magna. In molestie facilisis nisl, et convallis enim hendrerit sed. Donec id nulla eget mi ultrices finibus sit amet at sem. Duis scelerisque neque sit amet nisl lobortis tincidunt. Morbi viverra dui eget dapibus lacinia. Praesent convallis nunc vel nisi mattis egestas. Aliquam pulvinar quam porta libero laoreet pharetra. Duis ultrices laoreet purus. Vivamus congue dolor at congue interdum."
            , createDate: new Date()
        }
        , {
            commentBy: {
                username: "heather"
                , role: {
                    roleID: "ANALYST"
                }
            }
            , body: "Nullam molestie sapien a risus tempor fermentum. Sed tempus maximus orci, porttitor elementum felis sodales sit amet. Quisque pulvinar hendrerit ipsum, in porta lacus gravida vitae."
            , createDate: new Date()
        }
        , {
            commentBy: {
                username: "dbatt"
                , role: {
                    roleID: "DEVELOPER"
                }
            }
            , body: "Phasellus ut libero est. Nullam viverra ullamcorper nisi, nec tempus mauris pulvinar nec. Vestibulum cursus, tellus ut consequat porttitor, nibh ex auctor est, non varius ex nisi maximus mauris. Aliquam bibendum nisl vestibulum massa commodo aliquet. Etiam ex nunc, finibus nec ornare non, feugiat quis massa. Interdum et malesuada fames ac ante ipsum primis in faucibus. Duis sit amet vestibulum leo, eu blandit erat."
            , createDate: new Date()
        }
        */
    ];
    $scope.loadIssue = function () {
        $log.info('user', $rootScope.user);
        var threadId = $routeParams.threadId;
        //load issue metadata
        issueService.getIssue(threadId).then( //success
            function (response) {
                if (response.status == 'Success') {
                    $scope.issue = response.data;
                }
                //error
                else {
                    $scope.alerts.push({
                        msg: response.data,
                        type: "danger"
                    });
                }
            }, //error
            function (error) {
                $scope.alerts.push({
                    msg: "Failed to connect to server.",
                    type: "danger"
                });
            });
        //load all comments by threadId
        issueService.getComments(threadId).then(
            //success
            function (response) {
                if (response.status == 'Success') {
                    $scope.comments = response.data;
                }
                //error
                else {
                    $scope.alerts.push({
                        msg: response.data,
                        type: "danger"
                    });
                }
            }, //error
            function (error) {
                $scope.alerts.push({
                    msg: "Failed to connect to server.",
                    type: "danger"
                });
            });
    }
    $scope.loadIssue();
    $scope.roleStyle = function (user) {
        $log.debug('role user', user);
        if (user.roles[0].authority == "ROLE_DEVELOPER") return "text-success";
        else if (user.roles[0].authority == "ROLE_ANALYST") return "text-primary";
        else return "text-muted";
    }
    $scope.toggleOpen = function () {
            //        $scope.issue.open = false; //for testing only
            issueService.toggleOpen($routeParams.threadId, $rootScope.user.username).then(
                //success
                function (response) {
                    if (response.status == 'Success') {
                        //reload issue
                        $scope.loadIssue();
                    }
                    //error
                    else {
                        $scope.alerts.push({
                            msg: response.data,
                            type: "danger"
                        });
                    }
                }, //error
                function (error) {
                    $scope.alerts.push({
                        msg: "Failed to connect to server.",
                        type: "danger"
                    });
                });
        }
        //post a new comment
    $scope.postComment = function () {
        var newComment = {
            threadId: $routeParams.threadId,
            body: $scope.newComment,
            userId: $rootScope.user.username
        }
        issueService.postComment(newComment).then(
            //success
            function (response) {
                if (response.status == 'Success') {
                    $scope.comments.push(response.data);
                }
                //error
                else {
                    $scope.alerts.push({
                        msg: response.data,
                        type: "danger"
                    });
                }
            }, //error
            function (error) {
                $scope.alerts.push({
                    msg: "Failed to connect to server.",
                    type: "danger"
                });
            });
    }

});
<commit_msg>clear textbox after comment<commit_after>angular.module('cliffhanger.issue', ['ngRoute']).config(['$routeProvider', function ($routeProvider) {
    $routeProvider.when('/issue/:threadId', {
        templateUrl: 'views/issue/issue.html',
        controller: 'IssueCtrl',
        activetab: 'messageboard'
    });
}]).controller('IssueCtrl', function ($rootScope, $log, $scope, $q, issueService, $routeParams) {
    //list of alerts
    $scope.alerts = [];
    $scope.closeAlert = function (index) {
        $scope.alerts.splice(index, 1);
    };
    //TODO load issue/comment data
    //test issue data
    $scope.issue = {
        /*
            subject: "Can't load table testHiveTable"
            , opener: {
                username: "dbatt"
                , role: {
                    roleID: "DEVELOPER"
                }
            }
            , createDate: new Date()
            , open: true
            */
    };
    //test comment data
    $scope.comments = [
        /*
        {
            commentBy: {
                username: "dbatt"
                , role: {
                    roleID: "DEVELOPER"
                }
            }
            , body: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus est leo, congue eu neque id, mattis lacinia metus. Donec tincidunt porta massa. Nunc sed lacus elementum, vulputate enim ut, bibendum tortor. Praesent et est lacus. Quisque vulputate nunc metus, sit amet porttitor ligula tempor sed. Morbi varius tortor in fermentum sagittis. Mauris laoreet scelerisque convallis. Nulla hendrerit mi quis nisi sagittis accumsan. Integer ac cursus risus. Sed tellus ante, feugiat eu enim nec, eleifend fermentum massa. Praesent lorem augue, vehicula vitae hendrerit vel, efficitur et eros. Phasellus aliquet ut purus a cursus. Nullam imperdiet sem in mattis tempor. Integer vel eros eu quam hendrerit consequat."
            , createDate: new Date()
        }
        , {
            commentBy: {
                username: "heather"
                , role: {
                    roleID: "ANALYST"
                }
            }
            , body: "Pellentesque vestibulum sem sit amet lacus suscipit, non porttitor nibh egestas. Maecenas lobortis mattis blandit. Pellentesque id dui nisi. Sed lobortis dolor sed risus eleifend, sit amet finibus leo faucibus. Etiam sed ex dolor. Sed urna risus, congue id tellus et, ultricies convallis tellus. Fusce convallis felis non tristique varius. Etiam hendrerit, libero imperdiet mattis lobortis, mi diam viverra turpis, sed luctus nibh erat faucibus odio."
            , createDate: new Date()
        }
        , {
            commentBy: {
                username: "colton"
                , role: {
                    roleID: "ADMIN"
                }
            }
            , body: "Curabitur ac neque finibus, vulputate libero eu, laoreet orci. Fusce in eleifend tellus. Quisque nec condimentum magna. In molestie facilisis nisl, et convallis enim hendrerit sed. Donec id nulla eget mi ultrices finibus sit amet at sem. Duis scelerisque neque sit amet nisl lobortis tincidunt. Morbi viverra dui eget dapibus lacinia. Praesent convallis nunc vel nisi mattis egestas. Aliquam pulvinar quam porta libero laoreet pharetra. Duis ultrices laoreet purus. Vivamus congue dolor at congue interdum."
            , createDate: new Date()
        }
        , {
            commentBy: {
                username: "heather"
                , role: {
                    roleID: "ANALYST"
                }
            }
            , body: "Nullam molestie sapien a risus tempor fermentum. Sed tempus maximus orci, porttitor elementum felis sodales sit amet. Quisque pulvinar hendrerit ipsum, in porta lacus gravida vitae."
            , createDate: new Date()
        }
        , {
            commentBy: {
                username: "dbatt"
                , role: {
                    roleID: "DEVELOPER"
                }
            }
            , body: "Phasellus ut libero est. Nullam viverra ullamcorper nisi, nec tempus mauris pulvinar nec. Vestibulum cursus, tellus ut consequat porttitor, nibh ex auctor est, non varius ex nisi maximus mauris. Aliquam bibendum nisl vestibulum massa commodo aliquet. Etiam ex nunc, finibus nec ornare non, feugiat quis massa. Interdum et malesuada fames ac ante ipsum primis in faucibus. Duis sit amet vestibulum leo, eu blandit erat."
            , createDate: new Date()
        }
        */
    ];
    $scope.loadIssue = function () {
        $log.info('user', $rootScope.user);
        var threadId = $routeParams.threadId;
        //load issue metadata
        issueService.getIssue(threadId).then( //success
            function (response) {
                if (response.status == 'Success') {
                    $scope.issue = response.data;
                }
                //error
                else {
                    $scope.alerts.push({
                        msg: response.data,
                        type: "danger"
                    });
                }
            }, //error
            function (error) {
                $scope.alerts.push({
                    msg: "Failed to connect to server.",
                    type: "danger"
                });
            });
        //load all comments by threadId
        issueService.getComments(threadId).then(
            //success
            function (response) {
                if (response.status == 'Success') {
                    $scope.comments = response.data;
                }
                //error
                else {
                    $scope.alerts.push({
                        msg: response.data,
                        type: "danger"
                    });
                }
            }, //error
            function (error) {
                $scope.alerts.push({
                    msg: "Failed to connect to server.",
                    type: "danger"
                });
            });
    }
    $scope.loadIssue();
    $scope.roleStyle = function (user) {
        $log.debug('role user', user);
        if (user.roles[0].authority == "ROLE_DEVELOPER") return "text-success";
        else if (user.roles[0].authority == "ROLE_ANALYST") return "text-primary";
        else return "text-muted";
    }
    $scope.toggleOpen = function () {
            //        $scope.issue.open = false; //for testing only
            issueService.toggleOpen($routeParams.threadId, $rootScope.user.username).then(
                //success
                function (response) {
                    if (response.status == 'Success') {
                        //reload issue
                        $scope.loadIssue();
                    }
                    //error
                    else {
                        $scope.alerts.push({
                            msg: response.data,
                            type: "danger"
                        });
                    }
                }, //error
                function (error) {
                    $scope.alerts.push({
                        msg: "Failed to connect to server.",
                        type: "danger"
                    });
                });
        }
        //post a new comment
    $scope.postComment = function () {
        var newComment = {
            threadId: $routeParams.threadId,
            body: $scope.newComment,
            userId: $rootScope.user.username
        }
        issueService.postComment(newComment).then(
            //success
            function (response) {
                if (response.status == 'Success') {
                    $scope.comments.push(response.data);
                    $scope.newComment = "";
                }
                //error
                else {
                    $scope.alerts.push({
                        msg: response.data,
                        type: "danger"
                    });
                }
            }, //error
            function (error) {
                $scope.alerts.push({
                    msg: "Failed to connect to server.",
                    type: "danger"
                });
            });
    }

});
<|endoftext|>


<commit_before>var FileActions={
	actions:{},
	defaults:{},
	icons:{},
	currentFile:null,
	register:function(mime,name,permissions,icon,action){
		if(!FileActions.actions[mime]){
			FileActions.actions[mime]={};
		}
		if (!FileActions.actions[mime][name]) {
			FileActions.actions[mime][name] = {};
		}
		FileActions.actions[mime][name]['action'] = action;
		FileActions.actions[mime][name]['permissions'] = permissions;
		FileActions.icons[name]=icon;
	},
	setDefault:function(mime,name){
		FileActions.defaults[mime]=name;
	},
	get:function(mime,type,permissions){
		var actions={};
		if(FileActions.actions.all){
			actions=$.extend( actions, FileActions.actions.all );
		}
		if(mime){
			if(FileActions.actions[mime]){
				actions=$.extend( actions, FileActions.actions[mime] );
			}
			var mimePart=mime.substr(0,mime.indexOf('/'));
			if(FileActions.actions[mimePart]){
				actions=$.extend( actions, FileActions.actions[mimePart] );
			}
		}
		if(type){//type is 'dir' or 'file'
			if(FileActions.actions[type]){
				actions=$.extend( actions, FileActions.actions[type] );
			}
		}
		var filteredActions = {};
		$.each(actions, function(name, action) {
			if (action.permissions & permissions) {
				filteredActions[name] = action.action;
			}
		});
		return filteredActions;
	},
	getDefault:function(mime,type,permissions){
		if(mime){
			var mimePart=mime.substr(0,mime.indexOf('/'));
		}
		var name=false;
		if(mime && FileActions.defaults[mime]){
			name=FileActions.defaults[mime];
		}else if(mime && FileActions.defaults[mimePart]){
			name=FileActions.defaults[mimePart];
		}else if(type && FileActions.defaults[type]){
			name=FileActions.defaults[type];
		}else{
			name=FileActions.defaults.all;
		}
		var actions=this.get(mime,type,permissions);
		return actions[name];
	},
	display:function(parent){
		FileActions.currentFile=parent;
		$('#fileList span.fileactions, #fileList td.date a.action').remove();
		var actions=FileActions.get(FileActions.getCurrentMimeType(),FileActions.getCurrentType(), FileActions.getCurrentPermissions());
		var file=FileActions.getCurrentFile();
		if($('tr').filterAttr('data-file',file).data('renaming')){
			return;
		}
		parent.children('a.name').append('');
		var defaultAction=FileActions.getDefault(FileActions.getCurrentMimeType(),FileActions.getCurrentType(), FileActions.getCurrentPermissions());
		for(name in actions){
			// NOTE: Temporary fix to prevent rename action in root of Shared directory
			if (name == 'Rename' && $('#dir').val() == '/Shared') {
				continue;
			}
			if((name=='Download' || actions[name]!=defaultAction) && name!='Delete'){
				var img=FileActions.icons[name];
				if(img.call){
					img=img(file);
				}
				var html='';
				if(img) { html+=' '; }
				html += t('files', name) +'';
				var element=$(html);
				element.data('action',name);
				element.click(function(event){
					event.stopPropagation();
					event.preventDefault();
					var action=actions[$(this).data('action')];
					var currentFile=FileActions.getCurrentFile();
					FileActions.hide();
					action(currentFile);
				});
				element.hide();
				parent.find('a.name>span.fileactions').append(element);
			}
		}
		if(actions['Delete']){
			var img=FileActions.icons['Delete'];
			if(img.call){
				img=img(file);
			}
			// NOTE: Temporary fix to allow unsharing of files in root of Shared folder
			if ($('#dir').val() == '/Shared') {
				var html = '';
			} else {
				var html='';
			}
			var element=$(html);
			if(img){
				element.append($(''));
			}
			element.data('action','Delete');
			element.click(function(event){
				event.stopPropagation();
				event.preventDefault();
				var action=actions[$(this).data('action')];
				var currentFile=FileActions.getCurrentFile();
				FileActions.hide();
				action(currentFile);
			});
			element.hide();
			parent.parent().children().last().append(element);
		}
		$('#fileList .action').css('-o-transition-property','none');//temporarly disable
		$('#fileList .action').fadeIn(200,function(){
			$('#fileList .action').css('-o-transition-property','opacity');
		});
		return false;
	},
	hide:function(){
		$('#fileList span.fileactions, #fileList td.date a.action').fadeOut(200,function(){
			$(this).remove();
		});
	},
	getCurrentFile:function(){
		return FileActions.currentFile.parent().attr('data-file');
	},
	getCurrentMimeType:function(){
		return FileActions.currentFile.parent().attr('data-mime');
	},
	getCurrentType:function(){
		return FileActions.currentFile.parent().attr('data-type');
	},
	getCurrentPermissions:function() {
		return FileActions.currentFile.parent().data('permissions');
	}
};

$(document).ready(function(){
	if($('#allowZipDownload').val() == 1){
		var downloadScope = 'all';
	} else {
		var downloadScope = 'file';
	}
	FileActions.register(downloadScope,'Download', OC.PERMISSION_READ, function(){return OC.imagePath('core','actions/download');},function(filename){
		window.location=OC.filePath('files', 'ajax', 'download.php') + '?files='+encodeURIComponent(filename)+'&dir='+encodeURIComponent($('#dir').val());
	});
});

FileActions.register('all','Delete', OC.PERMISSION_DELETE, function(){return OC.imagePath('core','actions/delete');},function(filename){
	if(Files.cancelUpload(filename)) {
		if(filename.substr){
			filename=[filename];
		}
		$.each(filename,function(index,file){
			var filename = $('tr').filterAttr('data-file',file);
			filename.hide();
			filename.find('input[type="checkbox"]').removeAttr('checked');
			filename.removeClass('selected');
		});
		procesSelection();
	}else{
		FileList.do_delete(filename);
	}
	$('.tipsy').remove();
});

// t('files', 'Rename')
FileActions.register('all','Rename', OC.PERMISSION_UPDATE, function(){return OC.imagePath('core','actions/rename');},function(filename){
	FileList.rename(filename);
});

FileActions.register('dir','Open', OC.PERMISSION_READ, '', function(filename){
	window.location=OC.linkTo('files', 'index.php') + '?dir='+encodeURIComponent($('#dir').val()).replace(/%2F/g, '/')+'/'+encodeURIComponent(filename);
});

FileActions.setDefault('dir','Open');
<commit_msg>code style<commit_after>var FileActions = {
	actions: {},
	defaults: {},
	icons: {},
	currentFile: null,
	register: function (mime, name, permissions, icon, action) {
		if (!FileActions.actions[mime]) {
			FileActions.actions[mime] = {};
		}
		if (!FileActions.actions[mime][name]) {
			FileActions.actions[mime][name] = {};
		}
		FileActions.actions[mime][name]['action'] = action;
		FileActions.actions[mime][name]['permissions'] = permissions;
		FileActions.icons[name] = icon;
	},
	setDefault: function (mime, name) {
		FileActions.defaults[mime] = name;
	},
	get: function (mime, type, permissions) {
		var actions = {};
		if (FileActions.actions.all) {
			actions = $.extend(actions, FileActions.actions.all);
		}
		if (mime) {
			if (FileActions.actions[mime]) {
				actions = $.extend(actions, FileActions.actions[mime]);
			}
			var mimePart = mime.substr(0, mime.indexOf('/'));
			if (FileActions.actions[mimePart]) {
				actions = $.extend(actions, FileActions.actions[mimePart]);
			}
		}
		if (type) {//type is 'dir' or 'file'
			if (FileActions.actions[type]) {
				actions = $.extend(actions, FileActions.actions[type]);
			}
		}
		var filteredActions = {};
		$.each(actions, function (name, action) {
			if (action.permissions & permissions) {
				filteredActions[name] = action.action;
			}
		});
		return filteredActions;
	},
	getDefault: function (mime, type, permissions) {
		if (mime) {
			var mimePart = mime.substr(0, mime.indexOf('/'));
		}
		var name = false;
		if (mime && FileActions.defaults[mime]) {
			name = FileActions.defaults[mime];
		} else if (mime && FileActions.defaults[mimePart]) {
			name = FileActions.defaults[mimePart];
		} else if (type && FileActions.defaults[type]) {
			name = FileActions.defaults[type];
		} else {
			name = FileActions.defaults.all;
		}
		var actions = this.get(mime, type, permissions);
		return actions[name];
	},
	display: function (parent) {
		FileActions.currentFile = parent;
		$('#fileList span.fileactions, #fileList td.date a.action').remove();
		var actions = FileActions.get(FileActions.getCurrentMimeType(), FileActions.getCurrentType(), FileActions.getCurrentPermissions());
		var file = FileActions.getCurrentFile();
		if ($('tr').filterAttr('data-file', file).data('renaming')) {
			return;
		}
		parent.children('a.name').append('');
		var defaultAction = FileActions.getDefault(FileActions.getCurrentMimeType(), FileActions.getCurrentType(), FileActions.getCurrentPermissions());
		for (name in actions) {
			// NOTE: Temporary fix to prevent rename action in root of Shared directory
			if (name == 'Rename' && $('#dir').val() == '/Shared') {
				continue;
			}
			if ((name == 'Download' || actions[name] != defaultAction) && name != 'Delete') {
				var img = FileActions.icons[name];
				if (img.call) {
					img = img(file);
				}
				var html = '';
				if (img) {
					html += ' ';
				}
				html += t('files', name) + '';
				var element = $(html);
				element.data('action', name);
				element.click(function (event) {
					event.stopPropagation();
					event.preventDefault();
					var action = actions[$(this).data('action')];
					var currentFile = FileActions.getCurrentFile();
					FileActions.hide();
					action(currentFile);
				});
				element.hide();
				parent.find('a.name>span.fileactions').append(element);
			}
		}
		if (actions['Delete']) {
			var img = FileActions.icons['Delete'];
			if (img.call) {
				img = img(file);
			}
			// NOTE: Temporary fix to allow unsharing of files in root of Shared folder
			if ($('#dir').val() == '/Shared') {
				var html = '';
			} else {
				var html = '';
			}
			var element = $(html);
			if (img) {
				element.append($(''));
			}
			element.data('action', 'Delete');
			element.click(function (event) {
				event.stopPropagation();
				event.preventDefault();
				var action = actions[$(this).data('action')];
				var currentFile = FileActions.getCurrentFile();
				FileActions.hide();
				action(currentFile);
			});
			element.hide();
			parent.parent().children().last().append(element);
		}
		$('#fileList .action').css('-o-transition-property', 'none');//temporarly disable
		$('#fileList .action').fadeIn(200, function () {
			$('#fileList .action').css('-o-transition-property', 'opacity');
		});
		return false;
	},
	hide: function () {
		$('#fileList span.fileactions, #fileList td.date a.action').fadeOut(200, function () {
			$(this).remove();
		});
	},
	getCurrentFile: function () {
		return FileActions.currentFile.parent().attr('data-file');
	},
	getCurrentMimeType: function () {
		return FileActions.currentFile.parent().attr('data-mime');
	},
	getCurrentType: function () {
		return FileActions.currentFile.parent().attr('data-type');
	},
	getCurrentPermissions: function () {
		return FileActions.currentFile.parent().data('permissions');
	}
};

$(document).ready(function () {
	if ($('#allowZipDownload').val() == 1) {
		var downloadScope = 'all';
	} else {
		var downloadScope = 'file';
	}
	FileActions.register(downloadScope, 'Download', OC.PERMISSION_READ, function () {
		return OC.imagePath('core', 'actions/download');
	}, function (filename) {
		window.location = OC.filePath('files', 'ajax', 'download.php') + '?files=' + encodeURIComponent(filename) + '&dir=' + encodeURIComponent($('#dir').val());
	});
});

FileActions.register('all', 'Delete', OC.PERMISSION_DELETE, function () {
	return OC.imagePath('core', 'actions/delete');
}, function (filename) {
	if (Files.cancelUpload(filename)) {
		if (filename.substr) {
			filename = [filename];
		}
		$.each(filename, function (index, file) {
			var filename = $('tr').filterAttr('data-file', file);
			filename.hide();
			filename.find('input[type="checkbox"]').removeAttr('checked');
			filename.removeClass('selected');
		});
		procesSelection();
	} else {
		FileList.do_delete(filename);
	}
	$('.tipsy').remove();
});

// t('files', 'Rename')
FileActions.register('all', 'Rename', OC.PERMISSION_UPDATE, function () {
	return OC.imagePath('core', 'actions/rename');
}, function (filename) {
	FileList.rename(filename);
});

FileActions.register('dir', 'Open', OC.PERMISSION_READ, '', function (filename) {
	window.location = OC.linkTo('files', 'index.php') + '?dir=' + encodeURIComponent($('#dir').val()).replace(/%2F/g, '/') + '/' + encodeURIComponent(filename);
});

FileActions.setDefault('dir', 'Open');
<|endoftext|>


<commit_before>// main.js
// Dependencies:
// Description: singleton object
// This object will be our main "controller" class and will contain references
// to most of the other objects in the game.

"use strict";

// if app exists use the existing copy
// else create a new object literal
var app = app || {};

/*
 .main is an object literal that is a property of the app global
 This object literal has its own properties and methods (functions)

 */
app.main =
{
    WIDTH : 640, 				// Canvas width
    HEIGHT : 480,				// Canvas height
    canvas : undefined,			// Canvas
    ctx : undefined,			// Canvas context
   	lastTime : 0, 				// used by calculateDeltaTime()
    debug : true,				// debug
	reset : true,
	animationID : 0,			//ID index of the current frame.
	prevKeyDown : undefined,	//keyDown from previous frame.

	//Modules
	sound : undefined,			//Sound

	//Game state enum
	gameState : undefined,
	GAME_STATE: Object.freeze
	({
		START : 0,
		GAME : 1,
		WIN : 2,
	}),

	soul : undefined,
	bbox : undefined,
	conway : undefined,

	soulPos : undefined,

    //Initialization
	init : function()
	{
		//Init log
		console.log("app.main.init() called");

		// init canvas
		this.canvas = document.querySelector('canvas');
		this.canvas.width = this.WIDTH;
		this.canvas.height = this.HEIGHT;
		this.ctx = this.canvas.getContext('2d');
		this.ctx.mozImageSmoothingEnabled = false;
		this.ctx.msImageSmoothingEnabled = false;
		this.ctx.imageSmoothingEnabled = false;

		//Key down from previous frame.
		this.prevKeyDown = myKeys.keydown;

		//Game State
		this.gameState = this.GAME_STATE.START;

		//Bullet box
		this.bbox = new Bbox(320, 320, 316, 140, 1);

		//Player Soul
		this.soulPos = new Vect(309, 310, 0);
		var soulImage = document.getElementById("heart");
		var soulImageDmg = document.getElementById("heart_dmg");
		this.soul = new Soul(this.soulPos.x, this.soulPos.y, soulImage, soulImageDmg, 1);
		this.soul.getCollision(this.ctx);								//Form collision data for player.

		// start the game loop
		this.frame();
	},

	//Setup and resetup, is used for init and any reset.
	setup : function()
	{
		//Conway
		this.conway = new Conway(167, 255, 77, 33, 4);
		this.conway.createEngine(70, 25, 1, 1);
		this.conway.createEngine(25, 25, 1, 1);
		this.conway.createEngine(40, 0, 1, 1);
		this.conway.createEngine(48, 0, 1, 1);
		this.conway.createEngine(0, 0, 1, 1);
		this.conway.createGlider(70, 0, -1, 1);
		this.conway.createGlider(12, 0, 1, 1);
		this.conway.createGlider(4, 24, 1, -1);

		//Player reset
		this.soul.pos = this.soulPos.get();
	},

	//Core update
	frame : function()
	{
		//LOOP
	 	this.animationID = requestAnimationFrame(this.frame.bind(this));

		//Damage reset
		if(this.reset && this.soul.dmg)
		{
			this.setup();
			this.sound.playBeep();
		}

	 	//Calculate Delta Time of frame
	 	var dt = this.calculateDeltaTime();

		//Clear
		this.ctx.save();
		this.ctx.fillStyle = "#000";
		this.ctx.fillRect(0, 0, this.WIDTH, this.HEIGHT);
		this.ctx.restore();

		//Update
		this.update(dt);

		//Draw
		this.draw(this.ctx);

		//Save prevKeyDown for next frame.
		this.prevKeyDown = myKeys.keydown.slice();

		//Draw debug info
		if (this.debug)
		{
			// draw dt in bottom right corner
			this.fillText(
				"dt: " + dt.toFixed(3),
				this.WIDTH - 140,
				this.HEIGHT - 10,
				"24pt undertale",
				"white",
				false);
		}
	},

	//Update logic
	update : function(dt)
	{
		switch(this.gameState)
		{
			case this.GAME_STATE.START:
				if(this.prevKeyDown[myKeys.KEYBOARD.KEY_Z] && !myKeys.keydown[myKeys.KEYBOARD.KEY_Z])
				{
					//Setup
					this.setup();
					this.gameState = this.GAME_STATE.GAME;
				}
				break;
			case this.GAME_STATE.GAME:
				this.conway.update(dt);
				this.bbox.transition(dt);
				this.soul.move(dt);
				this.soul.limit(this.bbox.getBound());
				if(this.conway.getFrameCount() > 1340)
				{
					this.gameState = this.GAME_STATE.WIN;
				}
				break;
			case this.GAME_STATE.WIN:
				if(this.prevKeyDown[myKeys.KEYBOARD.KEY_Z] && !myKeys.keydown[myKeys.KEYBOARD.KEY_Z])
				{
					this.gameState = this.GAME_STATE.START;
				}
				break;
		}
	},

	//Draw the main scene
	draw : function(ctx, objs)
	{
		switch(this.gameState)
		{
			case this.GAME_STATE.START:
				this.bbox.draw(ctx);
				this.soul.draw(ctx);
				this.fillText(
					"Press 'Z' to start!",
					320,
					439.75,
					"24pt undertale",
					"white",
					true);
				break;
			case this.GAME_STATE.GAME:
				this.bbox.draw(ctx);
				this.conway.draw(ctx);
				this.soul.checkCollision(ctx);
				this.soul.draw(ctx);
				break;
			case this.GAME_STATE.WIN:
				this.bbox.draw(ctx);
				this.soul.draw(ctx);
				this.fillText(
					"You Win!",
					320,
					440,
					"48pt undertale",
					"white",
					true);
				break;
		}
	},

	//Draw filled text
	fillText : function(string, x, y, css, color, centered)
	{
		this.ctx.save();
		if(centered)
		{
			this.ctx.textAlign = "center";
			this.ctx.textBaseline="middle";
		}
		this.ctx.font = css;
		this.ctx.fillStyle = color;
		this.ctx.fillText(string, x, y);
		this.ctx.restore();
	},

	//Calculate delta-time
	calculateDeltaTime : function()
	{
		var now, fps;
		now = (+new Date);
		fps = 1000 / (now - this.lastTime);
		fps = clamp(fps, 12, 60);
		this.lastTime = now;
		return 1/fps;
	},
};<commit_msg>DT now displays as a percentage of 60.<commit_after>// main.js
// Dependencies:
// Description: singleton object
// This object will be our main "controller" class and will contain references
// to most of the other objects in the game.

"use strict";

// if app exists use the existing copy
// else create a new object literal
var app = app || {};

/*
 .main is an object literal that is a property of the app global
 This object literal has its own properties and methods (functions)

 */
app.main =
{
    WIDTH : 640, 				// Canvas width
    HEIGHT : 480,				// Canvas height
    canvas : undefined,			// Canvas
    ctx : undefined,			// Canvas context
   	lastTime : 0, 				// used by calculateDeltaTime()
    debug : true,				// debug
	reset : true,
	animationID : 0,			//ID index of the current frame.
	prevKeyDown : undefined,	//keyDown from previous frame.

	//Modules
	sound : undefined,			//Sound

	//Game state enum
	gameState : undefined,
	GAME_STATE: Object.freeze
	({
		START : 0,
		GAME : 1,
		WIN : 2,
	}),

	soul : undefined,
	bbox : undefined,
	conway : undefined,

	soulPos : undefined,

    //Initialization
	init : function()
	{
		//Init log
		console.log("app.main.init() called");

		// init canvas
		this.canvas = document.querySelector('canvas');
		this.canvas.width = this.WIDTH;
		this.canvas.height = this.HEIGHT;
		this.ctx = this.canvas.getContext('2d');
		this.ctx.mozImageSmoothingEnabled = false;
		this.ctx.msImageSmoothingEnabled = false;
		this.ctx.imageSmoothingEnabled = false;

		//Key down from previous frame.
		this.prevKeyDown = myKeys.keydown;

		//Game State
		this.gameState = this.GAME_STATE.START;

		//Bullet box
		this.bbox = new Bbox(320, 320, 316, 140, 1);

		//Player Soul
		this.soulPos = new Vect(309, 310, 0);
		var soulImage = document.getElementById("heart");
		var soulImageDmg = document.getElementById("heart_dmg");
		this.soul = new Soul(this.soulPos.x, this.soulPos.y, soulImage, soulImageDmg, 1);
		this.soul.getCollision(this.ctx);								//Form collision data for player.

		// start the game loop
		this.frame();
	},

	//Setup and resetup, is used for init and any reset.
	setup : function()
	{
		//Conway
		this.conway = new Conway(167, 255, 77, 33, 4);
		this.conway.createEngine(70, 25, 1, 1);
		this.conway.createEngine(25, 25, 1, 1);
		this.conway.createEngine(40, 0, 1, 1);
		this.conway.createEngine(48, 0, 1, 1);
		this.conway.createEngine(0, 0, 1, 1);
		this.conway.createGlider(70, 0, -1, 1);
		this.conway.createGlider(12, 0, 1, 1);
		this.conway.createGlider(4, 24, 1, -1);

		//Player reset
		this.soul.pos = this.soulPos.get();
	},

	//Core update
	frame : function()
	{
		//LOOP
	 	this.animationID = requestAnimationFrame(this.frame.bind(this));

		//Damage reset
		if(this.reset && this.soul.dmg)
		{
			this.setup();
			this.sound.playBeep();
		}

		for(var i = 0; i < 0; i++)
		{
			console.log(this);
		}

	 	//Calculate Delta Time of frame
	 	var dt = this.calculateDeltaTime();

		//Clear
		this.ctx.save();
		this.ctx.fillStyle = "#000";
		this.ctx.fillRect(0, 0, this.WIDTH, this.HEIGHT);
		this.ctx.restore();

		//Update
		this.update(dt);

		//Draw
		this.draw(this.ctx);

		//Save prevKeyDown for next frame.
		this.prevKeyDown = myKeys.keydown.slice();

		//Draw debug info
		if (this.debug)
		{
			// draw dt in bottom right corner
			this.fillText(
				"dt: " + (100 / (60 * dt)).toFixed(1) + "%",
				this.WIDTH - 140,
				this.HEIGHT - 10,
				"24pt undertale",
				"white",
				false);
		}
	},

	//Update logic
	update : function(dt)
	{
		switch(this.gameState)
		{
			case this.GAME_STATE.START:
				if(this.prevKeyDown[myKeys.KEYBOARD.KEY_Z] && !myKeys.keydown[myKeys.KEYBOARD.KEY_Z])
				{
					//Setup
					this.setup();
					this.gameState = this.GAME_STATE.GAME;
				}
				break;
			case this.GAME_STATE.GAME:
				this.conway.update(dt);
				this.bbox.transition(dt);
				this.soul.move(dt);
				this.soul.limit(this.bbox.getBound());
				if(this.conway.getFrameCount() > 1340)
				{
					this.gameState = this.GAME_STATE.WIN;
				}
				break;
			case this.GAME_STATE.WIN:
				if(this.prevKeyDown[myKeys.KEYBOARD.KEY_Z] && !myKeys.keydown[myKeys.KEYBOARD.KEY_Z])
				{
					this.gameState = this.GAME_STATE.START;
				}
				break;
		}
	},

	//Draw the main scene
	draw : function(ctx, objs)
	{
		switch(this.gameState)
		{
			case this.GAME_STATE.START:
				this.bbox.draw(ctx);
				this.soul.draw(ctx);
				this.fillText(
					"Press 'Z' to start!",
					320,
					439.75,
					"24pt undertale",
					"white",
					true);
				break;
			case this.GAME_STATE.GAME:
				this.bbox.draw(ctx);
				this.conway.draw(ctx);
				this.soul.checkCollision(ctx);
				this.soul.draw(ctx);
				break;
			case this.GAME_STATE.WIN:
				this.bbox.draw(ctx);
				this.soul.draw(ctx);
				this.fillText(
					"You Win!",
					320,
					440,
					"48pt undertale",
					"white",
					true);
				break;
		}
	},

	//Draw filled text
	fillText : function(string, x, y, css, color, centered)
	{
		this.ctx.save();
		if(centered)
		{
			this.ctx.textAlign = "center";
			this.ctx.textBaseline="middle";
		}
		this.ctx.font = css;
		this.ctx.fillStyle = color;
		this.ctx.fillText(string, x, y);
		this.ctx.restore();
	},

	//Calculate delta-time
	calculateDeltaTime : function()
	{
		var now, fps;
		now = (+new Date);
		fps = 1000 / (now - this.lastTime);
		fps = clamp(fps, 12, 60);
		this.lastTime = now;
		return 1/fps;
	},
};<|endoftext|>


<commit_before>var genoverse = {
    bindings: {
        genome:           '=',
        chr:              '=',
        start:            '=',
        end:              '=',

        highlights:       '=?',

        genoverseUtils:   '='
    },
    controller: ['$http', '$interpolate', '$timeout', function($http, $interpolate, $timeout) {
        var ctrl = this;

        // Variables
        // ---------
        ctrl.trackConfigs = [];

        // Methods
        // -------
        ctrl.render = function() {
            // <genoverse-track name="'Sequence'" model="Genoverse.Track.Model.Sequence.Ensembl" view="Genoverse.Track.View.Sequence" controller="Genoverse.Track.Controller.Sequence" url="genoverseUtils.urls.sequence" resizable="'auto'" auto-height="true" hide-empty="false" extra="{100000: false}"></genoverse-track>
            // <genoverse-track name="'Genes'" labels="true" info="'Ensembl API genes'" model="Genoverse.Track.Model.Gene.Ensembl" view="Genoverse.Track.View.Gene.Ensembl" url="genoverseUtils.urls.genes" resizable="'auto'" auto-height="true" hide-empty="false" extra="{populateMenu: genoverseUtils.genesPopulateMenu}"></genoverse-track>
            // <genoverse-track name="'Transcripts'" labels="true" info="'Ensembl API transcripts'" model="Genoverse.Track.Model.Transcript.Ensembl" view="Genoverse.Track.View.Transcript.Ensembl" url="genoverseUtils.urls.transcripts" resizable="'auto'" auto-height="true" hide-empty="false" extra="{populateMenu: genoverseUtils.transcriptsPopulateMenu}"></genoverse-track>
            // <genoverse-track name="'RNAcentral'" id="'RNAcentral'" info="'Unique RNAcentral Sequences'" model="Genoverse.Track.Model.Gene.Ensembl" model-extra="{parseData: genoverseUtils.RNAcentralParseData}" view="Genoverse.Track.View.Transcript.Ensembl" url="genoverseUtils.urls.RNAcentral" extra="{populateMenu: genoverseUtils.RNAcentralPopulateMenu}" resizable="'auto'" auto-height="true" hide-empty="false"></genoverse-track>

            // create Genoverse browser
            var genoverseConfig = {
                container: $('#genoverse'),
                width: $('#genoverse').width(),

                chr: ctrl.chr,
                start: ctrl.start,
                end: ctrl.end,
                genome: ctrl.genome,

                urlParamTemplate: false,

                highlights: ctrl.highlights,
                plugins: ['controlPanel', 'karyotype', 'resizer', 'fileDrop'],
                tracks: [
                    Genoverse.Track.Scalebar,
                    Genoverse.Track.extend({
                        name       : 'Sequence',
                        url        : ctrl.genoverseUtils.urls.sequence(),
                        controller : Genoverse.Track.Controller.Sequence,
                        model      : Genoverse.Track.Model.Sequence.Ensembl,
                        view       : Genoverse.Track.View.Sequence,
                        100000     : false,
                        resizable  : 'auto',
                        autoHeight : true,
                        hideEmpty  : false
                    }),
                    Genoverse.Track.extend({
                        name        : 'Genes',
                        labels      : true,
                        info        : 'Ensembl API genes',
                        url         : ctrl.genoverseUtils.urls.genes(),
                        model       : Genoverse.Track.Model.Gene.Ensembl,
                        view        : Genoverse.Track.View.Gene.Ensembl,
                        100000      : false,
                        populateMenu: ctrl.genoverseUtils.genesPopulateMenu,
                        resizable   : 'auto',
                        autoHeight  : true,
                        hideEmpty   : false
                    }),
                    Genoverse.Track.extend({
                        name        : 'Transcripts',
                        labels      : true,
                        info        : 'Ensembl API transcripts',
                        url         : ctrl.genoverseUtils.urls.transcripts(),
                        model       : Genoverse.Track.Model.Transcript.Ensembl,
                        view        : Genoverse.Track.View.Transcript.Ensembl,
                        100000      : false,
                        populateMenu: ctrl.genoverseUtils.transcriptsPopulateMenu,
                        resizable   : 'auto',
                        autoHeight  : true,
                        hideEmpty   : false
                    }),
                    Genoverse.Track.extend({
                        name        : 'RNAcentral',
                        info        : 'Unique RNAcentral Sequences',
                        url         : ctrl.genoverseUtils.urls.RNAcentral(),
                        model       : Genoverse.Track.Model.Gene.Ensembl.extend({parseData: ctrl.genoverseUtils.RNAcentralParseData}),
                        view        : Genoverse.Track.View.Transcript.Ensembl,
                        100000      : false,
                        populateMenu: ctrl.genoverseUtils.RNAcentralPopulateMenu,
                        resizable   : 'auto',
                        autoHeight  : true,
                        hideEmpty   : false
                    })
                ],
                loadGenome: function () {
                    if (typeof this.genome === 'string') {
                        var genomeName = this.genome;

                        return $.ajax({
                            url      : '/api/v1/karyotypes/' + genomeName,
                            dataType : 'json',
                            context  : this,
                            success  : function (result) {
                                Genoverse.Genomes[genomeName] = result;
                                this.genome = Genoverse.Genomes[genomeName];

                                if (!this.genome) {
                                    this.die('Unable to load genome ' + genomeName);
                                }
                            }
                        });
                    }
                },
                /**
                 * Override loadPlugins to hard-code genoverse location, so that Genoverse survives minification.
                 */
                loadPlugins: function (plugins) {
                    var browser         = this;
                    var loadPluginsTask = $.Deferred();

                    plugins = plugins || this.plugins;

                    this.loadedPlugins = this.loadedPlugins || {};

                    for (var i in Genoverse.Plugins) {
                      this.loadedPlugins[i] = this.loadedPlugins[i] || 'script';
                    }

                    if (typeof plugins === 'string') {
                      plugins = [ plugins ];
                    }

                    function loadPlugin(plugin) {
                      var css      = '/static/node_modules/@burkov/genoverse/dist/' + 'css/'        + plugin + '.css';
                      var js       = '/static/node_modules/@burkov/genoverse/dist/' + 'js/plugins/' + plugin + '.js';
                      var deferred = $.Deferred();

                      function getCSS() {
                        function done() {
                          browser.loadedPlugins[plugin] = browser.loadedPlugins[plugin] || 'script';
                          deferred.resolve(plugin);
                        }

                        if (Genoverse.Plugins[plugin].noCSS || $('link[href="' + css + '"]').length) {
                          return done();
                        }

                        $('<link href="' + css + '" rel="stylesheet">').on('load', done).appendTo('body');
                      }

                      if (browser.loadedPlugins[plugin] || $('script[src="' + js + '"]').length) {
                        getCSS();
                      } else {
                        $.getScript(js, getCSS);
                      }

                      return deferred;
                    }

                    function initializePlugin(plugin) {
                      if (typeof Genoverse.Plugins[plugin] !== 'function' || browser.loadedPlugins[plugin] === true) {
                        return [];
                      }

                      var requires = Genoverse.Plugins[plugin].requires;
                      var deferred = $.Deferred();

                      function init() {
                        if (browser.loadedPlugins[plugin] !== true) {
                          Genoverse.Plugins[plugin].call(browser);
                          browser.container.addClass('gv-' + plugin.replace(/([A-Z])/g, '-$1').toLowerCase() + '-plugin');
                          browser.loadedPlugins[plugin] = true;
                        }

                        deferred.resolve();
                      }

                      if (requires) {
                        $.when(browser.loadPlugins(requires)).done(init);
                      } else {
                        init();
                      }

                      return deferred;
                    }

                    // Load plugins css file
                    $.when.apply($, $.map(plugins, loadPlugin)).done(function () {
                      var pluginsLoaded = [];
                      var plugin;

                      for (var i = 0; i < arguments.length; i++) {
                        plugin = arguments[i];

                        if (browser.loadedPlugins[plugin] !== true) {
                          pluginsLoaded.push(initializePlugin(plugin));
                        }
                      }

                      $.when.apply($, pluginsLoaded).always(loadPluginsTask.resolve);
                    });

                    return loadPluginsTask;
                  },

            };

            try { ctrl.browser = new Genoverse(genoverseConfig); }
            catch (e) {
                if (e instanceof TypeError) {
                    ctrl.browser.destroy();
                    delete ctrl.browser;
                    genoverseConfig.plugins = ['controlPanel', 'resizer', 'fileDrop'];
                    ctrl.browser = new Genoverse(genoverseConfig);
                }
            }

            // set browser -> Angular data flow
            ctrl.browser.on({
                // this event is called, whenever the user updates the browser viewport location
                afterSetRange: function () {
                    // let angular update its model in response to coordinates change
                    // that's an anti-pattern, but no other way to use FRP in angular
                    $timeout(angular.noop);
                }
            });

            // initialize old state for $doCheck hook
            ctrl.oldBrowserStart = ctrl.browser.start;
            ctrl.oldBrowserEnd = ctrl.browser.end;
            ctrl.oldBrowserChr = ctrl.browser.chr;

            ctrl.oldStart = ctrl.start;
            ctrl.oldEnd = ctrl.end;
            ctrl.oldChr = ctrl.chr;
            ctrl.oldGenome = ctrl.genome;
            ctrl.oldHighlights = ctrl.highlights;

            // resize genoverse on browser width changes, if container passed - attach once only
            $(window).on('resize', ctrl.setGenoverseWidth);
        };

        /**
         * Makes browser "responsive" - if container changes width, so does the browser.
         */
        ctrl.setGenoverseWidth = function() {
            // if $scope.container passed, makes browser width responsive
            var width = $('.genoverse-wrap').width();
            ctrl.browser.setWidth(width);

            // resize might change viewport location - digest these changes
            $timeout(angular.noop)
        };

        // Hooks
        // -----

        this.$onInit = function() {
            ctrl.render();
        };

        ctrl.$doCheck = function() {
            if (ctrl.browser.start != ctrl.oldBrowserStart) {
                ctrl.start = ctrl.oldStart = ctrl.oldBrowserStart = ctrl.browser.start;
            }
            if (ctrl.browser.end != ctrl.oldBrowserEnd) {
                ctrl.end = ctrl.oldEnd = ctrl.oldBrowserEnd = ctrl.browser.end;
            }
            if (ctrl.browser.chr != ctrl.oldBrowserChr) {
                ctrl.chr = ctrl.oldBrowserChr = ctrl.oldChr = ctrl.browser.chr;
            }

            if (ctrl.genome === ctrl.oldGenome && (ctrl.chr !== ctrl.oldChr || ctrl.start !== ctrl.oldStart || ctrl.end !== ctrl.oldEnd )) {
                ctrl.browser.moveTo(ctrl.chr, ctrl.start, ctrl.end, true);
            }
            if (ctrl.genome !== ctrl.oldGenome) {
                // destroy the old instance of browser and watches
                if (ctrl.browser) {
                    ctrl.browser.destroy(); // destroy genoverse and all callbacks and ajax requests
                    delete ctrl.browser; // clear old instance of browser
                }

                // set the default location for the browser
                if (ctrl.genoverseUtils.exampleLocations[ctrl.genome]) {
                    ctrl.chr = ctrl.genoverseUtils.exampleLocations[ctrl.genome].chr;
                    ctrl.start = ctrl.genoverseUtils.exampleLocations[ctrl.genome].start;
                    ctrl.end = ctrl.genoverseUtils.exampleLocations[ctrl.genome].end;
                } else {
                    alert("Can't find example location for genome ", ctrl.genome);
                }

                ctrl.render(); // create a new instance of browser

                ctrl.oldGenome = ctrl.genome;
                ctrl.oldChr = ctrl.oldBrowserChr = ctrl.chr;
                ctrl.oldStart = ctrl.oldBrowserStart = ctrl.start;
                ctrl.oldEnd = ctrl.oldBrowserEnd = ctrl.end;
            }
            if (ctrl.highlights !== ctrl.oldHighlights) {
                ctrl.browser.addHighlights(ctrl.highlights);
                ctrl.oldHighlights = ctrl.highlights;
            }

        };

    }],
    template: "
" +
              "

" +
              "
",
};

angular.module("genomeBrowser").component("genoverse", genoverse);<commit_msg> #377 Commented-out catch clause for testing.<commit_after>var genoverse = {
    bindings: {
        genome:           '=',
        chr:              '=',
        start:            '=',
        end:              '=',

        highlights:       '=?',

        genoverseUtils:   '='
    },
    controller: ['$http', '$interpolate', '$timeout', function($http, $interpolate, $timeout) {
        var ctrl = this;

        // Variables
        // ---------
        ctrl.trackConfigs = [];

        // Methods
        // -------
        ctrl.render = function() {
            // <genoverse-track name="'Sequence'" model="Genoverse.Track.Model.Sequence.Ensembl" view="Genoverse.Track.View.Sequence" controller="Genoverse.Track.Controller.Sequence" url="genoverseUtils.urls.sequence" resizable="'auto'" auto-height="true" hide-empty="false" extra="{100000: false}"></genoverse-track>
            // <genoverse-track name="'Genes'" labels="true" info="'Ensembl API genes'" model="Genoverse.Track.Model.Gene.Ensembl" view="Genoverse.Track.View.Gene.Ensembl" url="genoverseUtils.urls.genes" resizable="'auto'" auto-height="true" hide-empty="false" extra="{populateMenu: genoverseUtils.genesPopulateMenu}"></genoverse-track>
            // <genoverse-track name="'Transcripts'" labels="true" info="'Ensembl API transcripts'" model="Genoverse.Track.Model.Transcript.Ensembl" view="Genoverse.Track.View.Transcript.Ensembl" url="genoverseUtils.urls.transcripts" resizable="'auto'" auto-height="true" hide-empty="false" extra="{populateMenu: genoverseUtils.transcriptsPopulateMenu}"></genoverse-track>
            // <genoverse-track name="'RNAcentral'" id="'RNAcentral'" info="'Unique RNAcentral Sequences'" model="Genoverse.Track.Model.Gene.Ensembl" model-extra="{parseData: genoverseUtils.RNAcentralParseData}" view="Genoverse.Track.View.Transcript.Ensembl" url="genoverseUtils.urls.RNAcentral" extra="{populateMenu: genoverseUtils.RNAcentralPopulateMenu}" resizable="'auto'" auto-height="true" hide-empty="false"></genoverse-track>

            // create Genoverse browser
            var genoverseConfig = {
                container: $('#genoverse'),
                width: $('#genoverse').width(),

                chr: ctrl.chr,
                start: ctrl.start,
                end: ctrl.end,
                genome: ctrl.genome,

                urlParamTemplate: false,

                highlights: ctrl.highlights,
                plugins: ['controlPanel', 'karyotype', 'resizer', 'fileDrop'],
                tracks: [
                    Genoverse.Track.Scalebar,
                    Genoverse.Track.extend({
                        name       : 'Sequence',
                        url        : ctrl.genoverseUtils.urls.sequence(),
                        controller : Genoverse.Track.Controller.Sequence,
                        model      : Genoverse.Track.Model.Sequence.Ensembl,
                        view       : Genoverse.Track.View.Sequence,
                        100000     : false,
                        resizable  : 'auto',
                        autoHeight : true,
                        hideEmpty  : false
                    }),
                    Genoverse.Track.extend({
                        name        : 'Genes',
                        labels      : true,
                        info        : 'Ensembl API genes',
                        url         : ctrl.genoverseUtils.urls.genes(),
                        model       : Genoverse.Track.Model.Gene.Ensembl,
                        view        : Genoverse.Track.View.Gene.Ensembl,
                        100000      : false,
                        populateMenu: ctrl.genoverseUtils.genesPopulateMenu,
                        resizable   : 'auto',
                        autoHeight  : true,
                        hideEmpty   : false
                    }),
                    Genoverse.Track.extend({
                        name        : 'Transcripts',
                        labels      : true,
                        info        : 'Ensembl API transcripts',
                        url         : ctrl.genoverseUtils.urls.transcripts(),
                        model       : Genoverse.Track.Model.Transcript.Ensembl,
                        view        : Genoverse.Track.View.Transcript.Ensembl,
                        100000      : false,
                        populateMenu: ctrl.genoverseUtils.transcriptsPopulateMenu,
                        resizable   : 'auto',
                        autoHeight  : true,
                        hideEmpty   : false
                    }),
                    Genoverse.Track.extend({
                        name        : 'RNAcentral',
                        info        : 'Unique RNAcentral Sequences',
                        url         : ctrl.genoverseUtils.urls.RNAcentral(),
                        model       : Genoverse.Track.Model.Gene.Ensembl.extend({parseData: ctrl.genoverseUtils.RNAcentralParseData}),
                        view        : Genoverse.Track.View.Transcript.Ensembl,
                        100000      : false,
                        populateMenu: ctrl.genoverseUtils.RNAcentralPopulateMenu,
                        resizable   : 'auto',
                        autoHeight  : true,
                        hideEmpty   : false
                    })
                ],
                loadGenome: function () {
                    if (typeof this.genome === 'string') {
                        var genomeName = this.genome;

                        return $.ajax({
                            url      : '/api/v1/karyotypes/' + genomeName,
                            dataType : 'json',
                            context  : this,
                            success  : function (result) {
                                Genoverse.Genomes[genomeName] = result;
                                this.genome = Genoverse.Genomes[genomeName];

                                if (!this.genome) {
                                    this.die('Unable to load genome ' + genomeName);
                                }
                            }
                        });
                    }
                },
                /**
                 * Override loadPlugins to hard-code genoverse location, so that Genoverse survives minification.
                 */
                loadPlugins: function (plugins) {
                    var browser         = this;
                    var loadPluginsTask = $.Deferred();

                    plugins = plugins || this.plugins;

                    this.loadedPlugins = this.loadedPlugins || {};

                    for (var i in Genoverse.Plugins) {
                      this.loadedPlugins[i] = this.loadedPlugins[i] || 'script';
                    }

                    if (typeof plugins === 'string') {
                      plugins = [ plugins ];
                    }

                    function loadPlugin(plugin) {
                      var css      = '/static/node_modules/@burkov/genoverse/dist/' + 'css/'        + plugin + '.css';
                      var js       = '/static/node_modules/@burkov/genoverse/dist/' + 'js/plugins/' + plugin + '.js';
                      var deferred = $.Deferred();

                      function getCSS() {
                        function done() {
                          browser.loadedPlugins[plugin] = browser.loadedPlugins[plugin] || 'script';
                          deferred.resolve(plugin);
                        }

                        if (Genoverse.Plugins[plugin].noCSS || $('link[href="' + css + '"]').length) {
                          return done();
                        }

                        $('<link href="' + css + '" rel="stylesheet">').on('load', done).appendTo('body');
                      }

                      if (browser.loadedPlugins[plugin] || $('script[src="' + js + '"]').length) {
                        getCSS();
                      } else {
                        $.getScript(js, getCSS);
                      }

                      return deferred;
                    }

                    function initializePlugin(plugin) {
                      if (typeof Genoverse.Plugins[plugin] !== 'function' || browser.loadedPlugins[plugin] === true) {
                        return [];
                      }

                      var requires = Genoverse.Plugins[plugin].requires;
                      var deferred = $.Deferred();

                      function init() {
                        if (browser.loadedPlugins[plugin] !== true) {
                          Genoverse.Plugins[plugin].call(browser);
                          browser.container.addClass('gv-' + plugin.replace(/([A-Z])/g, '-$1').toLowerCase() + '-plugin');
                          browser.loadedPlugins[plugin] = true;
                        }

                        deferred.resolve();
                      }

                      if (requires) {
                        $.when(browser.loadPlugins(requires)).done(init);
                      } else {
                        init();
                      }

                      return deferred;
                    }

                    // Load plugins css file
                    $.when.apply($, $.map(plugins, loadPlugin)).done(function () {
                      var pluginsLoaded = [];
                      var plugin;

                      for (var i = 0; i < arguments.length; i++) {
                        plugin = arguments[i];

                        if (browser.loadedPlugins[plugin] !== true) {
                          pluginsLoaded.push(initializePlugin(plugin));
                        }
                      }

                      $.when.apply($, pluginsLoaded).always(loadPluginsTask.resolve);
                    });

                    return loadPluginsTask;
                  },

            };

            ctrl.browser = new Genoverse(genoverseConfig);
            // catch (e) {
            //     if (e instanceof TypeError) {
            //         ctrl.browser.destroy();
            //         delete ctrl.browser;
            //         genoverseConfig.plugins = ['controlPanel', 'resizer', 'fileDrop'];
            //         ctrl.browser = new Genoverse(genoverseConfig);
            //     }
            // }

            // set browser -> Angular data flow
            ctrl.browser.on({
                // this event is called, whenever the user updates the browser viewport location
                afterSetRange: function () {
                    // let angular update its model in response to coordinates change
                    // that's an anti-pattern, but no other way to use FRP in angular
                    $timeout(angular.noop);
                }
            });

            // initialize old state for $doCheck hook
            ctrl.oldBrowserStart = ctrl.browser.start;
            ctrl.oldBrowserEnd = ctrl.browser.end;
            ctrl.oldBrowserChr = ctrl.browser.chr;

            ctrl.oldStart = ctrl.start;
            ctrl.oldEnd = ctrl.end;
            ctrl.oldChr = ctrl.chr;
            ctrl.oldGenome = ctrl.genome;
            ctrl.oldHighlights = ctrl.highlights;

            // resize genoverse on browser width changes, if container passed - attach once only
            $(window).on('resize', ctrl.setGenoverseWidth);
        };

        /**
         * Makes browser "responsive" - if container changes width, so does the browser.
         */
        ctrl.setGenoverseWidth = function() {
            // if $scope.container passed, makes browser width responsive
            var width = $('.genoverse-wrap').width();
            ctrl.browser.setWidth(width);

            // resize might change viewport location - digest these changes
            $timeout(angular.noop)
        };

        // Hooks
        // -----

        this.$onInit = function() {
            ctrl.render();
        };

        ctrl.$doCheck = function() {
            if (ctrl.browser.start != ctrl.oldBrowserStart) {
                ctrl.start = ctrl.oldStart = ctrl.oldBrowserStart = ctrl.browser.start;
            }
            if (ctrl.browser.end != ctrl.oldBrowserEnd) {
                ctrl.end = ctrl.oldEnd = ctrl.oldBrowserEnd = ctrl.browser.end;
            }
            if (ctrl.browser.chr != ctrl.oldBrowserChr) {
                ctrl.chr = ctrl.oldBrowserChr = ctrl.oldChr = ctrl.browser.chr;
            }

            if (ctrl.genome === ctrl.oldGenome && (ctrl.chr !== ctrl.oldChr || ctrl.start !== ctrl.oldStart || ctrl.end !== ctrl.oldEnd )) {
                ctrl.browser.moveTo(ctrl.chr, ctrl.start, ctrl.end, true);
            }
            if (ctrl.genome !== ctrl.oldGenome) {
                // destroy the old instance of browser and watches
                if (ctrl.browser) {
                    ctrl.browser.destroy(); // destroy genoverse and all callbacks and ajax requests
                    delete ctrl.browser; // clear old instance of browser
                }

                // set the default location for the browser
                if (ctrl.genoverseUtils.exampleLocations[ctrl.genome]) {
                    ctrl.chr = ctrl.genoverseUtils.exampleLocations[ctrl.genome].chr;
                    ctrl.start = ctrl.genoverseUtils.exampleLocations[ctrl.genome].start;
                    ctrl.end = ctrl.genoverseUtils.exampleLocations[ctrl.genome].end;
                } else {
                    alert("Can't find example location for genome ", ctrl.genome);
                }

                ctrl.render(); // create a new instance of browser

                ctrl.oldGenome = ctrl.genome;
                ctrl.oldChr = ctrl.oldBrowserChr = ctrl.chr;
                ctrl.oldStart = ctrl.oldBrowserStart = ctrl.start;
                ctrl.oldEnd = ctrl.oldBrowserEnd = ctrl.end;
            }
            if (ctrl.highlights !== ctrl.oldHighlights) {
                ctrl.browser.addHighlights(ctrl.highlights);
                ctrl.oldHighlights = ctrl.highlights;
            }

        };

    }],
    template: "
" +
              "

" +
              "
",
};

angular.module("genomeBrowser").component("genoverse", genoverse);<|endoftext|>


<commit_before>'use strict';
// Projects controller

angular.module('projects').controller('ProjectsController', ['$scope', '$stateParams', '$sce', '$location', '$window', '$timeout', 'Authentication', 'Projects', 'FileUploader', 'linkify',
	function($scope, $stateParams, $sce, $location, $window, $timeout, Authentication, Projects, FileUploader, linkify ) {
		$scope.authentication = Authentication;

		// Create file uploader instance
		$scope.uploader = new FileUploader({
			url: '/api/projects/picture'
		});

		$scope.uploaderC = new FileUploader({
			url: '/api/projects/picture'
		});

		// Create new Project
		$scope.create = function() {
			// Create new Project object
			//if((this.essentialDetails && essentialDetails.litDetails.standards) || (this.essentialDetails && this.essentialDetails.mathDetails.standards) || (this.essentialDetails && essentialDetails.scienceDetails.standards) || (this.essentialDetails && essentialDetails.ssDetails.standards)){

			$scope.essentialDetails.overallStandards = '';

			if($scope.essentialDetails.litDetails.standards !== undefined){
				$scope.essentialDetails.overallStandards += $scope.essentialDetails.litDetails.standards + ', ';
			}
			if(this.essentialDetails.mathDetails.standards){
				$scope.essentialDetails.overallStandards += $scope.essentialDetails.mathDetails.standards + ', ';
			}
			//this.essentialDetails.overallStandards = this.essentialDetails.litDetails.standards + ', ' + this.essentialDetails.mathDetails.standards + ', ' + this.essentialDetails.scienceDetails.standards + ', ' + this.essentialDetails.ssDetails.standards;
			//}
			//else{
				//this.essentialDetails.overallStandards = '';
			//}
			var project = new Projects ({
				name: this.name,
				created: this.created,
				user: this.user,
				status: this.status,
				isPublic: this.isPublic,
				minGrade: this.minGrade,
				maxGrade: this.maxGrade,
				ask: this.ask,
				imagine: this.imagine,
				essentialDetails: this.essentialDetails,
				rating: null
			});

			//project.essentialDetails.overallStandards = $scope.essentialDetails.overallStandards;

			// Redirect after save
			project.$save(function(response) {

				// Start upload of picture

				if ($scope.uploaderC.queue.length > 0)
				{
					$scope.uploaderC.queue[0].url = '/api/projects/picture/' + response._id;
					$scope.uploaderC.uploadAll();
				}

				// Clear form fields
				$scope.name = '';

				$location.path('projects/' + response._id);

			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});

		};

		// Remove existing Project
		$scope.remove = function( project ) {
			if ( project ) { project.$remove();

				for (var i in $scope.projects ) {
					if ($scope.projects [i] === project ) {
						$scope.projects.splice(i, 1);
					}
				}
			} else {
				$scope.project.$remove(function() {
					$location.path('projects');
				});
			}
		};

		$scope.CombineStandards = function(){
			$scope.project.essentialDetails.overallStandards = $scope.project.essentialDetails.litDetails[0].standards + ', '
				+ $scope.project.essentialDetails.mathDetails[0].standards + ', '
				+ $scope.project.essentialDetails.scienceDetails[0].standards + ', '
				+ $scope.project.essentialDetails.ssDetails[0].standards;
		};

		// Update existing Project
		$scope.update = function() {
            console.log('In $scope.update');

			var project = $scope.project;

			project.imagine.plan = '';

			project.$update(function() {

				$location.path('projects/' + project._id);
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});

			if ($scope.uploader.queue.length > 0) {
				$scope.uploader.queue[0].url = '/api/projects/picture/' + project._id;
				$scope.uploader.uploadAll();
			}
		};

		// Find a list of Projects
		$scope.find = function() {
			$scope.projects = Projects.query();
		};

		// Find existing Project
		$scope.findOne = function() {
			$scope.project = Projects.get({
				projectId: $stateParams.projectId
			});

		};

		// Called after the user selected a new picture file
		$scope.uploader.onAfterAddingFile = function (fileItem) {
			if ($window.FileReader) {
				var fileReader = new FileReader();
				fileReader.readAsDataURL(fileItem._file);

				fileReader.onload = function (fileReaderEvent) {
					$timeout(function () {
						$scope.project.imagine.plan = fileReaderEvent.target.result;
					}, 0);
				};
			}
		};

		$scope.linkify = function(link) {
			return $sce.trustAsHtml(linkify.normal(link));
		};

		$scope.uploaderC.onAfterAddingFile = function (fileItem) {
			if ($window.FileReader) {
				var fileReader = new FileReader();
				fileReader.readAsDataURL(fileItem._file);

				fileReader.onload = function (fileReaderEvent) {
					$timeout(function () {
						$scope.imageURL = fileReaderEvent.target.result;
					}, 0);
				};
			}
		};

/*	-------------------------------------Star Rating Stuff-------------------------------------- */

		//an array containing the name of the glyphicon to use for each star
		$scope.glyphs = new Array(
			'gold glyphicon glyphicon-star-empty',
			'gold glyphicon glyphicon-star-empty',
			'gold glyphicon glyphicon-star-empty',
			'gold glyphicon glyphicon-star-empty',
			'gold glyphicon glyphicon-star-empty'
		);

		/*
			Runs when a star glyphicon is hovered into. It sets all the stars up to the current one
			to have the filled-in star glyphicon.
		*/
		$scope.rating_hover = function(num){
			for(var i = 0; i < num; i++){
				$scope.glyphs[i] = 'gold glyphicon glyphicon-star';
			}
			for(i = num; i < 5; i++){
				$scope.glyphs[i] = 'gold glyphicon glyphicon-star-empty';
			}
		};

		//Runs when a star glyphicon is hovered out of. Resets the  stars' highlighing to the current rating
		$scope.reset_hover = function(){
			$scope.rating_hover($scope.rating);
		};

		//Prints out user's current rating of the project
		$scope.getMyRating = function(){

			if ($scope.project.rating && $scope.project.rating.ratings ){
				var rater = $scope.project.rating.ratings.filter(isRater)[0];
				console.log(rater);
				if (typeof rater === 'undefined'){
					$scope.rating = 0;	//current rating
					return 'You haven\'t yet rated this project. Give it a couple of stars?';
				}
				$scope.rating = rater.num;
				$scope.reset_hover();
				return ('Your currently rate this project at ' + rater.num + ' stars');
			}
			$scope.rating = 0;	//current rating
			return 'This project has not yet been rated. Give it a couple of stars?';

		};

        // Function to find the current rater
        var isRater = function(value){
			return value.reviewer === $scope.authentication.user._id;
        };

		//Changes the user's rating of the project
		$scope.rate = function(){
			console.log('In $scope.rate');
			if(!$scope.project.rating){
				$scope.project.rating = {
					ratings : [
						{
							num: $scope.rating,
							reviewer: $scope.authentication.user._id
						}
					],
					avg_rating : $scope.rating
				};
			} else {
                var rater = $scope.project.rating.ratings.filter(isRater)[0];
                var length = $scope.project.rating.ratings.length;
				var rateToRemove = 0;

                var newLength = length + 1;

                if(length === 0)
                {
                    $scope.project.rating.avg_rating = 0;
                }

				if(typeof rater !== 'undefined') {
                    rateToRemove = rater.num;
                    var rateIndex = $scope.project.rating.ratings.indexOf(rater);
                    $scope.project.rating.ratings.splice(rateIndex, 1);
                    newLength -= 1;
                }

				$scope.project.rating.avg_rating = ($scope.project.rating.avg_rating * length + $scope.rating - rateToRemove)/(newLength);

				$scope.project.rating.ratings.push({
						num: $scope.rating,
						reviewer: $scope.authentication.user._id
				});
			}
			$scope.update();

		};

	}
]);
<commit_msg>fixed the jshint errors<commit_after>'use strict';
// Projects controller

angular.module('projects').controller('ProjectsController', ['$scope', '$stateParams', '$sce', '$location', '$window', '$timeout', 'Authentication', 'Projects', 'FileUploader', 'linkify',
	function($scope, $stateParams, $sce, $location, $window, $timeout, Authentication, Projects, FileUploader, linkify ) {
		$scope.authentication = Authentication;

		// Create file uploader instance
		$scope.uploader = new FileUploader({
			url: '/api/projects/picture'
		});

		$scope.uploaderC = new FileUploader({
			url: '/api/projects/picture'
		});

		// Create new Project
		$scope.create = function() {
			// Create new Project object
			//if((this.essentialDetails && essentialDetails.litDetails.standards) || (this.essentialDetails && this.essentialDetails.mathDetails.standards) || (this.essentialDetails && essentialDetails.scienceDetails.standards) || (this.essentialDetails && essentialDetails.ssDetails.standards)){

			$scope.essentialDetails.overallStandards = '';

			if($scope.essentialDetails.litDetails.standards !== undefined){
				$scope.essentialDetails.overallStandards += $scope.essentialDetails.litDetails.standards + ', ';
			}
			if(this.essentialDetails.mathDetails.standards){
				$scope.essentialDetails.overallStandards += $scope.essentialDetails.mathDetails.standards + ', ';
			}
			//this.essentialDetails.overallStandards = this.essentialDetails.litDetails.standards + ', ' + this.essentialDetails.mathDetails.standards + ', ' + this.essentialDetails.scienceDetails.standards + ', ' + this.essentialDetails.ssDetails.standards;
			//}
			//else{
				//this.essentialDetails.overallStandards = '';
			//}
			var project = new Projects ({
				name: this.name,
				created: this.created,
				user: this.user,
				status: this.status,
				isPublic: this.isPublic,
				minGrade: this.minGrade,
				maxGrade: this.maxGrade,
				ask: this.ask,
				imagine: this.imagine,
				essentialDetails: this.essentialDetails,
				rating: null
			});

			//project.essentialDetails.overallStandards = $scope.essentialDetails.overallStandards;

			// Redirect after save
			project.$save(function(response) {

				// Start upload of picture

				if ($scope.uploaderC.queue.length > 0)
				{
					$scope.uploaderC.queue[0].url = '/api/projects/picture/' + response._id;
					$scope.uploaderC.uploadAll();
				}

				// Clear form fields
				$scope.name = '';

				$location.path('projects/' + response._id);

			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});

		};

		// Remove existing Project
		$scope.remove = function( project ) {
			if ( project ) { project.$remove();

				for (var i in $scope.projects ) {
					if ($scope.projects [i] === project ) {
						$scope.projects.splice(i, 1);
					}
				}
			} else {
				$scope.project.$remove(function() {
					$location.path('projects');
				});
			}
		};

		$scope.CombineStandards = function(){
			$scope.project.essentialDetails.overallStandards = $scope.project.essentialDetails.litDetails[0].standards + ', ' + $scope.project.essentialDetails.mathDetails[0].standards + ', ' + $scope.project.essentialDetails.scienceDetails[0].standards + ', ' + $scope.project.essentialDetails.ssDetails[0].standards;
		};

		// Update existing Project
		$scope.update = function() {
            console.log('In $scope.update');

			var project = $scope.project;

			project.imagine.plan = '';

			project.$update(function() {

				$location.path('projects/' + project._id);
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});

			if ($scope.uploader.queue.length > 0) {
				$scope.uploader.queue[0].url = '/api/projects/picture/' + project._id;
				$scope.uploader.uploadAll();
			}
		};

		// Find a list of Projects
		$scope.find = function() {
			$scope.projects = Projects.query();
		};

		// Find existing Project
		$scope.findOne = function() {
			$scope.project = Projects.get({
				projectId: $stateParams.projectId
			});

		};

		// Called after the user selected a new picture file
		$scope.uploader.onAfterAddingFile = function (fileItem) {
			if ($window.FileReader) {
				var fileReader = new FileReader();
				fileReader.readAsDataURL(fileItem._file);

				fileReader.onload = function (fileReaderEvent) {
					$timeout(function () {
						$scope.project.imagine.plan = fileReaderEvent.target.result;
					}, 0);
				};
			}
		};

		$scope.linkify = function(link) {
			return $sce.trustAsHtml(linkify.normal(link));
		};

		$scope.uploaderC.onAfterAddingFile = function (fileItem) {
			if ($window.FileReader) {
				var fileReader = new FileReader();
				fileReader.readAsDataURL(fileItem._file);

				fileReader.onload = function (fileReaderEvent) {
					$timeout(function () {
						$scope.imageURL = fileReaderEvent.target.result;
					}, 0);
				};
			}
		};

/*	-------------------------------------Star Rating Stuff-------------------------------------- */

		//an array containing the name of the glyphicon to use for each star
		$scope.glyphs = new Array(
			'gold glyphicon glyphicon-star-empty',
			'gold glyphicon glyphicon-star-empty',
			'gold glyphicon glyphicon-star-empty',
			'gold glyphicon glyphicon-star-empty',
			'gold glyphicon glyphicon-star-empty'
		);

		/*
			Runs when a star glyphicon is hovered into. It sets all the stars up to the current one
			to have the filled-in star glyphicon.
		*/
		$scope.rating_hover = function(num){
			for(var i = 0; i < num; i++){
				$scope.glyphs[i] = 'gold glyphicon glyphicon-star';
			}
			for(i = num; i < 5; i++){
				$scope.glyphs[i] = 'gold glyphicon glyphicon-star-empty';
			}
		};

		//Runs when a star glyphicon is hovered out of. Resets the  stars' highlighing to the current rating
		$scope.reset_hover = function(){
			$scope.rating_hover($scope.rating);
		};

		//Prints out user's current rating of the project
		$scope.getMyRating = function(){

			if ($scope.project.rating && $scope.project.rating.ratings ){
				var rater = $scope.project.rating.ratings.filter(isRater)[0];
				console.log(rater);
				if (typeof rater === 'undefined'){
					$scope.rating = 0;	//current rating
					return 'You haven\'t yet rated this project. Give it a couple of stars?';
				}
				$scope.rating = rater.num;
				$scope.reset_hover();
				return ('Your currently rate this project at ' + rater.num + ' stars');
			}
			$scope.rating = 0;	//current rating
			return 'This project has not yet been rated. Give it a couple of stars?';

		};

        // Function to find the current rater
        var isRater = function(value){
			return value.reviewer === $scope.authentication.user._id;
        };

		//Changes the user's rating of the project
		$scope.rate = function(){
			console.log('In $scope.rate');
			if(!$scope.project.rating){
				$scope.project.rating = {
					ratings : [
						{
							num: $scope.rating,
							reviewer: $scope.authentication.user._id
						}
					],
					avg_rating : $scope.rating
				};
			} else {
                var rater = $scope.project.rating.ratings.filter(isRater)[0];
                var length = $scope.project.rating.ratings.length;
				var rateToRemove = 0;

                var newLength = length + 1;

                if(length === 0)
                {
                    $scope.project.rating.avg_rating = 0;
                }

				if(typeof rater !== 'undefined') {
                    rateToRemove = rater.num;
                    var rateIndex = $scope.project.rating.ratings.indexOf(rater);
                    $scope.project.rating.ratings.splice(rateIndex, 1);
                    newLength -= 1;
                }

				$scope.project.rating.avg_rating = ($scope.project.rating.avg_rating * length + $scope.rating - rateToRemove)/(newLength);

				$scope.project.rating.ratings.push({
						num: $scope.rating,
						reviewer: $scope.authentication.user._id
				});
			}
			$scope.update();

		};

	}
]);
<|endoftext|>