<commit_before>/*
 * HOMER 5 UI (Xenophon)
 *
 * Copyright (C) 2011-2015 Alexandr Dubovikov <alexandr.dubovikov@gmail.com>
 * Copyright (C) 2011-2015 Lorenzo Mangani <lorenzo.mangani@gmail.com> QXIP B.V.
 * License AGPL-3.0 http://opensource.org/licenses/AGPL-3.0
 *
*/

'use strict';

angular.module('homer.widgets.adminalias', ['adf.provider'])
  .value('adminaliasServiceUrl', 'api/admin/alias')
  .config(function(dashboardProvider){
    dashboardProvider
      .widget('adminalias', {
        title: 'Admin Alias',
        description: 'Alias admin',
        templateUrl: 'js/widgets/adminalias/adminalias.html',
        controller: 'adminaliasCtrl',
        resolve: {
          aliases: function(adminaliasService, config){
              return adminaliasService.get();
          }
        },
        edit: {
          templateUrl: 'js/widgets/adminalias/edit.html'
        }
      });
  })
  .service('adminaliasService', function($q, $http, adminaliasServiceUrl){
    return {
      get: function(){
        var deferred = $q.defer();
        $http.get(adminaliasServiceUrl+"/get")
          .success(function(data){
            if (data && data.data){
              deferred.resolve(data.data);
            } else {
              deferred.reject();
            }
          })
          .error(function(){
            deferred.reject();
          });

        return deferred.promise;
      },
      save: function(ldata){
        var deferred = $q.defer();
        console.log(ldata);
        $http.post(adminaliasServiceUrl+"/new", ldata)
          .success(function(data){
            if (data && data.data){
              deferred.resolve(data.data);
            } else {
              deferred.reject();
            }
          })
          .error(function(){
            deferred.reject();
          });

        return deferred.promise;
      },
      update: function(ldata){
        var deferred = $q.defer();
        console.log(ldata);
        $http.post(adminaliasServiceUrl+"/edit", ldata)
          .success(function(data){
            if (data && data.data){
              deferred.resolve(data.data);
            } else {
              deferred.reject();
            }
          })
          .error(function(){
            deferred.reject();
          });

        return deferred.promise;
      },
      delete: function($id){
        var deferred = $q.defer();
        $http.delete(adminaliasServiceUrl+"/delete/"+$id)
          .success(function(data){
            if (data && data.data){
              deferred.resolve(data.data);
            } else {
              deferred.reject();
            }
          })
          .error(function(){
            deferred.reject();
          });

        return deferred.promise;
      }
    };
  })
  .controller('adminaliasCtrl', function($scope, aliases, dialogs, adminaliasService, $timeout, $window, SweetAlert){

    // TAB FUNCTIONS DEFAULTS
    $scope.showtable = true;
    $scope.inactiveTab = false;
    $scope.activeTab = true; $scope.editTab = false; $scope.newTab = false;
    $scope.activeMainTab = true;
    $scope.disabled = false;

    $scope.removeAliasTab = function (index) {
        $scope.activeTab = true;
    	$scope.activeMainTab = true;
    	$scope.editTab = false;
    	$scope.newTab = false;
    	$scope.activeNewTab = false;
    	$scope.tabShown = true;
    };

    $scope.newAlias = function() {
      	 $scope.newalias = [];
      	 $scope.activeTab = false;
      	 $scope.activeNewTab = true;
      	 $scope.editTab = false;
      	 $scope.newTab = true;
      	 $scope.activeMainTab = false;
     	 $scope.tabShown = false;
    };
    $scope.editAlias = function() {
      	 $scope.newalias = [];
      	 $scope.activeTab = false;
      	 $scope.activeNewTab = true;
      	 $scope.editTab = true;
      	 $scope.newTab = false;
      	 $scope.activeMainTab = false;
     	$scope.tabShown = false;

    };

    $scope.addNewAlias = function() {

	$scope.errorNewAliasShow = false;
        $scope.removeAliasTab();

	var ldata = {};
        ldata['param'] = {
		gid: 10,
		ip: $scope.newalias.ip,
		port: $scope.newalias.port,
		alias: $scope.newalias.alias,
		status: $scope.newalias.status
        };

        adminaliasService.save(ldata).then(function (mdata) {
		$scope.gridOptions.data.length = 0;
		$timeout(function(){
			$scope.gridOptions.data = mdata;
		});
        });
    };

    $scope.doEditAlias = function() {

                console.log("Edit USER");
                $scope.editTab = false;
                $scope.newTab = false;
                $scope.activeNewTab = false;
                $scope.activeMainTab = true;
                $scope.activeTab = true;
                $scope.errorEditAliasShow = false;
                $scope.tabShown = true;

                var id = $scope.arec.id;

                var ldata = {};
                ldata['param'] = {
                    gid: 10,
                    ip: $scope.arec.ip,
                    port: $scope.arec.port,
                    alias: $scope.arec.alias,
                    status: $scope.arec.status,
                    id: id
                };

                adminaliasService.update(ldata).then(function (mdata) {
			$scope.gridOptions.data.length = 0;
			$timeout(function(){
				$scope.gridOptions.data = mdata;
			});
                });

    };

    $scope.doDeleteAlias = function() {

        console.log("Delete USER");

	 SweetAlert.swal({
                title: "Are you sure?",
                text: "Your will not be able to recover this!",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "Yes, delete it!",
                closeOnConfirm: true,
                closeOnCancel: true
                },
                function(isConfirm){

                        if(isConfirm)
                        {
                                $scope.editTab = false;
                                $scope.newTab = false;
                                $scope.activeNewTab = false;
                                $scope.activeMainTab = true;
                                $scope.activeTab = true;
                                $scope.tabShown = true;

			        var id = $scope.alias.id;

				adminaliasService.delete(id).then(function (mdata) {
					$scope.gridOptions.data.length = 0;
					$timeout(function(){
						$scope.gridOptions.data = mdata;
					});
	        		});

                                $scope.removeAlarmTab();
                        }
                }
        );

    };

    $scope.gridOptions = {
	showFooter: false,
	enableSorting: true,
	enableFiltering: true,
	multiSelect: false,
	enableRowSelection: false,
	enableSelectAll: false,
	enableRowHeaderSelection: false,
	rowTemplate: "

",
	noUnselect: true
    };

    $scope.gridOptions.rowIdentity = function(row) {
          return row.id;
    };

    $scope.gridOptions.onRegisterApi = function(gridApi){
                //set gridApi on scope
                $scope.gridApi = gridApi;
    };

    $scope.onDblClickRow = function(rowItem) {
	    // tab management
	    $scope.editTab = true;
    	    $scope.activeTab = false;
    	    $scope.newTab = false;
    	    $scope.arec = rowItem.entity;
    };

    $scope.Delete = function(row) {
	// console.log('ADM-ROW_DEL');
          var index = $scope.gridOptions.data.indexOf(row.entity);
          $scope.gridOptions.data.splice(index, 1);
    };

    $scope.gridOptions.columnDefs = [
		{ name: 'id', enableCellEdit: false, width: 50 },
		{ name: 'alias', displayName: 'Alias' },
		{ name: 'gid', width: 50 },
		{ name: 'ip', displayName: 'IP' },
		{ name: 'port', displayName: 'Port' },
		{ name: 'status', displayName: 'status' },
		{ name: 'created', displayName: 'Created' , type: 'date', cellFilter: 'date:"yyyy-MM-dd"'}
      ];

      $scope.gridOptions.data = aliases;

  });
<commit_msg>UI::Alias client side fixes<commit_after>/*
 * HOMER 5 UI (Xenophon)
 *
 * Copyright (C) 2011-2015 Alexandr Dubovikov <alexandr.dubovikov@gmail.com>
 * Copyright (C) 2011-2015 Lorenzo Mangani <lorenzo.mangani@gmail.com> QXIP B.V.
 * License AGPL-3.0 http://opensource.org/licenses/AGPL-3.0
 *
*/

'use strict';

angular.module('homer.widgets.adminalias', ['adf.provider'])
  .value('adminaliasServiceUrl', 'api/admin/alias')
  .config(function(dashboardProvider){
    dashboardProvider
      .widget('adminalias', {
        title: 'Admin Alias',
        description: 'Alias admin',
        templateUrl: 'js/widgets/adminalias/adminalias.html',
        controller: 'adminaliasCtrl',
        resolve: {
          aliases: function(adminaliasService, config){
              return adminaliasService.get();
          }
        },
        edit: {
          templateUrl: 'js/widgets/adminalias/edit.html'
        }
      });
  })
  .service('adminaliasService', function($q, $http, adminaliasServiceUrl){
    return {
      get: function(){
        var deferred = $q.defer();
        $http.get(adminaliasServiceUrl+"/get")
          .success(function(data){
            if (data && data.data){
              deferred.resolve(data.data);
            } else {
              deferred.reject();
            }
          })
          .error(function(){
            deferred.reject();
          });

        return deferred.promise;
      },
      save: function(ldata){
        var deferred = $q.defer();
        console.log(ldata);
        $http.post(adminaliasServiceUrl+"/new", ldata)
          .success(function(data){
            if (data && data.data){
              deferred.resolve(data.data);
            } else {
              deferred.reject();
            }
          })
          .error(function(){
            deferred.reject();
          });

        return deferred.promise;
      },
      update: function(ldata){
        var deferred = $q.defer();
        console.log(ldata);
        $http.post(adminaliasServiceUrl+"/edit", ldata)
          .success(function(data){
            if (data && data.data){
              deferred.resolve(data.data);
            } else {
              deferred.reject();
            }
          })
          .error(function(){
            deferred.reject();
          });

        return deferred.promise;
      },
      delete: function($id){
        var deferred = $q.defer();
        $http.delete(adminaliasServiceUrl+"/delete/"+$id)
          .success(function(data){
            if (data && data.data){
              deferred.resolve(data.data);
            } else {
              deferred.reject();
            }
          })
          .error(function(){
            deferred.reject();
          });

        return deferred.promise;
      }
    };
  })
  .controller('adminaliasCtrl', function($scope, aliases, dialogs, adminaliasService, $timeout, $window, SweetAlert){

    // TAB FUNCTIONS DEFAULTS
    $scope.showtable = true;
    $scope.inactiveTab = false;
    $scope.activeTab = true; $scope.editTab = false; $scope.newTab = false;
    $scope.activeMainTab = true;
    $scope.disabled = false;

    $scope.removeAliasTab = function (index) {
        $scope.activeTab = true;
    	$scope.activeMainTab = true;
    	$scope.editTab = false;
    	$scope.newTab = false;
    	$scope.activeNewTab = false;
    	$scope.tabShown = true;
    };

    $scope.newAlias = function() {
      	 $scope.newalias = [];
      	 $scope.activeTab = false;
      	 $scope.activeNewTab = true;
      	 $scope.editTab = false;
      	 $scope.newTab = true;
      	 $scope.activeMainTab = false;
     	 $scope.tabShown = false;
    };
    $scope.editAlias = function() {
      	 $scope.newalias = [];
      	 $scope.activeTab = false;
      	 $scope.activeNewTab = true;
      	 $scope.editTab = true;
      	 $scope.newTab = false;
      	 $scope.activeMainTab = false;
     	$scope.tabShown = false;

    };

    $scope.addNewAlias = function() {

	$scope.errorNewAliasShow = false;
        $scope.removeAliasTab();

	var ldata = {};
        ldata['param'] = {
		gid: 10,
		ip: $scope.newalias.ip,
		port: $scope.newalias.port,
		alias: $scope.newalias.alias,
		status: $scope.newalias.status
        };

        adminaliasService.save(ldata).then(function (mdata) {
		$scope.gridOptions.data.length = 0;
		$timeout(function(){
			$scope.gridOptions.data = mdata;
		});
        });
    };

    $scope.doEditAlias = function() {

                console.log("Edit ALIAS");
                $scope.editTab = false;
                $scope.newTab = false;
                $scope.activeNewTab = false;
                $scope.activeMainTab = true;
                $scope.activeTab = true;
                $scope.errorEditAliasShow = false;
                $scope.tabShown = true;

                var id = $scope.arec.id;

                var ldata = {};
                ldata['param'] = {
                    gid: 10,
                    ip: $scope.arec.ip,
                    port: $scope.arec.port,
                    alias: $scope.arec.alias,
                    status: $scope.arec.status,
                    id: id
                };

                adminaliasService.update(ldata).then(function (mdata) {
			$scope.gridOptions.data.length = 0;
			$timeout(function(){
				$scope.gridOptions.data = mdata;
			});
                });

    };

    $scope.doDeleteAlias = function() {

        console.log("Delete ALIAS");

	 SweetAlert.swal({
                title: "Are you sure?",
                text: "Your will not be able to recover this!",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "Yes, delete it!",
                closeOnConfirm: true,
                closeOnCancel: true
                },
                function(isConfirm){

                        if(isConfirm)
                        {
                                $scope.editTab = false;
                                $scope.newTab = false;
                                $scope.activeNewTab = false;
                                $scope.activeMainTab = true;
                                $scope.activeTab = true;
                                $scope.tabShown = true;

			        var id = $scope.arec.id;

				adminaliasService.delete(id).then(function (mdata) {
					$scope.gridOptions.data.length = 0;
					$timeout(function(){
						$scope.gridOptions.data = mdata;
					});
	        		});

                                $scope.removeAliasTab();
                        }
                }
        );

    };

    $scope.gridOptions = {
	showFooter: false,
	enableSorting: true,
	enableFiltering: true,
	multiSelect: false,
	enableRowSelection: false,
	enableSelectAll: false,
	enableRowHeaderSelection: false,
	rowTemplate: "

",
	noUnselect: true
    };

    $scope.gridOptions.rowIdentity = function(row) {
          return row.id;
    };

    $scope.gridOptions.onRegisterApi = function(gridApi){
                //set gridApi on scope
                $scope.gridApi = gridApi;
    };

    $scope.onDblClickRow = function(rowItem) {
	    // tab management
	    $scope.editTab = true;
    	    $scope.activeTab = false;
    	    $scope.newTab = false;
    	    $scope.arec = rowItem.entity;
    };

    $scope.Delete = function(row) {
	// console.log('ADM-ROW_DEL');
          var index = $scope.gridOptions.data.indexOf(row.entity);
          $scope.gridOptions.data.splice(index, 1);
    };

    $scope.gridOptions.columnDefs = [
		{ name: 'id', enableCellEdit: false, width: 50 },
		{ name: 'alias', displayName: 'Alias' },
		{ name: 'gid', width: 50 },
		{ name: 'ip', displayName: 'IP' },
		{ name: 'port', displayName: 'Port' },
		{ name: 'status', displayName: 'status' },
		{ name: 'created', displayName: 'Created' , type: 'date', cellFilter: 'date:"yyyy-MM-dd"'}
      ];

      $scope.gridOptions.data = aliases;

  });
<|endoftext|>


<commit_before>(function(angular){
    'use strict';
    var app = angular.module('dashboard.controllers', []);

    app.controller('DashboardCtrl', ['$scope', 'CourseStudent', 'Topic',
        function ($scope, CourseStudent, Topic) {
            CourseStudent.query({}, function(my_courses){
                if (my_courses.length > 2) {
                    $scope.my_courses = my_courses.slice(0, 2);
                } else {
                    $scope.my_courses = my_courses;
                }
            });
            $scope.latest_topics = Topic.query({limit: 12, ordering: 'updated_at'})
        }
    ]);

})(window.angular);<commit_msg>chage topic number in dashboard<commit_after>(function(angular){
    'use strict';
    var app = angular.module('dashboard.controllers', []);

    app.controller('DashboardCtrl', ['$scope', 'CourseStudent', 'Topic',
        function ($scope, CourseStudent, Topic) {
            CourseStudent.query({}, function(my_courses){
                if (my_courses.length > 2) {
                    $scope.my_courses = my_courses.slice(0, 2);
                } else {
                    $scope.my_courses = my_courses;
                }
            });
            $scope.latest_topics = Topic.query({limit: 8, ordering: 'updated_at'})
        }
    ]);

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


<commit_before>hqDefine('cloudcare/js/util', function () {
    if (!String.prototype.startsWith) {
        String.prototype.startsWith = function (searchString, position) {
            position = position || 0;
            return this.indexOf(searchString, position) === position;
        };
    }

    NProgress.configure({
        showSpinner: false,
    });

    var getFormUrl = function (urlRoot, appId, moduleId, formId, instanceId) {
        // TODO: make this cleaner
        var url = urlRoot + "view/" + appId + "/modules-" + moduleId + "/forms-" + formId + "/context/";
        if (instanceId) {
            url += '?instance_id=' + instanceId;
        }
        return url;
    };

    var getSubmitUrl = function (urlRoot, appId) {
        // deprecated but still called from "touchforms-inline"
        // which is used to fill out forms from within case details view
        // use app.getSubmitUrl instead
        // todo: replace and remove
        return urlRoot + "/" + appId + "/";
    };

    var showError = function (message, $el) {
        if (message === undefined) {
            message = gettext("Sorry, an error occurred while processing that request.");
        }
        _show(message, $el, null, "alert alert-danger");
        reportFormplayerErrorToHQ({
            type: 'show_error_notification',
            message: message,
        });

    };

    var showWarning = function (message, $el) {
        if (message === undefined) {
            return;
        }
        _show(message, $el, 5000, "alert alert-warning");
    };

    var showHTMLError = function (message, $el, autoHideTime) {
        message = message || gettext("Sorry, an error occurred while processing that request.");
        _show(message, $el, autoHideTime, "", true);
        reportFormplayerErrorToHQ({
            type: 'show_error_notification',
            message: message,
        });
    };

    var showSuccess = function (message, $el, autoHideTime, isHTML) {
        if (message === undefined) {
            message = "Success";
        }
        return _show(message, $el, autoHideTime, "alert alert-success", isHTML);
    };

    var _show = function (message, $el, autoHideTime, classes, isHTML) {
        var $container = $("<div />"),
            $alertDialog;
        $container.addClass(classes);
        if (isHTML) {
            $container.html(message);
        } else {
            $container.text(message);
        }
        // HTML errors may already have an alert dialog
        $alertDialog = $container.hasClass("alert") ? $container : $container.find('.alert');
        $alertDialog
            .prepend(
                $("<a />")
                    .addClass("close")
                    .attr("data-dismiss", "alert")
                    .html("×")
            );
        $el.append($container);
        if (autoHideTime) {
            $container.delay(autoHideTime).fadeOut(500);
        }
        return $container;
    };

    var showLoading = function (selector) {
        NProgress.start();
    };

    var formplayerLoading = function (selector) {
        showLoading();
    };

    var formplayerLoadingComplete = function (isError, message) {
        hideLoading();
        if (isError) {
            showError(message || gettext('Error saving!'), $('#cloudcare-notifications'));
        }
    };

    var formplayerSyncComplete = function (isError) {
        hideLoading();
        if (isError) {
            showError(
                gettext('Could not sync user data. Please report an issue if this persists.'),
                $('#cloudcare-notifications')
            );
        } else {
            showSuccess(gettext('User Data successfully synced.'), $('#cloudcare-notifications'), 5000);
        }
    };

    var clearUserDataComplete = function (isError) {
        hideLoading();
        if (isError) {
            showError(
                gettext('Could not clear user data. Please report an issue if this persists.'),
                $('#cloudcare-notifications')
            );
        } else {
            showSuccess(gettext('User data successfully cleared.'), $('#cloudcare-notifications'), 5000);
        }
    };

    var hideLoading = function (selector) {
        NProgress.done();
    };

    var reportFormplayerErrorToHQ = function (data) {
        try {
            var reverse = hqImport("hqwebapp/js/initial_page_data").reverse;

            $.ajax({
                type: 'POST',
                url: reverse('report_formplayer_error'),
                data: JSON.stringify(data),
                contentType: "application/json",
                dataType: "json",
                success: function () {
                    window.console.info('Successfully reported error: ' + JSON.stringify(data));
                },
                error: function () {
                    window.console.error('Failed to report error: ' + JSON.stringify(data));
                },
            });
        } catch (e) {
            window.console.error(
                "reportFormplayerErrorToHQ failed hard and there is nowhere " +
                "else to report this error: " + JSON.stringify(data),
                e
            );
        }
    };

    return {
        getFormUrl: getFormUrl,
        getSubmitUrl: getSubmitUrl,
        showError: showError,
        showWarning: showWarning,
        showHTMLError: showHTMLError,
        showSuccess: showSuccess,
        clearUserDataComplete: clearUserDataComplete,
        formplayerLoading: formplayerLoading,
        formplayerLoadingComplete: formplayerLoadingComplete,
        formplayerSyncComplete: formplayerSyncComplete,
        reportFormplayerErrorToHQ: reportFormplayerErrorToHQ,
    };
});
<commit_msg>extend visibility of volatility warning based on user feedback<commit_after>hqDefine('cloudcare/js/util', function () {
    if (!String.prototype.startsWith) {
        String.prototype.startsWith = function (searchString, position) {
            position = position || 0;
            return this.indexOf(searchString, position) === position;
        };
    }

    NProgress.configure({
        showSpinner: false,
    });

    var getFormUrl = function (urlRoot, appId, moduleId, formId, instanceId) {
        // TODO: make this cleaner
        var url = urlRoot + "view/" + appId + "/modules-" + moduleId + "/forms-" + formId + "/context/";
        if (instanceId) {
            url += '?instance_id=' + instanceId;
        }
        return url;
    };

    var getSubmitUrl = function (urlRoot, appId) {
        // deprecated but still called from "touchforms-inline"
        // which is used to fill out forms from within case details view
        // use app.getSubmitUrl instead
        // todo: replace and remove
        return urlRoot + "/" + appId + "/";
    };

    var showError = function (message, $el) {
        if (message === undefined) {
            message = gettext("Sorry, an error occurred while processing that request.");
        }
        _show(message, $el, null, "alert alert-danger");
        reportFormplayerErrorToHQ({
            type: 'show_error_notification',
            message: message,
        });

    };

    var showWarning = function (message, $el) {
        if (message === undefined) {
            return;
        }
        _show(message, $el, 30000, "alert alert-warning");
    };

    var showHTMLError = function (message, $el, autoHideTime) {
        message = message || gettext("Sorry, an error occurred while processing that request.");
        _show(message, $el, autoHideTime, "", true);
        reportFormplayerErrorToHQ({
            type: 'show_error_notification',
            message: message,
        });
    };

    var showSuccess = function (message, $el, autoHideTime, isHTML) {
        if (message === undefined) {
            message = "Success";
        }
        return _show(message, $el, autoHideTime, "alert alert-success", isHTML);
    };

    var _show = function (message, $el, autoHideTime, classes, isHTML) {
        var $container = $("<div />"),
            $alertDialog;
        $container.addClass(classes);
        if (isHTML) {
            $container.html(message);
        } else {
            $container.text(message);
        }
        // HTML errors may already have an alert dialog
        $alertDialog = $container.hasClass("alert") ? $container : $container.find('.alert');
        $alertDialog
            .prepend(
                $("<a />")
                    .addClass("close")
                    .attr("data-dismiss", "alert")
                    .html("×")
            );
        $el.append($container);
        if (autoHideTime) {
            $container.delay(autoHideTime).fadeOut(500);
        }
        return $container;
    };

    var showLoading = function (selector) {
        NProgress.start();
    };

    var formplayerLoading = function (selector) {
        showLoading();
    };

    var formplayerLoadingComplete = function (isError, message) {
        hideLoading();
        if (isError) {
            showError(message || gettext('Error saving!'), $('#cloudcare-notifications'));
        }
    };

    var formplayerSyncComplete = function (isError) {
        hideLoading();
        if (isError) {
            showError(
                gettext('Could not sync user data. Please report an issue if this persists.'),
                $('#cloudcare-notifications')
            );
        } else {
            showSuccess(gettext('User Data successfully synced.'), $('#cloudcare-notifications'), 5000);
        }
    };

    var clearUserDataComplete = function (isError) {
        hideLoading();
        if (isError) {
            showError(
                gettext('Could not clear user data. Please report an issue if this persists.'),
                $('#cloudcare-notifications')
            );
        } else {
            showSuccess(gettext('User data successfully cleared.'), $('#cloudcare-notifications'), 5000);
        }
    };

    var hideLoading = function (selector) {
        NProgress.done();
    };

    var reportFormplayerErrorToHQ = function (data) {
        try {
            var reverse = hqImport("hqwebapp/js/initial_page_data").reverse;

            $.ajax({
                type: 'POST',
                url: reverse('report_formplayer_error'),
                data: JSON.stringify(data),
                contentType: "application/json",
                dataType: "json",
                success: function () {
                    window.console.info('Successfully reported error: ' + JSON.stringify(data));
                },
                error: function () {
                    window.console.error('Failed to report error: ' + JSON.stringify(data));
                },
            });
        } catch (e) {
            window.console.error(
                "reportFormplayerErrorToHQ failed hard and there is nowhere " +
                "else to report this error: " + JSON.stringify(data),
                e
            );
        }
    };

    return {
        getFormUrl: getFormUrl,
        getSubmitUrl: getSubmitUrl,
        showError: showError,
        showWarning: showWarning,
        showHTMLError: showHTMLError,
        showSuccess: showSuccess,
        clearUserDataComplete: clearUserDataComplete,
        formplayerLoading: formplayerLoading,
        formplayerLoadingComplete: formplayerLoadingComplete,
        formplayerSyncComplete: formplayerSyncComplete,
        reportFormplayerErrorToHQ: reportFormplayerErrorToHQ,
    };
});
<|endoftext|>


<commit_before>hqDefine("groups/js/all_groups.js", function() {
    $(function () {
        var $createGroupForm = $("#create_group_form");
        debugger;
        $("button:submit", $createGroupForm).click(function(){
            ga_track_event("Groups", "Create Group", {
               'hitCallback': function () {
                   $createGroupForm.submit();
               }
            });
            return false;
        });
    });
});
<commit_msg>Remove stray debugger<commit_after>hqDefine("groups/js/all_groups.js", function() {
    $(function () {
        var $createGroupForm = $("#create_group_form");
        $("button:submit", $createGroupForm).click(function(){
            ga_track_event("Groups", "Create Group", {
               'hitCallback': function () {
                   $createGroupForm.submit();
               }
            });
            return false;
        });
    });
});
<|endoftext|>


<commit_before>BEST.module('famous:core:ui-element', {
    tree: 'ui-element.html',
    behaviors: {
        '#view' : {
            'align': function(align) {
                return align;
            },
            'align-x': function(alignX) {
                return alignX;
            },
            'align-y': function(alignY) {
                return alignY;
            },
            'align-z': function(alignZ) {
                return alignZ;
            },
            'mount-point': function(mountPoint) {
                return mountPoint;
            },
            'mount-point-x': function(mountPointX) {
                return mountPointX;
            },
            'mount-point-y': function(mountPointY) {
                return mountPointY;
            },
            'mount-point-z': function(mountPointZ) {
                return mountPointZ;
            },
            'opacity': function(opacity) {
                return opacity;
            },
            'origin': function(origin) {
                return origin;
            },
            'origin-x': function(originX) {
                return originX;
            },
            'origin-y': function(originY) {
                return originY;
            },
            'origin-z': function(originZ) {
                return originZ;
            },
            'position': function(position) {
                return position;
            },
            'position-x': function(positionX) {
                return(positionX);
            },
            'position-y': function(positionY) {
                return positionY;
            },
            'position-z': function(positionZ) {
                return positionZ;
            },
            'offset-position': function(offsetPosition) {
                return offsetPosition;
            },
            'rotation': function(rotation) {
                return rotation;
            },
            'rotation-x': function(rotationX) {
                return rotationX;
            },
            'rotation-y': function(rotationY) {
                return rotationY;
            },
            'rotation-z': function(rotationZ) {
                return rotationZ;
            },
            'scale': function(scale) {
                return scale;
            },
            'scale-x': function(scaleX) {
                return scaleX;
            },
            'scale-y': function(scaleY) {
                return scaleY;
            },
            'scale-z': function(scaleZ) {
                return scaleZ;
            },
            'size': function(size) {
                return size;
            },
            'size-absolute': function(sizeAbsolute) {
                return sizeAbsolute;
            },
            'size-absolute-x': function(sizeAbsoluteX) {
                return sizeAbsoluteX;
            },
            'size-absolute-y': function(sizeAbsoluteY) {
                return sizeAbsoluteY;
            },
            'size-absolute-z': function(sizeAbsoluteZ) {
                return sizeAbsoluteZ;
            },
            'size-proportional': function(sizeProportional) {
                return sizeProportional;
            },
            'size-proportional-x': function(sizeProportionalX) {
                return sizeProportionalX;
            },
            'size-proportional-y': function(sizeProportionalY) {
                return sizeProportionalY;
            },
            'size-proportional-z': function(sizeProportionalZ) {
                return sizeProportionalZ;
            },
            'size-differential': function(sizeDiffential) {
                return sizeDiffential;
            },
            'size-differential-x': function(sizeDiffentialX) {
                return sizeDiffentialX;
            },
            'size-differential-y': function(sizeDiffentialY) {
                return sizeDiffentialY;
            },
            'size-differential-z': function(sizeDiffentialZ) {
                return sizeDiffentialZ;
            },
            'overflow' : function(overflow) {
                return overflow;
            },
            'border' : function(border) {
                return border;
            }
        },
        '#element' : {
            '$yield' : true,
            'id': function(id) {
                return id;
            },
            'content': function(content) {
                return content;
            },
            'style': function(style) {
                return style;
            },
            'attributes': function(attributes) {
                return attributes;
            },
            'unselectable': function(unselectable) {
                return unselectable;
            },
            'backface-visible': function(backfaceVisible) {
                return backfaceVisible;
            },
            'box-shadow': function(boxShadow) {
                return boxShadow;
            },
            'template': function(template) {
                return template;
            }
        }
    },
    events: {
        '$public': {
            // famous:core:view events
            'align': 'setter',
            'align-x': 'setter|camel',
            'align-y': 'setter|camel',
            'align-z': 'setter|camel',
            'mount-point': 'setter|camel',
            'mount-point-x': 'setter|camel',
            'mount-point-y': 'setter|camel',
            'mount-point-z': 'setter|camel',
            'opacity': 'setter',
            'origin': 'setter',
            'origin-x': 'setter|camel',
            'origin-y': 'setter|camel',
            'origin-z': 'setter|camel',
            'position': 'setter',
            'position-x': 'setter|camel',
            'position-y': 'setter|camel',
            'position-z': 'setter|camel',
            'offset-position' : 'setter|camel',
            'rotation': 'setter',
            'rotation-x': 'setter|camel',
            'rotation-y': 'setter|camel',
            'rotation-z': 'setter|camel',
            'scale': 'setter',
            'scale-x': 'setter|camel',
            'scale-y': 'setter|camel',
            'scale-z': 'setter|camel',
            'size': 'setter',
            'size-absolute': 'setter|camel',
            'size-absolute-x': 'setter|camel',
            'size-absolute-y': 'setter|camel',
            'size-absolute-z': 'setter|camel',
            'size-proportional': 'setter|camel',
            'size-proportional-x': 'setter|camel',
            'size-proportional-y': 'setter|camel',
            'size-proportional-z': 'setter|camel',
            'size-differential': 'setter|camel',
            'size-differential-x': 'setter|camel',
            'size-differential-y': 'setter|camel',
            'size-differential-z': 'setter|camel',
            'overflow' : 'setter',
            'border' : 'setter',

            // famous:core:dom-element events
            'id': 'setter',
            'content': 'setter',
            'style': 'setter',
            'attributes': 'setter',
            'unselectable': 'setter',
            'backface-visible': 'setter|camel',
            'box-shadow': 'setter|camel',
            'template': 'setter'
        }
    }
});
<commit_msg>Add ui-events to ui-element<commit_after>BEST.module('famous:core:ui-element', {
    tree: 'ui-element.html',
    behaviors: {
        '#view' : {
            'align': function(align) {
                return align;
            },
            'align-x': function(alignX) {
                return alignX;
            },
            'align-y': function(alignY) {
                return alignY;
            },
            'align-z': function(alignZ) {
                return alignZ;
            },
            'mount-point': function(mountPoint) {
                return mountPoint;
            },
            'mount-point-x': function(mountPointX) {
                return mountPointX;
            },
            'mount-point-y': function(mountPointY) {
                return mountPointY;
            },
            'mount-point-z': function(mountPointZ) {
                return mountPointZ;
            },
            'opacity': function(opacity) {
                return opacity;
            },
            'origin': function(origin) {
                return origin;
            },
            'origin-x': function(originX) {
                return originX;
            },
            'origin-y': function(originY) {
                return originY;
            },
            'origin-z': function(originZ) {
                return originZ;
            },
            'position': function(position) {
                return position;
            },
            'position-x': function(positionX) {
                return(positionX);
            },
            'position-y': function(positionY) {
                return positionY;
            },
            'position-z': function(positionZ) {
                return positionZ;
            },
            'offset-position': function(offsetPosition) {
                return offsetPosition;
            },
            'rotation': function(rotation) {
                return rotation;
            },
            'rotation-x': function(rotationX) {
                return rotationX;
            },
            'rotation-y': function(rotationY) {
                return rotationY;
            },
            'rotation-z': function(rotationZ) {
                return rotationZ;
            },
            'scale': function(scale) {
                return scale;
            },
            'scale-x': function(scaleX) {
                return scaleX;
            },
            'scale-y': function(scaleY) {
                return scaleY;
            },
            'scale-z': function(scaleZ) {
                return scaleZ;
            },
            'size': function(size) {
                return size;
            },
            'size-absolute': function(sizeAbsolute) {
                return sizeAbsolute;
            },
            'size-absolute-x': function(sizeAbsoluteX) {
                return sizeAbsoluteX;
            },
            'size-absolute-y': function(sizeAbsoluteY) {
                return sizeAbsoluteY;
            },
            'size-absolute-z': function(sizeAbsoluteZ) {
                return sizeAbsoluteZ;
            },
            'size-proportional': function(sizeProportional) {
                return sizeProportional;
            },
            'size-proportional-x': function(sizeProportionalX) {
                return sizeProportionalX;
            },
            'size-proportional-y': function(sizeProportionalY) {
                return sizeProportionalY;
            },
            'size-proportional-z': function(sizeProportionalZ) {
                return sizeProportionalZ;
            },
            'size-differential': function(sizeDiffential) {
                return sizeDiffential;
            },
            'size-differential-x': function(sizeDiffentialX) {
                return sizeDiffentialX;
            },
            'size-differential-y': function(sizeDiffentialY) {
                return sizeDiffentialY;
            },
            'size-differential-z': function(sizeDiffentialZ) {
                return sizeDiffentialZ;
            },
            'overflow' : function(overflow) {
                return overflow;
            },
            'border' : function(border) {
                return border;
            }
        },
        '#element' : {
            '$yield' : true,
            'id': function(id) {
                return id;
            },
            'content': function(content) {
                return content;
            },
            'style': function(style) {
                return style;
            },
            'attributes': function(attributes) {
                return attributes;
            },
            'unselectable': function(unselectable) {
                return unselectable;
            },
            'backface-visible': function(backfaceVisible) {
                return backfaceVisible;
            },
            'box-shadow': function(boxShadow) {
                return boxShadow;
            },
            'template': function(template) {
                return template;
            }
        }
    },
    events: {
        '$public': {
            // famous:core:view events
            'align': 'setter',
            'align-x': 'setter|camel',
            'align-y': 'setter|camel',
            'align-z': 'setter|camel',
            'mount-point': 'setter|camel',
            'mount-point-x': 'setter|camel',
            'mount-point-y': 'setter|camel',
            'mount-point-z': 'setter|camel',
            'opacity': 'setter',
            'origin': 'setter',
            'origin-x': 'setter|camel',
            'origin-y': 'setter|camel',
            'origin-z': 'setter|camel',
            'position': 'setter',
            'position-x': 'setter|camel',
            'position-y': 'setter|camel',
            'position-z': 'setter|camel',
            'offset-position' : 'setter|camel',
            'rotation': 'setter',
            'rotation-x': 'setter|camel',
            'rotation-y': 'setter|camel',
            'rotation-z': 'setter|camel',
            'scale': 'setter',
            'scale-x': 'setter|camel',
            'scale-y': 'setter|camel',
            'scale-z': 'setter|camel',
            'size': 'setter',
            'size-absolute': 'setter|camel',
            'size-absolute-x': 'setter|camel',
            'size-absolute-y': 'setter|camel',
            'size-absolute-z': 'setter|camel',
            'size-proportional': 'setter|camel',
            'size-proportional-x': 'setter|camel',
            'size-proportional-y': 'setter|camel',
            'size-proportional-z': 'setter|camel',
            'size-differential': 'setter|camel',
            'size-differential-x': 'setter|camel',
            'size-differential-y': 'setter|camel',
            'size-differential-z': 'setter|camel',
            'overflow' : 'setter',
            'border' : 'setter',

            // famous:core:dom-element events
            'id': 'setter',
            'content': 'setter',
            'style': 'setter',
            'attributes': 'setter',
            'unselectable': 'setter',
            'backface-visible': 'setter|camel',
            'box-shadow': 'setter|camel',
            'template': 'setter'
        },

        '#element' : {
            'famous:events:click' : function($dispatcher, $payload) {
                $dispatcher.emit('ui-click', $payload);
            },
            'famous:events:mouseup' : function($dispatcher, $payload) {
                $dispatcher.emit('ui-mouseup', $payload);
            },
            'famous:events:mousedown' : function($dispatcher, $payload) {
                $dispatcher.emit('ui-mousedown', $payload);
            },
            'famous:events:mousemove' : function($dispatcher, $payload) {
                $dispatcher.emit('ui-mousemove', $payload);
            },
            'famous:events:dblclick' : function($dispatcher, $payload) {
                $dispatcher.emit('ui-dblclick', $payload);
            },
            'famous:events:mouseover' : function($dispatcher, $payload) {
                $dispatcher.emit('ui-mouseover', $payload);
            },
            'famous:events:mouseout' : function($dispatcher, $payload) {
                $dispatcher.emit('ui-mouseout', $payload);
            },
            'famous:events:mouseenter' : function($dispatcher, $payload) {
                $dispatcher.emit('ui-mouseenter', $payload);
            },
            'famous:events:mouseleave' : function($dispatcher, $payload) {
                $dispatcher.emit('ui-mouseleave', $payload);
            },
            'famous:events:touchstart' : function($dispatcher, $payload) {
                $dispatcher.emit('ui-touchstart', $payload);
            },
            'famous:events:touchend' : function($dispatcher, $payload) {
                $dispatcher.emit('ui-touchend', $payload);
            },
            'famous:events:touchcancel' : function($dispatcher, $payload) {
                $dispatcher.emit('ui-touchcancel', $payload);
            },
            'famous:events:touchleave' : function($dispatcher, $payload) {
                $dispatcher.emit('ui-touchleave', $payload);
            },
            'famous:events:touchmove' : function($dispatcher, $payload) {
                $dispatcher.emit('ui-touchmove', $payload);
            }
        }
    }
});
<|endoftext|>


<commit_before>'use strict';
exports.up = function(knex) {
  return knex.schema
    .createTableIfNotExists('posts', function(table) {
        table.uuid('_id').notNullable().primary();
        table.string('title').notNullable().defaultTo('');
        table.string('slug').notNullable().defaultTo('').unique();
        table.string('author').notNullable().defaultTo('').references('_id').inTable('users');
        table.text('excerpt').notNullable().defaultTo('');
        table.text('content','longtext').notNullable().defaultTo('');
        table.integer('featured').notNullable().defaultTo(0);
        table.string('status').notNullable().defaultTo('draft');
        table.string('type').notNullable().defaultTo('post');
        table.string('comments_status').notNullable().defaultTo('open');
        table.integer('comments_count').notNullable().defaultTo(0);
        table.timestamps();
    });
};
exports.down = function(knex) {
  return knex.schema
    .dropTable('posts');
};
<commit_msg>Passato Promise ai metodi<commit_after>'use strict';

exports.up = function(knex,Promise) {
  return Promise.all([
    knex.schema.createTableIfNotExists('posts',function(table) {
        table.uuid('_id').notNullable().primary();
        table.string('title').notNullable().defaultTo('');
        table.string('slug').notNullable().defaultTo('').unique();
        table.string('author').notNullable().defaultTo('').references('_id').inTable('users');
        table.text('excerpt').notNullable().defaultTo('');
        table.text('content','longtext').notNullable().defaultTo('');
        table.integer('featured').notNullable().defaultTo(0);
        table.string('status').notNullable().defaultTo('draft');
        table.string('type').notNullable().defaultTo('post');
        table.string('comments_status').notNullable().defaultTo('open');
        table.integer('comments_count').notNullable().defaultTo(0);
        table.timestamps();
    })
   ]);
};

exports.down = function(knex,Promise) {
  return Promise.all([
    knex.schema.dropTable('posts')
  ]);
};
<|endoftext|>


<commit_before>/**
Image modifier utilities

Sample modifier strings, separated by a dash

  - /s50/path/to/image.png
  - /s50-gne/path/to/image.png
  - /w300-h200/path/to/image.png
  - /image.jpg
  - /path/to/image.png
  - /path/to/image.png.json

Supported modifiers are:

  - height:       eg. h500
  - width:        eg. w200
  - square:       eg. s50
  - crop:         eg. cfill
  - top:          eg. y12
  - left:         eg. x200
  - gravity:      eg. gs, gne
  - filter:       eg. fsepia
  - external:     eg. efacebook

Crop modifiers:
  fit
     - maintain original proportions
     - resize so image fits wholly into new dimensions
         - eg: h400-w500 - 400x600 -> 333x500
     - default option
  fill
     - maintain original proportions
     - resize via smallest dimension, crop the largest
     - crop image all dimensions that dont fit
         - eg: h400-w500 - 400x600 -> 400x500
  cut
     - maintain original proportions
     - no resize, crop to gravity or x/y
  scale
     - do not maintain original proportions
     - force image to be new dimensions (squishing the image)

*/
'use strict';

var _, string, filters, sources,  filterKeys, sourceKeys, modifierMap, modKeys;

_          = require('lodash');
string     = require('../utils/string');
filters    = require('../streams/filters');
sources    = require('../streams/sources');
filterKeys = _.keys(filters);
sourceKeys = _.keys(sources);

modifierMap = [
  {
    key: 'h',
    desc: 'height',
    type: 'integer'
  },
  {
    key: 'w',
    desc: 'width',
    type: 'integer'
  },
  {
    key: 's',
    desc: 'square',
    type: 'integer'
  },
  {
    key: 'y',
    desc: 'top',
    type: 'integer'
  },
  {
    key: 'x',
    desc: 'left',
    type: 'integer'
  },
  {
    key: 'g',
    desc: 'gravity',
    type: 'string',
    values: ['c','n','s','e','w','ne','nw','se','sw'],
    default: 'c'
  },
  {
    key: 'c',
    desc: 'crop',
    type: 'string',
    values: ['fit','fill','cut','scale'],
    default: 'fit'
  },
  {
    key: 'e',
    desc: 'external',
    type: 'string',
    values: sourceKeys,
    default: 's3'
  },
  {
    key: 'f',
    desc: 'filter',
    type: 'string',
    values: filterKeys
  }
];

exports.map = modifierMap;

modKeys = _.map(modifierMap, function(value){
  return value.key;
});

function inArray(key, array){
  return _.indexOf(array, key) > -1;
}

function getModifier(key){
  var i, mod;

  for (i in modifierMap){
    mod = modifierMap[i];
    if (mod.key === key){
      return mod;
    }
  }
  return null;
}

exports.mod = getModifier;

exports.parse = function(requestUrl){
  var segments, mods, image, key, value, mod, gravity, crop;

  gravity  = getModifier('g');
  crop     = getModifier('c');
  segments = requestUrl.replace(/^\//,'').split('/');
  image    = _.last(segments).toLowerCase();

  // set the mod keys and defaults
  mods = {
    action: 'original',
    height: null,
    width: null,
    gravity: gravity.default,
    crop: crop.default
  };

  _.each(_.first(segments).split('-'), function(item){
    key = item[0];
    value = item.slice(1);

    if (inArray(key, modKeys)){
      // get the modifier object that responds to the listed key
      mod = getModifier(key);

      switch(mod.desc){
      case 'height':
        mods.height = string.sanitize(value);
        break;
      case 'width':
        mods.width = string.sanitize(value);
        break;
      case 'square':
        mods.action = 'square';
        mods.height = string.sanitize(value);
        mods.width = string.sanitize(value);
        break;
      case 'gravity':
        value = string.sanitize(value, 'alpha');
        if (inArray(value.toLowerCase(), mod.values)){
          mods.gravity = value.toLowerCase();
        }
        break;
      case 'top':
        mods.y = string.sanitize(value);
        break;
      case 'left':
        mods.x = string.sanitize(value);
        break;
      case 'crop':
        value = string.sanitize(value, 'alpha');
        if (inArray(value.toLowerCase(), mod.values)){
          mods.crop = value.toLowerCase();
        }
        break;
      case 'external':
        value = string.sanitize(value, 'alpha');
        if (inArray(value.toLowerCase(), mod.values)){
          mods.external = value.toLowerCase();
        }
        break;
      case 'filter':
        value = string.sanitize(value, 'alpha');
        if (inArray(value.toLowerCase(), mod.values)){
          mods.filter = value.toLowerCase();
        }
        break;
      }
    }
  });

  // check to see if this a metadata call, it trumps all other requested mods
  if (image.slice(-5) === '.json'){
    mods.action = 'json';
    return mods;
  }

  if (mods.action === 'square'){
    // make sure crop is set to the default
    mods.crop = 'fill';
    return mods;
  }

  if (mods.height !== null || mods.width !== null){
    mods.action = 'resize';

    if (mods.crop !== crop.default){
      mods.action = 'crop';
    }
    if (mods.gravity !== gravity.default) {
      mods.action = 'crop';
    }
    if (_.has(mods, 'x') || _.has(mods, 'y')) {
      mods.action = 'crop';
    }
  }

  return mods;
};
<commit_msg>Use env variable for default source<commit_after>/**
Image modifier utilities

Sample modifier strings, separated by a dash

  - /s50/path/to/image.png
  - /s50-gne/path/to/image.png
  - /w300-h200/path/to/image.png
  - /image.jpg
  - /path/to/image.png
  - /path/to/image.png.json

Supported modifiers are:

  - height:       eg. h500
  - width:        eg. w200
  - square:       eg. s50
  - crop:         eg. cfill
  - top:          eg. y12
  - left:         eg. x200
  - gravity:      eg. gs, gne
  - filter:       eg. fsepia
  - external:     eg. efacebook

Crop modifiers:
  fit
     - maintain original proportions
     - resize so image fits wholly into new dimensions
         - eg: h400-w500 - 400x600 -> 333x500
     - default option
  fill
     - maintain original proportions
     - resize via smallest dimension, crop the largest
     - crop image all dimensions that dont fit
         - eg: h400-w500 - 400x600 -> 400x500
  cut
     - maintain original proportions
     - no resize, crop to gravity or x/y
  scale
     - do not maintain original proportions
     - force image to be new dimensions (squishing the image)

*/
'use strict';

var _, string, filters, sources, filterKeys, sourceKeys, modifierMap, modKeys, env;

_          = require('lodash');
string     = require('../utils/string');
filters    = require('../streams/filters');
sources    = require('../streams/sources');
filterKeys = _.keys(filters);
sourceKeys = _.keys(sources);
env        = require('../../config/environment_vars');

modifierMap = [
  {
    key: 'h',
    desc: 'height',
    type: 'integer'
  },
  {
    key: 'w',
    desc: 'width',
    type: 'integer'
  },
  {
    key: 's',
    desc: 'square',
    type: 'integer'
  },
  {
    key: 'y',
    desc: 'top',
    type: 'integer'
  },
  {
    key: 'x',
    desc: 'left',
    type: 'integer'
  },
  {
    key: 'g',
    desc: 'gravity',
    type: 'string',
    values: ['c','n','s','e','w','ne','nw','se','sw'],
    default: 'c'
  },
  {
    key: 'c',
    desc: 'crop',
    type: 'string',
    values: ['fit','fill','cut','scale'],
    default: 'fit'
  },
  {
    key: 'e',
    desc: 'external',
    type: 'string',
    values: sourceKeys,
    default: env.DEFAULT_SOURCE
  },
  {
    key: 'f',
    desc: 'filter',
    type: 'string',
    values: filterKeys
  }
];

exports.map = modifierMap;

modKeys = _.map(modifierMap, function(value){
  return value.key;
});

function inArray(key, array){
  return _.indexOf(array, key) > -1;
}

function getModifier(key){
  var i, mod;

  for (i in modifierMap){
    mod = modifierMap[i];
    if (mod.key === key){
      return mod;
    }
  }
  return null;
}

exports.mod = getModifier;

exports.parse = function(requestUrl){
  var segments, mods, image, key, value, mod, gravity, crop;

  gravity  = getModifier('g');
  crop     = getModifier('c');
  segments = requestUrl.replace(/^\//,'').split('/');
  image    = _.last(segments).toLowerCase();

  // set the mod keys and defaults
  mods = {
    action: 'original',
    height: null,
    width: null,
    gravity: gravity.default,
    crop: crop.default
  };

  _.each(_.first(segments).split('-'), function(item){
    key = item[0];
    value = item.slice(1);

    if (inArray(key, modKeys)){
      // get the modifier object that responds to the listed key
      mod = getModifier(key);

      switch(mod.desc){
      case 'height':
        mods.height = string.sanitize(value);
        break;
      case 'width':
        mods.width = string.sanitize(value);
        break;
      case 'square':
        mods.action = 'square';
        mods.height = string.sanitize(value);
        mods.width = string.sanitize(value);
        break;
      case 'gravity':
        value = string.sanitize(value, 'alpha');
        if (inArray(value.toLowerCase(), mod.values)){
          mods.gravity = value.toLowerCase();
        }
        break;
      case 'top':
        mods.y = string.sanitize(value);
        break;
      case 'left':
        mods.x = string.sanitize(value);
        break;
      case 'crop':
        value = string.sanitize(value, 'alpha');
        if (inArray(value.toLowerCase(), mod.values)){
          mods.crop = value.toLowerCase();
        }
        break;
      case 'external':
        value = string.sanitize(value, 'alpha');
        if (inArray(value.toLowerCase(), mod.values)){
          mods.external = value.toLowerCase();
        }
        break;
      case 'filter':
        value = string.sanitize(value, 'alpha');
        if (inArray(value.toLowerCase(), mod.values)){
          mods.filter = value.toLowerCase();
        }
        break;
      }
    }
  });

  // check to see if this a metadata call, it trumps all other requested mods
  if (image.slice(-5) === '.json'){
    mods.action = 'json';
    return mods;
  }

  if (mods.action === 'square'){
    // make sure crop is set to the default
    mods.crop = 'fill';
    return mods;
  }

  if (mods.height !== null || mods.width !== null){
    mods.action = 'resize';

    if (mods.crop !== crop.default){
      mods.action = 'crop';
    }
    if (mods.gravity !== gravity.default) {
      mods.action = 'crop';
    }
    if (_.has(mods, 'x') || _.has(mods, 'y')) {
      mods.action = 'crop';
    }
  }

  return mods;
};
<|endoftext|>


<commit_before>var async = require('async');
var request = require('request');
var cheerio = require('cheerio');
var mysql = require('mysql');
var dbFuncs = require('./dbFuncs');

var con = mysql.createConnection({
  host     : '',
  user     : '',    // user should have create table and insert privileges to selected database
  password : '',
  database : ''
});
// drop and create hcra table
var dropTable = con.query(dbFuncs.dropHcraTableSQL, function(err, rows, fields){
  if(err) throw err;
});
var createTable = con.query(dbFuncs.createHcraTableSQL, function(err, rows, fields){
  if(err) throw err;
});

var urlBegin = 'http://www.health.ny.gov/regulations/hcra/elector/';
var urlElectBegin = urlBegin + 'elect_';
var alpha = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','x','y','z','-'];
var nums = ['','1','2','3','4','5','6','7','8','9'];
var reqLoop = [];
for (var i = 0; i < alpha.length; i++) {
  for (var j = 0; j < nums.length; j++) {
    reqLoop.push(urlElectBegin + alpha[i] + nums[j] + '.htm');
  };
};

var jsToMysqlDate = function(dateText, minOrMax){
  if( dateText.trim() === '' ){
    if (minOrMax === 'min'){
      return '1000-01-01';
    } else {
      return '9999-12-12';
    }
  } else {
    var dateObj = new Date(dateText);
    return  dateObj.getUTCFullYear() + '-' +
      ('00' + (dateObj.getUTCMonth()+1)).slice(-2) + '-' +
      ('00' + dateObj.getUTCDate()).slice(-2);
  }
}

var getUrlAndParseTable = function(url, callback){
  request(url, function (err, res, body) {

    if (!err && res.statusCode == 200) {
      var insertVals = [];
      $ = cheerio.load(body);
      $('#content table').each(function(){
        if($(this).find('caption').text() === 'KEY'){
        } else {
          $(this).find('tr').each(function(key,val){
            if( key == 0 ){

            }else{

              var rowData = [];
              $(this).find('td').each(function(k, v){
                var cellData = $(this).text().trim();
                if(k === 1) {
                  cellData = jsToMysqlDate(cellData, 'min');
                }
                if(k === 2){
                  cellData = jsToMysqlDate(cellData , 'max');
                }
                rowData.push(cellData);
              });
              insertVals.push(rowData);
            }
          });
        }
      });
      if(insertVals.length === 0){
        callback('no table data', 'no table data');
      } else {
        var sql = 'INSERT INTO electorList ';
        sql += '(changeFlag,effectiveDate,endDate,name,type,fs15,fs16,city,state,contact,phone,message) values ? ;';
        var query = con.query(sql, [insertVals], function(err, result) {
          if(err){
            callback(err, result);
          }else{
            callback(null, result);
          }
        });
      }
    }else{
      callback('url does not exist', null);
    }
  });
}

var parseUrls = function(x){
  if(x < reqLoop.length){
    getUrlAndParseTable(reqLoop[x], function(err, res){
      if(err === null){
        console.log('Inserted ' + res.affectedRows + ' records from ' + reqLoop[x]);
      }else{
        // console.log('Errored out on ' + reqLoop[x]);
      }

      parseUrls(x + 1);
    });
  } else {
    con.end();
  }
}
parseUrls(0);
<commit_msg>don't need async since using only callbacks to make requests one at a time<commit_after>var request = require('request');
var cheerio = require('cheerio');
var mysql = require('mysql');
var dbFuncs = require('./dbFuncs');

var con = mysql.createConnection({
  host     : '',
  user     : '',    // user should have create table and insert privileges to selected database
  password : '',
  database : ''
});
// drop and create hcra table
var dropTable = con.query(dbFuncs.dropHcraTableSQL, function(err, rows, fields){
  if(err) throw err;
});
var createTable = con.query(dbFuncs.createHcraTableSQL, function(err, rows, fields){
  if(err) throw err;
});

var urlBegin = 'http://www.health.ny.gov/regulations/hcra/elector/';
var urlElectBegin = urlBegin + 'elect_';
var alpha = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','x','y','z','-'];
var nums = ['','1','2','3','4','5','6','7','8','9'];
var reqLoop = [];
for (var i = 0; i < alpha.length; i++) {
  for (var j = 0; j < nums.length; j++) {
    reqLoop.push(urlElectBegin + alpha[i] + nums[j] + '.htm');
  };
};

var jsToMysqlDate = function(dateText, minOrMax){
  if( dateText.trim() === '' ){
    if (minOrMax === 'min'){
      return '1000-01-01';
    } else {
      return '9999-12-12';
    }
  } else {
    var dateObj = new Date(dateText);
    return  dateObj.getUTCFullYear() + '-' +
      ('00' + (dateObj.getUTCMonth()+1)).slice(-2) + '-' +
      ('00' + dateObj.getUTCDate()).slice(-2);
  }
}

var getUrlAndParseTable = function(url, callback){
  request(url, function (err, res, body) {

    if (!err && res.statusCode == 200) {
      var insertVals = [];
      $ = cheerio.load(body);
      $('#content table').each(function(){
        if($(this).find('caption').text() === 'KEY'){
        } else {
          $(this).find('tr').each(function(key,val){
            if( key == 0 ){

            }else{

              var rowData = [];
              $(this).find('td').each(function(k, v){
                var cellData = $(this).text().trim();
                if(k === 1) {
                  cellData = jsToMysqlDate(cellData, 'min');
                }
                if(k === 2){
                  cellData = jsToMysqlDate(cellData , 'max');
                }
                rowData.push(cellData);
              });
              insertVals.push(rowData);
            }
          });
        }
      });
      if(insertVals.length === 0){
        callback('no table data', 'no table data');
      } else {
        var sql = 'INSERT INTO electorList ';
        sql += '(changeFlag,effectiveDate,endDate,name,type,fs15,fs16,city,state,contact,phone,message) values ? ;';
        var query = con.query(sql, [insertVals], function(err, result) {
          if(err){
            callback(err, result);
          }else{
            callback(null, result);
          }
        });
      }
    }else{
      callback('url does not exist', null);
    }
  });
}

var parseUrls = function(x){
  if(x < reqLoop.length){
    getUrlAndParseTable(reqLoop[x], function(err, res){
      if(err === null){
        console.log('Inserted ' + res.affectedRows + ' records from ' + reqLoop[x]);
      }else{
        // console.log('Errored out on ' + reqLoop[x]);
      }

      parseUrls(x + 1);
    });
  } else {
    con.end();
  }
}
parseUrls(0);
<|endoftext|>


<commit_before>import React from 'react';
import cx from 'classnames';
import pick from 'lodash/object/pick';
import omit from 'lodash/object/omit';

const propTypes = {
  children: React.PropTypes.node,
  row: React.PropTypes.bool,
  column: React.PropTypes.bool,
  auto: React.PropTypes.bool,
  vAlignContent: React.PropTypes.oneOf(['top', 'center', 'bottom']),
  hAlignContent: React.PropTypes.oneOf(['left', 'center', 'right']),
  marginLeft: React.PropTypes.oneOfType([
    React.PropTypes.string,
    React.PropTypes.number
  ]),
  marginTop: React.PropTypes.oneOfType([
    React.PropTypes.string,
    React.PropTypes.number
  ]),
  marginRight: React.PropTypes.oneOfType([
    React.PropTypes.string,
    React.PropTypes.number
  ]),
  marginBottom: React.PropTypes.oneOfType([
    React.PropTypes.string,
    React.PropTypes.number
  ]),
  grow: React.PropTypes.oneOfType([
    React.PropTypes.number,
    React.PropTypes.bool
  ]),
  shrink: React.PropTypes.oneOfType([
    React.PropTypes.number,
    React.PropTypes.bool
  ]),
  basis: React.PropTypes.oneOfType([
    React.PropTypes.number,
    React.PropTypes.string
  ]),
  height: React.PropTypes.oneOfType([
    React.PropTypes.number,
    React.PropTypes.string
  ]),
  width: React.PropTypes.oneOfType([
    React.PropTypes.number,
    React.PropTypes.string
  ]),
  flexBasis: React.PropTypes.oneOfType([ // deprecated
    React.PropTypes.number,
    React.PropTypes.string
  ]),
  wrap: React.PropTypes.bool,
  className: React.PropTypes.string,
  style: React.PropTypes.object
};

export default React.createClass({

  propTypes: propTypes,

  getDefaultProps() {
    return {
      className: '',
      style: {}
    };
  },

  getGrow() {
    const { grow } = this.props;
    if (typeof grow === 'number') {
      return grow;
    } else if (grow) {
      return 1;
    } else {
      return 0; // auto === true or default
    }
  },

  getShrink() {
    const { shrink, basis, flexBasis, auto } = this.props;
    if (typeof shrink === 'number') {
      return shrink;
    } else if (shrink) {
      return 1;
    }

    if (basis || flexBasis || auto) {
      return 0;
    } else {
      return 1; // grow === true or default
    }
  },

  getBasis() {
    const { grow, shrink, basis, flexBasis, auto } = this.props;
    const _basis = basis || flexBasis;
    if (_basis) {
      const suffix = typeof _basis === 'number' ? 'px' : '';
      return _basis + suffix;
    } else if (grow && !shrink && !auto) {
      return '100%';
    } else {
      return 'auto'; // safe default
    }
  },

  getFlexStyle() {
    const grow = this.getGrow();
    const shrink = this.getShrink();
    const basis = this.getBasis();
    const values = `${grow} ${shrink} ${basis}`;
    return {
      WebkitBoxFlex: values,
      MozBoxFlex: values,
      msFlex: values,
      WebkitFlex: values,
      flex: values
    };
  },

  getStyle() {
    const style = pick(this.props, [
      'width',
      'height',
      'marginLeft',
      'marginTop',
      'marginRight',
      'marginBottom'
    ]);
    return {...this.getFlexStyle(), ...style, ...this.props.style};
  },

  getContentAlignmentClasses() {
    const vPrefix = this.props.column ? 'justify-content-' : 'align-content-';
    const hPrefix = this.props.column ? 'align-content-' : 'justify-content-';

    const vAlignContentClasses = {
      top: `${vPrefix}start`,
      center: `${vPrefix}center`,
      bottom: `${vPrefix}end`
    };

    const hAlignContentClasses = {
      left: `${hPrefix}start`,
      center: `${hPrefix}center`,
      right: `${hPrefix}end`
    };

    const vAlignContent = vAlignContentClasses[this.props.vAlignContent];
    const hAlignContent = hAlignContentClasses[this.props.hAlignContent];

    return cx(vAlignContent, hAlignContent);
  },

  getClasses() {
    const direction = this.props.column ? 'flex-column' : 'flex-row';
    const contentAlignment = this.getContentAlignmentClasses();
    const wrap = this.props.wrap && 'flex-wrap';
    return cx('react-flex-view', direction, contentAlignment, wrap, this.props.className);
  },

  render() {
    const className = this.getClasses();
    const style = this.getStyle();
    const props = omit(this.props, Object.keys(propTypes));
    return (

        {this.props.children}

    );
  }

});
<commit_msg>handle `shrink === false` case<commit_after>import React from 'react';
import cx from 'classnames';
import pick from 'lodash/object/pick';
import omit from 'lodash/object/omit';

const propTypes = {
  children: React.PropTypes.node,
  row: React.PropTypes.bool,
  column: React.PropTypes.bool,
  auto: React.PropTypes.bool,
  vAlignContent: React.PropTypes.oneOf(['top', 'center', 'bottom']),
  hAlignContent: React.PropTypes.oneOf(['left', 'center', 'right']),
  marginLeft: React.PropTypes.oneOfType([
    React.PropTypes.string,
    React.PropTypes.number
  ]),
  marginTop: React.PropTypes.oneOfType([
    React.PropTypes.string,
    React.PropTypes.number
  ]),
  marginRight: React.PropTypes.oneOfType([
    React.PropTypes.string,
    React.PropTypes.number
  ]),
  marginBottom: React.PropTypes.oneOfType([
    React.PropTypes.string,
    React.PropTypes.number
  ]),
  grow: React.PropTypes.oneOfType([
    React.PropTypes.number,
    React.PropTypes.bool
  ]),
  shrink: React.PropTypes.oneOfType([
    React.PropTypes.number,
    React.PropTypes.bool
  ]),
  basis: React.PropTypes.oneOfType([
    React.PropTypes.number,
    React.PropTypes.string
  ]),
  height: React.PropTypes.oneOfType([
    React.PropTypes.number,
    React.PropTypes.string
  ]),
  width: React.PropTypes.oneOfType([
    React.PropTypes.number,
    React.PropTypes.string
  ]),
  flexBasis: React.PropTypes.oneOfType([ // deprecated
    React.PropTypes.number,
    React.PropTypes.string
  ]),
  wrap: React.PropTypes.bool,
  className: React.PropTypes.string,
  style: React.PropTypes.object
};

export default React.createClass({

  propTypes: propTypes,

  getDefaultProps() {
    return {
      className: '',
      style: {}
    };
  },

  getGrow() {
    const { grow } = this.props;
    if (typeof grow === 'number') {
      return grow;
    } else if (grow) {
      return 1;
    } else {
      return 0; // auto === true or default
    }
  },

  getShrink() {
    const { shrink, basis, flexBasis, auto } = this.props;
    if (typeof shrink === 'number') {
      return shrink;
    } else if (shrink) {
      return 1;
    } else if (shrink === false) {
      return 0;
    }

    if (basis || flexBasis || auto) {
      return 0;
    } else {
      return 1; // grow === true or default
    }
  },

  getBasis() {
    const { grow, shrink, basis, flexBasis, auto } = this.props;
    const _basis = basis || flexBasis;
    if (_basis) {
      const suffix = typeof _basis === 'number' ? 'px' : '';
      return _basis + suffix;
    } else if (grow && !shrink && !auto) {
      return '100%';
    } else {
      return 'auto'; // safe default
    }
  },

  getFlexStyle() {
    const grow = this.getGrow();
    const shrink = this.getShrink();
    const basis = this.getBasis();
    const values = `${grow} ${shrink} ${basis}`;
    return {
      WebkitBoxFlex: values,
      MozBoxFlex: values,
      msFlex: values,
      WebkitFlex: values,
      flex: values
    };
  },

  getStyle() {
    const style = pick(this.props, [
      'width',
      'height',
      'marginLeft',
      'marginTop',
      'marginRight',
      'marginBottom'
    ]);
    return {...this.getFlexStyle(), ...style, ...this.props.style};
  },

  getContentAlignmentClasses() {
    const vPrefix = this.props.column ? 'justify-content-' : 'align-content-';
    const hPrefix = this.props.column ? 'align-content-' : 'justify-content-';

    const vAlignContentClasses = {
      top: `${vPrefix}start`,
      center: `${vPrefix}center`,
      bottom: `${vPrefix}end`
    };

    const hAlignContentClasses = {
      left: `${hPrefix}start`,
      center: `${hPrefix}center`,
      right: `${hPrefix}end`
    };

    const vAlignContent = vAlignContentClasses[this.props.vAlignContent];
    const hAlignContent = hAlignContentClasses[this.props.hAlignContent];

    return cx(vAlignContent, hAlignContent);
  },

  getClasses() {
    const direction = this.props.column ? 'flex-column' : 'flex-row';
    const contentAlignment = this.getContentAlignmentClasses();
    const wrap = this.props.wrap && 'flex-wrap';
    return cx('react-flex-view', direction, contentAlignment, wrap, this.props.className);
  },

  render() {
    const className = this.getClasses();
    const style = this.getStyle();
    const props = omit(this.props, Object.keys(propTypes));
    return (

        {this.props.children}

    );
  }

});
<|endoftext|>


<commit_before>var Vector2;
if(!Vector2) {
  var Vector2 = function(x, y) {
    this.x = x || 0;
    this.y = y || 0;
  };
  Vector2.add = function(toAdd1, toAdd2) {
    return new Vector2(
      toAdd1.x + toAdd2.x,
      toAdd1.y + toAdd2.y
    );
  };
  Vector2.sub = function(subtractFrom, toSubtract) {
    return new Vector2(
      subtractFrom.x - toSubtract.x,
      subtractFrom.y - toSubtract.y
    );
  };
  Vector2.mult = function(toMultiply, scaleFactor) {
    return new Vector2(
      toMultiply.x * scaleFactor,
      toMultiply.y * scaleFactor
    );
  };
  Vector2.div = function(toDivide, inverseFactor) {
    return new Vector2(
      toDivide.x / inverseFactor,
      toDivide.y / inverseFactor
    );
  };
  Vector2.mag = function(toMeasure) {
    return Math.sqrt(toMeasure.x * toMeasure.x + toMeasure.y * toMeasure.y);
  };
  Vector2.magSq = function(toMeasure) {
    return toMeasure.x * toMeasure.x + toMeasure.y * toMeasure.y;
  };
  Vector2.normalize = function(toNormalize) {
    return Vector2.div(toNormalize, toNormalize.mag());
  };
  Vector2.rotate = function(toRotate, rotateBy) {
    var cosAngle = Math.cos(rotateBy);
    var sinAngle = Math.sin(rotateBy);
    return new Vector2(
      toRotate.x * cosAngle - y * sinAngle,
      toRotate.x * sinAngle + y * cosAngle
    );
  };
  Vector2.mid = function(lineEnd1, lineEnd2) {
    return new Vector2(
      lineEnd1.x / 2 + lineEnd2.x / 2,
      lineEnd1.y / 2 + lineEnd2.y / 2
    );
  };
  Vector2.dist = function(lineEnd1, lineEnd2) {
    return Vector2.sub(lineEnd1, lineEnd2).mag();
  };
  Vector2.lerp = function(lerpFrom, lerpTo, lerpStage) {
    return new Vector2(
      lerpFrom.x + (lerpTo.x - lerpFrom.x) * lerpStage,
      lerpFrom.y + (lerpTo.y - lerpFrom.y) * lerpStage
    );
  };
  Vector2.dot = function(toDot1, toDot2) {
    return toDot1.x * toDot2.x + toDot1.y * toDot2.y;
  };
  Vector2.array = function(toConvert) {
    return [toConvert.x, toConvert.y];
  };
  Vector2.reflect = function(toReflect, linePoint1, linePoint2) {
    return Vector2.sub(toReflect,
      Vector2.mult(
        Vector2.sub(toReflect,
          [(Equation.B(linePoint1, linePoint2) - Equation.TB(Equation.PM(linePoint1, linePoint2), toReflect)) /
           (Equation.PM(linePoint1, linePoint2) - Equation.M(linePoint1, linePoint2)), Equation.M(linePoint1, linePoint2) *
           (Equation.B(linePoint1, linePoint2) - Equation.TB(Equation.PM(linePoint1, linePoint2), toReflect)) /
           (Equation.PM(linePoint1, linePoint2) - Equation.M(linePoint1, linePoint2)) + Equation.B(linePoint1, linePoint2)]
        ),
      2)
    );
  };

  Vector2.prototype.add = function(toAdd) {
    this.x += toAdd.x;
    this.y += toAdd.y;
  };
  Vector2.prototype.sub = function(toSubtract) {
    this.x -= toSubtract.x;
    this.y -= toSubtract.y;
  };
  Vector2.prototype.mult = function(scaleFactor) {
    this.x *= scaleFactor;
    this.y *= scaleFactor;
  };
  Vector2.prototype.div = function(inverseFactor) {
    this.x /= inverseFactor;
    this.y /= inverseFactor;
  };
  Vector2.prototype.mag = function() {
    return Math.sqrt(this.x * this.x + this.y * this.y);
  };
  Vector2.prototype.magSq = function() {
    return this.x * this.x + this.y + this.y;
  };
  Vector2.prototype.normalize = function() {
    this.div(this.mag());
  };
  Vector2.prototype.rotate = function(rotateBy) {
    var cosAngle = Math.cos(rotateBy);
    var sinAngle = Math.sin(rotateBy);
    var oldX = this.x;
    this.x = oldX * cosAngle - y * sinAngle;
    this.y = oldX * sinAngle + y * cosAngle;
  };
  Vector2.prototype.mid = function(lineEnd) {
    return new Vector2(
      this.x / 2 + lineEnd.x / 2,
      this.y / 2 + lineEnd.y / 2
    );
  };
  Vector2.prototype.dist = function(lineEnd) {
    return Vector2.sub(this, lineEnd).mag();
  };
  Vector2.prototype.lerp = function(lerpWith, lerpStage) {
    return new Vector2(
      this.x + (lerpWith.x - this.x) * lerpStage,
      this.y + (lerpWith.y - this.y) * lerpStage
    );
  };
  Vector2.prototype.dot = function(dotWith) {
    return this.x * dotWith.x + this.y * dotWith.y;
  };
  Vector2.prototype.array = function() {
    return [this.x, this.y];
  };
  Vector2.prototype.reflect = function(linePoint1, linePoint2) {
    return Vector2.sub(this,
      Vector2.mult(
        Vector2.sub(this,
          [(Equation.B(linePoint1, linePoint2) - Equation.TB(Equation.PM(linePoint1, linePoint2), this)) /
           (Equation.PM(linePoint1, linePoint2) - Equation.M(linePoint1, linePoint2)), Equation.M(linePoint1, linePoint2) *
           (Equation.B(linePoint1, linePoint2) - Equation.TB(Equation.PM(linePoint1, linePoint2), this)) /
           (Equation.PM(linePoint1, linePoint2) - Equation.M(linePoint1, linePoint2)) + Equation.B(linePoint1, linePoint2)]
        ),
      2)
    );
  };
}

<commit_msg>Update vector2.js<commit_after>var Vector2 = function(x, y) {
  this.x = x || 0;
  this.y = y || 0;
};
Vector2.add = function(toAdd1, toAdd2) {
  return new Vector2(
    toAdd1.x + toAdd2.x,
    toAdd1.y + toAdd2.y
  );
};
Vector2.sub = function(subtractFrom, toSubtract) {
  return new Vector2(
    subtractFrom.x - toSubtract.x,
    subtractFrom.y - toSubtract.y
  );
};
Vector2.mult = function(toMultiply, scaleFactor) {
  return new Vector2(
    toMultiply.x * scaleFactor,
    toMultiply.y * scaleFactor
  );
};
Vector2.div = function(toDivide, inverseFactor) {
  return new Vector2(
    toDivide.x / inverseFactor,
    toDivide.y / inverseFactor
  );
};
Vector2.mag = function(toMeasure) {
  return Math.sqrt(toMeasure.x * toMeasure.x + toMeasure.y * toMeasure.y);
};
Vector2.magSq = function(toMeasure) {
  return toMeasure.x * toMeasure.x + toMeasure.y * toMeasure.y;
};
Vector2.normalize = function(toNormalize) {
  return Vector2.div(toNormalize, toNormalize.mag());
};
Vector2.rotate = function(toRotate, rotateBy) {
  var cosAngle = Math.cos(rotateBy);
  var sinAngle = Math.sin(rotateBy);
  return new Vector2(
    toRotate.x * cosAngle - y * sinAngle,
    toRotate.x * sinAngle + y * cosAngle
  );
};
Vector2.mid = function(lineEnd1, lineEnd2) {
  return new Vector2(
    lineEnd1.x / 2 + lineEnd2.x / 2,
    lineEnd1.y / 2 + lineEnd2.y / 2
  );
};
Vector2.dist = function(lineEnd1, lineEnd2) {
  return Vector2.sub(lineEnd1, lineEnd2).mag();
};
Vector2.lerp = function(lerpFrom, lerpTo, lerpStage) {
  return new Vector2(
    lerpFrom.x + (lerpTo.x - lerpFrom.x) * lerpStage,
    lerpFrom.y + (lerpTo.y - lerpFrom.y) * lerpStage
  );
};
Vector2.dot = function(toDot1, toDot2) {
  return toDot1.x * toDot2.x + toDot1.y * toDot2.y;
};
Vector2.array = function(toConvert) {
  return [toConvert.x, toConvert.y];
};
Vector2.reflect = function(toReflect, linePoint1, linePoint2) {
  return Vector2.sub(toReflect,
    Vector2.mult(
      Vector2.sub(toReflect, [(Equation.B(linePoint1, linePoint2) - Equation.TB(Equation.PM(linePoint1, linePoint2), toReflect)) /
        (Equation.PM(linePoint1, linePoint2) - Equation.M(linePoint1, linePoint2)), Equation.M(linePoint1, linePoint2) *
        (Equation.B(linePoint1, linePoint2) - Equation.TB(Equation.PM(linePoint1, linePoint2), toReflect)) /
        (Equation.PM(linePoint1, linePoint2) - Equation.M(linePoint1, linePoint2)) + Equation.B(linePoint1, linePoint2)
      ]),
      2)
  );
};

Vector2.prototype.add = function(toAdd) {
  this.x += toAdd.x;
  this.y += toAdd.y;
};
Vector2.prototype.sub = function(toSubtract) {
  this.x -= toSubtract.x;
  this.y -= toSubtract.y;
};
Vector2.prototype.mult = function(scaleFactor) {
  this.x *= scaleFactor;
  this.y *= scaleFactor;
};
Vector2.prototype.div = function(inverseFactor) {
  this.x /= inverseFactor;
  this.y /= inverseFactor;
};
Vector2.prototype.mag = function() {
  return Math.sqrt(this.x * this.x + this.y * this.y);
};
Vector2.prototype.magSq = function() {
  return this.x * this.x + this.y + this.y;
};
Vector2.prototype.normalize = function() {
  this.div(this.mag());
};
Vector2.prototype.rotate = function(rotateBy) {
  var cosAngle = Math.cos(rotateBy);
  var sinAngle = Math.sin(rotateBy);
  var oldX = this.x;
  this.x = oldX * cosAngle - y * sinAngle;
  this.y = oldX * sinAngle + y * cosAngle;
};
Vector2.prototype.mid = function(lineEnd) {
  return new Vector2(
    this.x / 2 + lineEnd.x / 2,
    this.y / 2 + lineEnd.y / 2
  );
};
Vector2.prototype.dist = function(lineEnd) {
  return Vector2.sub(this, lineEnd).mag();
};
Vector2.prototype.lerp = function(lerpWith, lerpStage) {
  return new Vector2(
    this.x + (lerpWith.x - this.x) * lerpStage,
    this.y + (lerpWith.y - this.y) * lerpStage
  );
};
Vector2.prototype.dot = function(dotWith) {
  return this.x * dotWith.x + this.y * dotWith.y;
};
Vector2.prototype.array = function() {
  return [this.x, this.y];
};
Vector2.prototype.reflect = function(linePoint1, linePoint2) {
  return Vector2.sub(this,
    Vector2.mult(
      Vector2.sub(this, [(Equation.B(linePoint1, linePoint2) - Equation.TB(Equation.PM(linePoint1, linePoint2), this)) /
        (Equation.PM(linePoint1, linePoint2) - Equation.M(linePoint1, linePoint2)), Equation.M(linePoint1, linePoint2) *
        (Equation.B(linePoint1, linePoint2) - Equation.TB(Equation.PM(linePoint1, linePoint2), this)) /
        (Equation.PM(linePoint1, linePoint2) - Equation.M(linePoint1, linePoint2)) + Equation.B(linePoint1, linePoint2)
      ]),
      2)
  );
};
<|endoftext|>


<commit_before>var PrettyError = require('pretty-error');
var pe = new PrettyError();

function errorHandler(error) {

	var prettyError = pe.render(new Error(error));

	console.error('');
	console.error(prettyError);

	process.exit(1);
}

function setPrettyErrrorTheme() {
	pe.appendStyle({
		'pretty-error > header > title > kind': {
			display: 'none'
		},

		// the 'colon' after 'Error':
		'pretty-error > header > colon': {
			display: 'none'
		},

		// our error message
		'pretty-error > header > message': {
			color: 'bright-white',
			//colour range red, green, yellow, blue, magenta, cyan, white,
			background: 'red',
			padding: '0 1' // top/bottom left/right
		},

		// each trace item ...
		'pretty-error > trace > item': {
			marginLeft: 2,
			marginBottom: 0,
			bullet: '"<grey>· </grey>"'
		},

		'pretty-error > trace > item > header > pointer > file': {
			color: 'yellow'
		},

		'pretty-error > trace > item > header > pointer > colon': {
			color: 'yellow'
		},

		'pretty-error > trace > item > header > pointer > line': {
			color: 'bright-cyan'
		},

		'pretty-error > trace > item > header > what': {
			color: 'bright-white'
		},

		'pretty-error > trace > item > footer > addr': {
			// display: 'none'
			marginLeft: 4
		}
	});
}

setPrettyErrrorTheme();

module.exports = errorHandler<commit_msg>feat: Exclude Node files (e.g. fs) from error handler stack<commit_after>var PrettyError = require('pretty-error');
var pe = new PrettyError();

function errorHandler(error) {

	var prettyError = pe.render(new Error(error));

	console.error('');
	console.error(prettyError);

	process.exit(1);
}

function setPrettyErrrorTheme() {
	pe.appendStyle({
		'pretty-error > header > title > kind': {
			display: 'none'
		},

		// the 'colon' after 'Error':
		'pretty-error > header > colon': {
			display: 'none'
		},

		// our error message
		'pretty-error > header > message': {
			color: 'bright-white',
			//colour range red, green, yellow, blue, magenta, cyan, white,
			background: 'red',
			padding: '0 1' // top/bottom left/right
		},

		// each trace item ...
		'pretty-error > trace > item': {
			marginLeft: 2,
			marginBottom: 0,
			bullet: '"<grey>· </grey>"'
		},

		'pretty-error > trace > item > header > pointer > file': {
			color: 'yellow'
		},

		'pretty-error > trace > item > header > pointer > colon': {
			color: 'yellow'
		},

		'pretty-error > trace > item > header > pointer > line': {
			color: 'bright-cyan'
		},

		'pretty-error > trace > item > header > what': {
			color: 'bright-white'
		},

		'pretty-error > trace > item > footer > addr': {
			// display: 'none'
			marginLeft: 4
		}
	});
}

function setPrettyErrorConfig() {
	pe.skipNodeFiles();
}

setPrettyErrrorTheme();
setPrettyErrorConfig();

module.exports = errorHandler<|endoftext|>