<commit_before>
'use strict';

angular.module('mean.icu.ui.displayby', [])
.directive('icuDisplayBy', function() {
    function controller($scope, $state, context,SettingServices,SearchService,EntityService, $rootScope, $stateParams,$location, $window,NotifyingService,UsersService, TasksService,ProjectsService,DiscussionsService,OfficesService,TemplateDocsService, OfficeDocumentsService) {
        $scope.statusList = SettingServices.getStatusList();
        $scope.activeList = SettingServices.getActiveStatusList();
        $scope.archiveList = SettingServices.getNonActiveStatusList();
        $scope.userFilterList = SettingServices.getUserFilter();

        $rootScope.$on('changeStatus',function(){
          $scope.AllStatus = $scope.statusList[$scope.filteringData.issue];
        });

        function arrayUnique(array) {
            var a = array.concat();
            for(var i=0; i<a.length; ++i) {
                for(var j=i+1; j<a.length; ++j) {
                    if(a[i] === a[j])
                        a.splice(j--, 1);
                }
            }

            return a;
        }
        $scope.currentType = 'All';

        $scope.clearDateRange = function(){
            SearchService.filterDateOption = null;
            $scope.datePicker.date = {startDate: null, endDate: null};
        };

        $scope.removeTags = function(text){
            return text ? String(text).replace(/<[^>]+>/gm, '') : '';
        };

        $scope.clearDueDate = function(){
          $scope.dueDate = null;
          SearchService.filteringByDueDate = null;
        };

        $scope.clearUpdatedDate = function(){
            $scope.updatedDate = null;
            SearchService.filteringByUpdated = null;
        };

        //clearing default date filter
        $scope.clearDateRange();
        $scope.clearDueDate();
        $scope.clearUpdatedDate();

        $scope.turnOffRecycle = function () {
            var query = SearchService.getQuery();
            $scope.recycled = false;
            $scope.isRecycled = false;
            $state.go('main.search', {reload: true, query: query});
        };

        $scope.tmpStatus = [];

          $scope.statusListChange = function(type){
            var index;
            if($scope.currentType == 'active'){
                if ($scope.activeList.indexOf(type) < 0)
                $scope.activeList.push(type);
                  else {
                      index = $scope.activeList.indexOf(type);
                      $scope.activeList.splice(index , 1);
                  }
            }
            else if($scope.currentType == 'nonactive'){
                // archiveList.push(type);
                if ($scope.archiveList.indexOf(type) < 0)
                $scope.archiveList.push(type);
                else {
                   index = $scope.archiveList.indexOf(type);
                   $scope.archiveList.splice(index , 1);
                }
            }
            else {
                $scope.currentType = 'all';
                if ($scope.userFilterList.indexOf(type) < 0)
                    $scope.userFilterList.push(type);
                else {
                   index = $scope.userFilterList.indexOf(type);
                    $scope.userFilterList.splice(index , 1);
                }
            }
        };

        $scope.isActive = function(type, status){
            if ( status !== 'active' && status !== 'nonactive' && $scope.tmpStatus.length && $scope.tmpStatus.indexOf(type)> -1)
                return true;
            if (status !== 'active' && status !== 'nonactive' && status == type)
                return true;
            else {
                if($scope.currentType == 'all') {
                    if ($scope.userFilterList.indexOf(type) > -1)
                        return true;
                }
                if($scope.currentType == 'active'){
                    if ($scope.activeList.indexOf(type) >-1)
                        return true;
                }
                if($scope.currentType == 'nonactive'){
                    if ($scope.archiveList.indexOf(type) >-1)
                    return true;
                }
            }
            return false;
        }

        $scope.AllStatus = [];

        $scope.showM = function(type){
            $scope.currentType = type;
            if (type == 'empty'){
              $scope.AllStatus = [];
              $scope.activeList = SettingServices.getActiveStatusList();
              $scope.archiveList = SettingServices.getNonActiveStatusList();
              $scope.userFilterList = SettingServices.getUserFilter();
            }
            else if ($location.search().type)
              $scope.AllStatus = $scope.statusList[$scope.filteringData.issue];
            else $scope.AllStatus =  arrayUnique($scope.activeList.concat($scope.archiveList));
            $scope.tmpStatus = [];
        }

        $scope.typeClicked = false;

        NotifyingService.subscribe('editionData', function () {
            TasksService.getAll(0,2500,'created').then(function (data) {
                $scope.tasks = data.data || data;
            });

            ProjectsService.getAll(0,2500,'created').then(function (data) {
                $scope.projects = data.data || data;
            });

            DiscussionsService.getAll(0,2500,'created').then(function (data) {
                $scope.discussions = data.data || data;
            });

            OfficeDocumentsService.getAll(0,2500,'created').then(function (data) {
                $scope.documents = data.data || data;
            });

            OfficesService.getAll(0,2500,'created').then(function (data) {
                $scope.offices = data.data || data;
            });

            TemplateDocsService.getAll(0,2500,'created').then(function (data) {
                $scope.templateDocs = data.data || data;
            });

            UsersService.getAll(0,2500,'created').then(function (data) {
                $scope.people = data.data || data;
            });
            $scope.createLists();
        }, $scope);

        $scope.createLists();

        $scope.focus = false;
        $scope.changeFocus = function(){
            $scope.focus = !$scope.focus;
        };

        $scope.myFilter = function (item) {
            if(item.office.title && $scope.officesList.office.title)
            {
                return item.office.title === $scope.officesList.office.title;
            }
            else
            {
                return false;
            }

        };

        $scope.clearSearchType = function(){

            $location.search('type', null);
            $window.location.reload();
        }

        $scope.getLinkUrl = function(){
            return $state.href('main.' + $scope.activeTab.state ,{'officeDocuments':undefined});
        };

        //$scope.temp = {};
        $scope.changeOrder = function () {
            //$scope.temp.office = $scope.officesList.office;

            // if($scope.officesList.office.title != "custom"){
            //     $scope.sorting.isReverse = !$scope.sorting.isReverse;
            // }

            /*Made By OHAD - Needed for reversing sort*/
            //$state.go($state.current.name, { sort: $scope.officesList.office.title });
        };

        $scope.goToParentState = function(){

        };

        $scope.typesList = [{
            name: 'new',
             color:'ff4081'
        },{
            name:  'received',
            color:'37afef'
        },{
            name:  'in-progress',
            color:'f69679'
         },{
            name:  'sent',
            color:'359123'
        },{
            name:  'done',
            color:'757575'
        }];

        $scope.typeSelected = '';

        $scope.singularItemName = {
            tasks: "task",
            projects: "project",
            discussions: "discussion",
            officeDocuments: "officeDocument",
            offices: "office",
            folders: "folder",
            watchers: "watcher"
        };

        $scope.allItems = {
            tasks: $scope.tasks,
            projects: $scope.projects,
            discussions: $scope.discussions,
            officeDocuments: $scope.officeDocuments,
            offices: $scope.offices,
            folders: $scope.folders
        };

        // Reverse list in sideline
        $scope.projectsList = $scope.projectsList.slice();
        $scope.projectsList.reverse();
        $scope.allItems.projects = $scope.allItems.projects.slice();
        $scope.allItems.projects.reverse();
        $scope.allItems.discussions = $scope.allItems.discussions.slice();
        $scope.allItems.discussions.reverse();
        $scope.discussions = $scope.discussions.slice();
        $scope.discussions.reverse();

        $scope.context = context;

        $window.onbeforeunload = function(){
            localStorage.removeItem("type");
        };

        $scope.reset = function(main){
             EntityService.setEntityFolderValue(undefined, undefined);
            localStorage.removeItem("type");
            $scope.typeSelected = null;
        };

        $scope.changeState = function(state){
            $state.go(state, {
                officeDocuments: undefined,
                activeTab: $scope.item
            }, {reload: false});
        };

        $scope.typeSelected = localStorage.getItem("type");
        $scope.switchToType = function (type) {
            EntityService.setActiveStatusFilterValue(type.name);
            OfficeDocumentsService.getAll(0,25,EntityService.getSortFilterValue().field, EntityService.getSortFilterValue().order,type.name).then(function (result) {

            $scope.officeDocuments=result;

         $scope.typeSelected = type.name;

         if (context.entityName == 'folder') {
             $scope.officeDocuments = $scope.officeDocuments.filter(function (officeDocument) {
                 return officeDocument.status == type.name && officeDocument.folder && officeDocument.folder._id == context.entityId;
             });
         } else {

             $scope.officeDocuments = $scope.officeDocuments.filter(function (officeDocument) {
                 return officeDocument.status == type.name;
             });
         }

         localStorage.setItem("type", type.name);

         $state.go($state.current, {
             officeDocuments: $scope.officeDocuments,
             activeTab: $scope.item
         }, { reload: true });
            });

         /**
         var temp=[];
         $scope.officeDocuments.forEach(function(d){
             temp.push(d);
         });
         temp = temp.filter(function(officeDocument){
             if(context.entityName=='folder'){
                 return officeDocument.status == type.name &&officeDocument.folder&& officeDocument.folder._id==context.entityId ;
             }
             else{
                 return officeDocument.status == type.name;
             }
          });
           /*if(context.entityName == 'all'){
             $state.go('main.' + context.main + '.all', {},{reload: true});
         }else if (context.entityName == 'folder'){
             $state.go('main.' + context.main + '.byentity', {
                 entityId: context.entityId,
                 entity: 'folder',
                 officeDocuments: temp
             },{reload: true});
         }*/
     };
        $scope.switchTo = function (entityName, id) {
            EntityService.setEntityFolderValue(entityName, id);
            OfficeDocumentsService.getAll(0,25,EntityService.getSortFilterValue().field,
                                               EntityService.getSortFilterValue().order,
                                               EntityService.getActiveStatusFilterValue(),
                                               EntityService.getEntityFolderValue().id).then(function (result) {

            $state.go('main.' + context.main + '.byentity', {
                entity: entityName,
                entityId: id,
                officeDocuments: result
            });
        });
            // If we are switching between entities, then shrink the display limit again
            if (!$scope.visible[entityName]) {
                $scope.displayLimit.reset();
            }

        };

        $scope.switchToAll = function (entityName, id) {
            $state.go('main.' + context.main + '.all.details.activities', {
                id: id,
                entity: entityName,
            });
        };

        $scope.visible = {
            project: true,
            discussion: true,
            user: true,
            officeDocument: true,
            office: true,
            folder: true
        };

        $scope.visible[$scope.context.entityName] = true;

        $scope.GoToFolders = function() {
            $state.go('main.folders.all');
        };

        $scope.GoToOffices = function() {
            $state.go('main.offices.all');
        };

        $scope.GoToTemplateDocs = function() {
            $state.go('main.templateDocs.all');
        };

        $scope.GoToAdminSettings = function() {
            $state.go('main.adminSettings');
        }
    }

        function link($scope, $element, context) {
            $scope.showMore = function(limit, entityName) {
                if (($scope.displayLimit[entityName] + 4) >= limit) {
                    $scope.displayLimit[entityName] = limit;
                } else {
                    $scope.displayLimit[entityName]  += 4;

                }
            };

            $scope.collapse = function(entityName) {
                $scope.displayLimit[entityName] = $scope.displayLimit.default[entityName];
            };
        }

    return {
        restrict: 'A',
        templateUrl: '/icu/components/display-by/display-by.html',
        controller: controller,
        link: link
    };
});
<commit_msg>fixed redirect 'by projects/discussion' in tasks menu tab<commit_after>
'use strict';

angular.module('mean.icu.ui.displayby', [])
.directive('icuDisplayBy', function() {
    function controller($scope, $state, context,SettingServices,SearchService,EntityService, $rootScope, $stateParams,$location, $window,NotifyingService,UsersService, TasksService,ProjectsService,DiscussionsService,OfficesService,TemplateDocsService, OfficeDocumentsService) {
        $scope.statusList = SettingServices.getStatusList();
        $scope.activeList = SettingServices.getActiveStatusList();
        $scope.archiveList = SettingServices.getNonActiveStatusList();
        $scope.userFilterList = SettingServices.getUserFilter();

        $rootScope.$on('changeStatus',function(){
          $scope.AllStatus = $scope.statusList[$scope.filteringData.issue];
        });

        function arrayUnique(array) {
            var a = array.concat();
            for(var i=0; i<a.length; ++i) {
                for(var j=i+1; j<a.length; ++j) {
                    if(a[i] === a[j])
                        a.splice(j--, 1);
                }
            }

            return a;
        }
        $scope.currentType = 'All';

        $scope.clearDateRange = function(){
            SearchService.filterDateOption = null;
            $scope.datePicker.date = {startDate: null, endDate: null};
        };

        $scope.removeTags = function(text){
            return text ? String(text).replace(/<[^>]+>/gm, '') : '';
        };

        $scope.clearDueDate = function(){
          $scope.dueDate = null;
          SearchService.filteringByDueDate = null;
        };

        $scope.clearUpdatedDate = function(){
            $scope.updatedDate = null;
            SearchService.filteringByUpdated = null;
        };

        //clearing default date filter
        $scope.clearDateRange();
        $scope.clearDueDate();
        $scope.clearUpdatedDate();

        $scope.turnOffRecycle = function () {
            var query = SearchService.getQuery();
            $scope.recycled = false;
            $scope.isRecycled = false;
            $state.go('main.search', {reload: true, query: query});
        };

        $scope.tmpStatus = [];

          $scope.statusListChange = function(type){
            var index;
            if($scope.currentType == 'active'){
                if ($scope.activeList.indexOf(type) < 0)
                $scope.activeList.push(type);
                  else {
                      index = $scope.activeList.indexOf(type);
                      $scope.activeList.splice(index , 1);
                  }
            }
            else if($scope.currentType == 'nonactive'){
                // archiveList.push(type);
                if ($scope.archiveList.indexOf(type) < 0)
                $scope.archiveList.push(type);
                else {
                   index = $scope.archiveList.indexOf(type);
                   $scope.archiveList.splice(index , 1);
                }
            }
            else {
                $scope.currentType = 'all';
                if ($scope.userFilterList.indexOf(type) < 0)
                    $scope.userFilterList.push(type);
                else {
                   index = $scope.userFilterList.indexOf(type);
                    $scope.userFilterList.splice(index , 1);
                }
            }
        };

        $scope.isActive = function(type, status){
            if ( status !== 'active' && status !== 'nonactive' && $scope.tmpStatus.length && $scope.tmpStatus.indexOf(type)> -1)
                return true;
            if (status !== 'active' && status !== 'nonactive' && status == type)
                return true;
            else {
                if($scope.currentType == 'all') {
                    if ($scope.userFilterList.indexOf(type) > -1)
                        return true;
                }
                if($scope.currentType == 'active'){
                    if ($scope.activeList.indexOf(type) >-1)
                        return true;
                }
                if($scope.currentType == 'nonactive'){
                    if ($scope.archiveList.indexOf(type) >-1)
                    return true;
                }
            }
            return false;
        }

        $scope.AllStatus = [];

        $scope.showM = function(type){
            $scope.currentType = type;
            if (type == 'empty'){
              $scope.AllStatus = [];
              $scope.activeList = SettingServices.getActiveStatusList();
              $scope.archiveList = SettingServices.getNonActiveStatusList();
              $scope.userFilterList = SettingServices.getUserFilter();
            }
            else if ($location.search().type)
              $scope.AllStatus = $scope.statusList[$scope.filteringData.issue];
            else $scope.AllStatus =  arrayUnique($scope.activeList.concat($scope.archiveList));
            $scope.tmpStatus = [];
        }

        $scope.typeClicked = false;

        NotifyingService.subscribe('editionData', function () {
            TasksService.getAll(0,2500,'created').then(function (data) {
                $scope.tasks = data.data || data;
            });

            ProjectsService.getAll(0,2500,'created').then(function (data) {
                $scope.projects = data.data || data;
            });

            DiscussionsService.getAll(0,2500,'created').then(function (data) {
                $scope.discussions = data.data || data;
            });

            OfficeDocumentsService.getAll(0,2500,'created').then(function (data) {
                $scope.documents = data.data || data;
            });

            OfficesService.getAll(0,2500,'created').then(function (data) {
                $scope.offices = data.data || data;
            });

            TemplateDocsService.getAll(0,2500,'created').then(function (data) {
                $scope.templateDocs = data.data || data;
            });

            UsersService.getAll(0,2500,'created').then(function (data) {
                $scope.people = data.data || data;
            });
            $scope.createLists();
        }, $scope);

        $scope.createLists();

        $scope.focus = false;
        $scope.changeFocus = function(){
            $scope.focus = !$scope.focus;
        };

        $scope.myFilter = function (item) {
            if(item.office.title && $scope.officesList.office.title)
            {
                return item.office.title === $scope.officesList.office.title;
            }
            else
            {
                return false;
            }

        };

        $scope.clearSearchType = function(){

            $location.search('type', null);
            $window.location.reload();
        }

        $scope.getLinkUrl = function(){
            return $state.href('main.' + $scope.activeTab.state ,{'officeDocuments':undefined});
        };

        //$scope.temp = {};
        $scope.changeOrder = function () {
            //$scope.temp.office = $scope.officesList.office;

            // if($scope.officesList.office.title != "custom"){
            //     $scope.sorting.isReverse = !$scope.sorting.isReverse;
            // }

            /*Made By OHAD - Needed for reversing sort*/
            //$state.go($state.current.name, { sort: $scope.officesList.office.title });
        };

        $scope.goToParentState = function(){

        };

        $scope.typesList = [{
            name: 'new',
             color:'ff4081'
        },{
            name:  'received',
            color:'37afef'
        },{
            name:  'in-progress',
            color:'f69679'
         },{
            name:  'sent',
            color:'359123'
        },{
            name:  'done',
            color:'757575'
        }];

        $scope.typeSelected = '';

        $scope.singularItemName = {
            tasks: "task",
            projects: "project",
            discussions: "discussion",
            officeDocuments: "officeDocument",
            offices: "office",
            folders: "folder",
            watchers: "watcher"
        };

        $scope.allItems = {
            tasks: $scope.tasks,
            projects: $scope.projects,
            discussions: $scope.discussions,
            officeDocuments: $scope.officeDocuments,
            offices: $scope.offices,
            folders: $scope.folders
        };

        // Reverse list in sideline
        $scope.projectsList = $scope.projectsList.slice();
        $scope.projectsList.reverse();
        $scope.allItems.projects = $scope.allItems.projects.slice();
        $scope.allItems.projects.reverse();
        $scope.allItems.discussions = $scope.allItems.discussions.slice();
        $scope.allItems.discussions.reverse();
        $scope.discussions = $scope.discussions.slice();
        $scope.discussions.reverse();

        $scope.context = context;

        $window.onbeforeunload = function(){
            localStorage.removeItem("type");
        };

        $scope.reset = function(main){
             EntityService.setEntityFolderValue(undefined, undefined);
            localStorage.removeItem("type");
            $scope.typeSelected = null;
        };

        $scope.changeState = function(state){
            $state.go(state, {
                officeDocuments: undefined,
                activeTab: $scope.item
            }, {reload: false});
        };

        $scope.typeSelected = localStorage.getItem("type");
        $scope.switchToType = function (type) {
            EntityService.setActiveStatusFilterValue(type.name);
            OfficeDocumentsService.getAll(0,25,EntityService.getSortFilterValue().field, EntityService.getSortFilterValue().order,type.name).then(function (result) {

            $scope.officeDocuments=result;

         $scope.typeSelected = type.name;

         if (context.entityName == 'folder') {
             $scope.officeDocuments = $scope.officeDocuments.filter(function (officeDocument) {
                 return officeDocument.status == type.name && officeDocument.folder && officeDocument.folder._id == context.entityId;
             });
         } else {

             $scope.officeDocuments = $scope.officeDocuments.filter(function (officeDocument) {
                 return officeDocument.status == type.name;
             });
         }

         localStorage.setItem("type", type.name);

         $state.go($state.current, {
             officeDocuments: $scope.officeDocuments,
             activeTab: $scope.item
         }, { reload: true });
            });

         /**
         var temp=[];
         $scope.officeDocuments.forEach(function(d){
             temp.push(d);
         });
         temp = temp.filter(function(officeDocument){
             if(context.entityName=='folder'){
                 return officeDocument.status == type.name &&officeDocument.folder&& officeDocument.folder._id==context.entityId ;
             }
             else{
                 return officeDocument.status == type.name;
             }
          });
           /*if(context.entityName == 'all'){
             $state.go('main.' + context.main + '.all', {},{reload: true});
         }else if (context.entityName == 'folder'){
             $state.go('main.' + context.main + '.byentity', {
                 entityId: context.entityId,
                 entity: 'folder',
                 officeDocuments: temp
             },{reload: true});
         }*/
     };
        $scope.switchTo = function (entityName, id) {
            EntityService.setEntityFolderValue(entityName, id);
            OfficeDocumentsService.getAll(0,25,EntityService.getSortFilterValue().field,
                                               EntityService.getSortFilterValue().order,
                                               EntityService.getActiveStatusFilterValue(),
                                               EntityService.getEntityFolderValue().id).then(function (result) {

            $state.go('main.' + context.main + '.byentity', {
                entity: entityName,
                entityId: id
            });
        });
            // If we are switching between entities, then shrink the display limit again
            if (!$scope.visible[entityName]) {
                $scope.displayLimit.reset();
            }

        };

        $scope.switchToAll = function (entityName, id) {
            $state.go('main.' + context.main + '.all.details.activities', {
                id: id,
                entity: entityName,
            });
        };

        $scope.visible = {
            project: true,
            discussion: true,
            user: true,
            officeDocument: true,
            office: true,
            folder: true
        };

        $scope.visible[$scope.context.entityName] = true;

        $scope.GoToFolders = function() {
            $state.go('main.folders.all');
        };

        $scope.GoToOffices = function() {
            $state.go('main.offices.all');
        };

        $scope.GoToTemplateDocs = function() {
            $state.go('main.templateDocs.all');
        };

        $scope.GoToAdminSettings = function() {
            $state.go('main.adminSettings');
        }
    }

        function link($scope, $element, context) {
            $scope.showMore = function(limit, entityName) {
                if (($scope.displayLimit[entityName] + 4) >= limit) {
                    $scope.displayLimit[entityName] = limit;
                } else {
                    $scope.displayLimit[entityName]  += 4;

                }
            };

            $scope.collapse = function(entityName) {
                $scope.displayLimit[entityName] = $scope.displayLimit.default[entityName];
            };
        }

    return {
        restrict: 'A',
        templateUrl: '/icu/components/display-by/display-by.html',
        controller: controller,
        link: link
    };
});
<|endoftext|>


<commit_before>import {concat} from 'ramda';

export const DIALECTS = {
    MYSQL: 'mysql',
    MARIADB: 'mariadb',
    POSTGRES: 'postgres',
    REDSHIFT: 'redshift',
    ELASTICSEARCH: 'elasticsearch',
    MSSQL: 'mssql',
    SQLITE: 'sqlite',
    S3: 's3',
    APACHE_DRILL: 'apache drill'
};

const commonSqlOptions = [
    {'label': 'Username', 'value': 'username', 'type': 'text'},
    {'label': 'Password', 'value': 'password', 'type': 'password'},
    {
        'label': 'Host',
        'value': 'host',
        'type': 'text'
    },
    {
        'label': 'Port',
        'value': 'port',
        'type': 'number',
        'description': 'Server port number (e.g. 3306)'
    },
    {'label': 'Database', 'value': 'database', 'type': 'text'},
    {'label': 'SSL Enabled', 'value': 'ssl', 'type': 'checkbox'}
];
export const CONNECTION_CONFIG = {
    [DIALECTS.MYSQL]: commonSqlOptions,
    [DIALECTS.MARIADB]: commonSqlOptions,
	[DIALECTS.MSSQL]: concat(
        commonSqlOptions, [
            {
                'label': 'Connection Timeout',
                'value': 'connectTimeout',
                'description': `
                    The number of milliseconds before the
                    attempt to connect is considered failed
                    (default: 15000).
                `,
                'placeholder': 15000,
                'type': 'number'
            },
            {
                'label': 'Request Timeout',
                'value': 'requestTimeout',
                'description': `
                    The number of milliseconds before a request is considered
                    failed, or 0 for no timeout (default: 15000).
                `,
                'placeholder': 15000,
                'type': 'number'
            }
        ]
    ),
    [DIALECTS.POSTGRES]: commonSqlOptions,
    [DIALECTS.REDSHIFT]: commonSqlOptions,
    [DIALECTS.SQLITE]: [
        {'label': 'Path to SQLite File', 'value': 'storage', 'type': 'path'}
    ],

    // TODO - What are the actual elasticsearch connection options?
    [DIALECTS.ELASTICSEARCH]: [
        {'label': 'Username', 'value': 'username', 'type': 'text'},
        {'label': 'Password', 'value': 'password', 'type': 'text'},
        {'label': 'Host', 'value': 'host', 'type': 'text'},
        {'label': 'Port', 'value': 'port', 'type': 'text'}
    ],
    [DIALECTS.S3]: [
        {'label': 's3 Bucket', 'value': 'bucket', 'type': 'text'},
        {'label': 'S3 Access Key ID', 'value': 'accessKeyId', 'type': 'text'},
        {
            'label': 'S3 Secret Access Key',
            'value': 'secretAccessKey',
            'type': 'password'
        }
    ],
    [DIALECTS.APACHE_DRILL]: [
        {'label': 'Host', 'value': 'host', 'type': 'text'},
        {'label': 'Port', 'value': 'port', 'type': 'text'},
        {'label': 'S3 Bucket Name', 'value': 'bucket', 'type': 'text'},
        {'label': 'S3 Access Key ID', 'value': 'accessKeyId', 'type': 'text'},
        {
            'label': 'S3 Secret Access Key',
            'value': 'secretAccessKey',
            'type': 'password'
        }
    ] // TODO - password options for apache drill
};

export const LOGOS = {
    [DIALECTS.REDSHIFT]: 'images/redshift-logo.png',
    [DIALECTS.POSTGRES]: 'images/postgres-logo.png',
    [DIALECTS.ELASTICSEARCH]: 'images/elastic-logo.png',
    [DIALECTS.MYSQL]: 'images/mysql-logo.png',
    [DIALECTS.MARIADB]: 'images/mariadb-logo.png',
    [DIALECTS.MSSQL]: 'images/mssql-logo.png',
    [DIALECTS.SQLITE]: 'images/sqlite-logo.png',
    [DIALECTS.S3]: 'images/s3-logo.png',
    [DIALECTS.APACHE_DRILL]: 'images/apache_drill-logo.png'
};

export const INITIAL_CONNECTIONS = {
    username: '',
    password: '',
    database: '',
    index: '',
    doc: '',
    dialect: DIALECTS.MYSQL,
    port: '',
    host: '',
    ssl: false
};
<commit_msg>capitalize s3<commit_after>import {concat} from 'ramda';

export const DIALECTS = {
    MYSQL: 'mysql',
    MARIADB: 'mariadb',
    POSTGRES: 'postgres',
    REDSHIFT: 'redshift',
    ELASTICSEARCH: 'elasticsearch',
    MSSQL: 'mssql',
    SQLITE: 'sqlite',
    S3: 's3',
    APACHE_DRILL: 'apache drill'
};

const commonSqlOptions = [
    {'label': 'Username', 'value': 'username', 'type': 'text'},
    {'label': 'Password', 'value': 'password', 'type': 'password'},
    {
        'label': 'Host',
        'value': 'host',
        'type': 'text'
    },
    {
        'label': 'Port',
        'value': 'port',
        'type': 'number',
        'description': 'Server port number (e.g. 3306)'
    },
    {'label': 'Database', 'value': 'database', 'type': 'text'},
    {'label': 'SSL Enabled', 'value': 'ssl', 'type': 'checkbox'}
];
export const CONNECTION_CONFIG = {
    [DIALECTS.MYSQL]: commonSqlOptions,
    [DIALECTS.MARIADB]: commonSqlOptions,
	[DIALECTS.MSSQL]: concat(
        commonSqlOptions, [
            {
                'label': 'Connection Timeout',
                'value': 'connectTimeout',
                'description': `
                    The number of milliseconds before the
                    attempt to connect is considered failed
                    (default: 15000).
                `,
                'placeholder': 15000,
                'type': 'number'
            },
            {
                'label': 'Request Timeout',
                'value': 'requestTimeout',
                'description': `
                    The number of milliseconds before a request is considered
                    failed, or 0 for no timeout (default: 15000).
                `,
                'placeholder': 15000,
                'type': 'number'
            }
        ]
    ),
    [DIALECTS.POSTGRES]: commonSqlOptions,
    [DIALECTS.REDSHIFT]: commonSqlOptions,
    [DIALECTS.SQLITE]: [
        {'label': 'Path to SQLite File', 'value': 'storage', 'type': 'path'}
    ],

    // TODO - What are the actual elasticsearch connection options?
    [DIALECTS.ELASTICSEARCH]: [
        {'label': 'Username', 'value': 'username', 'type': 'text'},
        {'label': 'Password', 'value': 'password', 'type': 'text'},
        {'label': 'Host', 'value': 'host', 'type': 'text'},
        {'label': 'Port', 'value': 'port', 'type': 'text'}
    ],
    [DIALECTS.S3]: [
        {'label': 'S3 Bucket', 'value': 'bucket', 'type': 'text'},
        {'label': 'S3 Access Key ID', 'value': 'accessKeyId', 'type': 'text'},
        {
            'label': 'S3 Secret Access Key',
            'value': 'secretAccessKey',
            'type': 'password'
        }
    ],
    [DIALECTS.APACHE_DRILL]: [
        {'label': 'Host', 'value': 'host', 'type': 'text'},
        {'label': 'Port', 'value': 'port', 'type': 'text'},
        {'label': 'S3 Bucket Name', 'value': 'bucket', 'type': 'text'},
        {'label': 'S3 Access Key ID', 'value': 'accessKeyId', 'type': 'text'},
        {
            'label': 'S3 Secret Access Key',
            'value': 'secretAccessKey',
            'type': 'password'
        }
    ] // TODO - password options for apache drill
};

export const LOGOS = {
    [DIALECTS.REDSHIFT]: 'images/redshift-logo.png',
    [DIALECTS.POSTGRES]: 'images/postgres-logo.png',
    [DIALECTS.ELASTICSEARCH]: 'images/elastic-logo.png',
    [DIALECTS.MYSQL]: 'images/mysql-logo.png',
    [DIALECTS.MARIADB]: 'images/mariadb-logo.png',
    [DIALECTS.MSSQL]: 'images/mssql-logo.png',
    [DIALECTS.SQLITE]: 'images/sqlite-logo.png',
    [DIALECTS.S3]: 'images/s3-logo.png',
    [DIALECTS.APACHE_DRILL]: 'images/apache_drill-logo.png'
};

export const INITIAL_CONNECTIONS = {
    username: '',
    password: '',
    database: '',
    index: '',
    doc: '',
    dialect: DIALECTS.MYSQL,
    port: '',
    host: '',
    ssl: false
};
<|endoftext|>


<commit_before>import merge from 'lodash/merge';
import path from 'path';
import store from './scenariooStore';
import docuWriter from './docuWriter/docuWriter';
import scenarioo from './scenarioo-js';

const SUCCESS = 'success';
const FAILED = 'failed';
const SKIPPED = 'skipped';

/**
 * This is the base reporter that pulls information from the store and the calling (framework-dependant) reporter
 * and invokes docuWriter in order to create the scenarioo documentation.
 *
 * This base reporter is testing-framework agnostic!
 *
 * @namespace scenariooReporter
 */
export default {
  runStarted,
  runEnded,

  useCaseStarted,
  useCaseEnded,

  scenarioStarted,
  scenarioEnded,

  expectationFailed,

  /** @constant {string} scenariooReporter#SUCCESS*/
  SUCCESS,
  /** @constant {string} scenariooReporter#FAILED*/
  FAILED,
  /** @constant {string} scenariooReporter#SKIPPED*/
  SKIPPED
};

/**
 * @func scenariooReporter#runStarted
 * @param {object} options
 */
function runStarted(options) {
  // some reporters (jasmine) need to initialize the store even before the run starts
  // so at this point here, the store might already be set up and good to go.
  if (!store.isInitialized()) {
    store.init(options);
  }

  if (options.pageNameExtractor) {
    docuWriter.registerPageNameFunction(options.pageNameExtractor);
  }

  const absoluteTargetDir = path.resolve(options.targetDirectory);
  store.setBuildDate(new Date());
  docuWriter.start(store.getBranch(), store.getBuild().name, absoluteTargetDir);

  console.log(`Reporting scenarios for scenarioo. Writing to "${absoluteTargetDir}"`);
}

/**
 * @func scenariooReporter#runEnded
 */
function runEnded() {
  if (!store.isInitialized()) {
    throw new Error('Cannot end test run. No test run was started');
  }

  const build = store.getBuild();
  const status = (build.failedUseCases === 0) ? 'success' : 'failed';

  docuWriter.saveBuild({
    status: status,
    name: build.name,
    date: build.date,
    revision: build.revision
  });

  store.clear();

  console.log('All done!');
}

/**
 * @func scenariooReporter#useCaseStarted
 * @param {string} useCaseName
 */
function useCaseStarted(useCaseName) {
  if (!store.isInitialized()) {
    throw new Error('Cannot start useCase, run was not started!');
  }
  store.updateCurrentUseCase({
    passedScenarios: 0,
    failedScenarios: 0,
    skippedScenarios: 0,
    name: useCaseName
  });
}

/**
 * @func scenariooReporter#useCaseEnded
 */
function useCaseEnded() {
  const useCase = store.getCurrentUseCase();
  const build = store.getBuild();

  const hasFailingScenarios = useCase.failedScenarios > 0;
  const hasPassedScenarios = useCase.passedScenarios > 0;
  const hasSkippedScenarios = useCase.skippedScenarios > 0;
  let useCaseStatus;
  if (hasFailingScenarios) {
    store.updateBuild({
      failedUseCases: build.failedUseCases + 1
    });
    useCaseStatus = FAILED;
  } else if (hasPassedScenarios) {
    store.updateBuild({
      passedUseCases: build.passedUseCases + 1
    });
    useCaseStatus = SUCCESS;
  } else if (hasSkippedScenarios) {
    store.updateBuild({
      skippedUseCases: build.skippedUseCases + 1
    });
    useCaseStatus = SKIPPED;
  }

  console.log(`useCase :: ${useCase.name} :: ${translateStatusForLogMessages(useCaseStatus)} (${useCase.passedScenarios} passed, ${useCase.failedScenarios} failed, ${ useCase.skippedScenarios} skipped)`);

  docuWriter.saveUseCase(merge({
    status: useCaseStatus
  }, useCase));

  store.resetCurrentUseCase();
}

/**
 * @func scenariooReporter#scenarioStarted
 * @param {string} scenarioName
 */
function scenarioStarted(scenarioName) {
  store.updateCurrentScenario({
    stepCounter: -1,
    name: scenarioName,
    status: undefined
  });
}

function expectationFailed(options, failureMessage) {
  store.updateCurrentScenario({ status: 'failed'}); // remember early that it failed allready
  if (options.reportStepOnExpectationFailed) {
    scenarioo.saveStep(failureMessage, {status: 'failed', labels: ['error']});
  }
}

/**
 * @func scenariooReporter#scenarioEnded
 * @param {string} status one of {@link scenariooReporter#SUCCESS}, {@link scenariooReporter#FAILED}, {@link scenariooReporter#SKIPPED}
 */
function scenarioEnded(status) {
  const scenario = store.getCurrentScenario();
  const useCase = store.getCurrentUseCase();

  switch (status) {
    case SUCCESS:
      store.updateCurrentUseCase({
        passedScenarios: useCase.passedScenarios + 1
      });
      break;
    case FAILED:
      store.updateCurrentUseCase({
        failedScenarios: useCase.failedScenarios + 1
      });
      break;
    case SKIPPED:
      store.updateCurrentUseCase({
        skippedScenarios: useCase.skippedScenarios + 1
      });
      break;
    default:
      throw new Error(`Unknown status ${status}`);
  }

  console.log(`scenario :: ${scenario.name} :: ${translateStatusForLogMessages(status)}`);

  docuWriter.saveScenario(merge({
    status: status
  }, scenario), useCase.name);

  store.resetCurrentScenario();
}

function translateStatusForLogMessages(status) {
  if (!status) {
    return 'n/a';
  }

  const map = {};
  map[SUCCESS] = 'suceeded';
  map[FAILED] = 'failed';
  map[SKIPPED] = 'skipped';
  const mapped = map[status];
  if (!mapped) {
    return 'n/a';
  }
  return mapped;
}
<commit_msg>#17 improved title for expectation failed error steps<commit_after>import merge from 'lodash/merge';
import path from 'path';
import store from './scenariooStore';
import docuWriter from './docuWriter/docuWriter';
import scenarioo from './scenarioo-js';

const SUCCESS = 'success';
const FAILED = 'failed';
const SKIPPED = 'skipped';

/**
 * This is the base reporter that pulls information from the store and the calling (framework-dependant) reporter
 * and invokes docuWriter in order to create the scenarioo documentation.
 *
 * This base reporter is testing-framework agnostic!
 *
 * @namespace scenariooReporter
 */
export default {
  runStarted,
  runEnded,

  useCaseStarted,
  useCaseEnded,

  scenarioStarted,
  scenarioEnded,

  expectationFailed,

  /** @constant {string} scenariooReporter#SUCCESS*/
  SUCCESS,
  /** @constant {string} scenariooReporter#FAILED*/
  FAILED,
  /** @constant {string} scenariooReporter#SKIPPED*/
  SKIPPED
};

/**
 * @func scenariooReporter#runStarted
 * @param {object} options
 */
function runStarted(options) {
  // some reporters (jasmine) need to initialize the store even before the run starts
  // so at this point here, the store might already be set up and good to go.
  if (!store.isInitialized()) {
    store.init(options);
  }

  if (options.pageNameExtractor) {
    docuWriter.registerPageNameFunction(options.pageNameExtractor);
  }

  const absoluteTargetDir = path.resolve(options.targetDirectory);
  store.setBuildDate(new Date());
  docuWriter.start(store.getBranch(), store.getBuild().name, absoluteTargetDir);

  console.log(`Reporting scenarios for scenarioo. Writing to "${absoluteTargetDir}"`);
}

/**
 * @func scenariooReporter#runEnded
 */
function runEnded() {
  if (!store.isInitialized()) {
    throw new Error('Cannot end test run. No test run was started');
  }

  const build = store.getBuild();
  const status = (build.failedUseCases === 0) ? 'success' : 'failed';

  docuWriter.saveBuild({
    status: status,
    name: build.name,
    date: build.date,
    revision: build.revision
  });

  store.clear();

  console.log('All done!');
}

/**
 * @func scenariooReporter#useCaseStarted
 * @param {string} useCaseName
 */
function useCaseStarted(useCaseName) {
  if (!store.isInitialized()) {
    throw new Error('Cannot start useCase, run was not started!');
  }
  store.updateCurrentUseCase({
    passedScenarios: 0,
    failedScenarios: 0,
    skippedScenarios: 0,
    name: useCaseName
  });
}

/**
 * @func scenariooReporter#useCaseEnded
 */
function useCaseEnded() {
  const useCase = store.getCurrentUseCase();
  const build = store.getBuild();

  const hasFailingScenarios = useCase.failedScenarios > 0;
  const hasPassedScenarios = useCase.passedScenarios > 0;
  const hasSkippedScenarios = useCase.skippedScenarios > 0;
  let useCaseStatus;
  if (hasFailingScenarios) {
    store.updateBuild({
      failedUseCases: build.failedUseCases + 1
    });
    useCaseStatus = FAILED;
  } else if (hasPassedScenarios) {
    store.updateBuild({
      passedUseCases: build.passedUseCases + 1
    });
    useCaseStatus = SUCCESS;
  } else if (hasSkippedScenarios) {
    store.updateBuild({
      skippedUseCases: build.skippedUseCases + 1
    });
    useCaseStatus = SKIPPED;
  }

  console.log(`useCase :: ${useCase.name} :: ${translateStatusForLogMessages(useCaseStatus)} (${useCase.passedScenarios} passed, ${useCase.failedScenarios} failed, ${ useCase.skippedScenarios} skipped)`);

  docuWriter.saveUseCase(merge({
    status: useCaseStatus
  }, useCase));

  store.resetCurrentUseCase();
}

/**
 * @func scenariooReporter#scenarioStarted
 * @param {string} scenarioName
 */
function scenarioStarted(scenarioName) {
  store.updateCurrentScenario({
    stepCounter: -1,
    name: scenarioName,
    status: undefined
  });
}

function expectationFailed(options, failureMessage) {
  store.updateCurrentScenario({ status: 'failed'}); // remember early that it failed allready
  if (options.reportStepOnExpectationFailed) {
    scenarioo.saveStep('Error: ' + failureMessage, {status: 'failed', labels: ['error']});
  }
}

/**
 * @func scenariooReporter#scenarioEnded
 * @param {string} status one of {@link scenariooReporter#SUCCESS}, {@link scenariooReporter#FAILED}, {@link scenariooReporter#SKIPPED}
 */
function scenarioEnded(status) {
  const scenario = store.getCurrentScenario();
  const useCase = store.getCurrentUseCase();

  switch (status) {
    case SUCCESS:
      store.updateCurrentUseCase({
        passedScenarios: useCase.passedScenarios + 1
      });
      break;
    case FAILED:
      store.updateCurrentUseCase({
        failedScenarios: useCase.failedScenarios + 1
      });
      break;
    case SKIPPED:
      store.updateCurrentUseCase({
        skippedScenarios: useCase.skippedScenarios + 1
      });
      break;
    default:
      throw new Error(`Unknown status ${status}`);
  }

  console.log(`scenario :: ${scenario.name} :: ${translateStatusForLogMessages(status)}`);

  docuWriter.saveScenario(merge({
    status: status
  }, scenario), useCase.name);

  store.resetCurrentScenario();
}

function translateStatusForLogMessages(status) {
  if (!status) {
    return 'n/a';
  }

  const map = {};
  map[SUCCESS] = 'suceeded';
  map[FAILED] = 'failed';
  map[SKIPPED] = 'skipped';
  const mapped = map[status];
  if (!mapped) {
    return 'n/a';
  }
  return mapped;
}
<|endoftext|>


<commit_before><commit_msg>Support unaligned index buffer<commit_after><|endoftext|>


<commit_before>"use strict";

exports.db = {
  host: '',
  port: 3306,
  user: '',
  password: '',
  type: '',
  database: '',

  // Database filename for SQLite
  filename: '',

  // For debugging, log SQL statements to the console
  debug: true
};

exports.uris = {
  authorization_uri: "http://example.com/authorized"
};

exports.service_provider_id = "example_service_provider";
<commit_msg>Update config.dist<commit_after>"use strict";

exports.db = {
  host: '',
  port: 3306,
  user: '',
  password: '',
  type: '',
  database: '',

  // Database filename for SQLite
  filename: '',

  // For debugging, log SQL statements to the console
  debug: true
};

exports.uris = {
  authorization_uri: "http://example.com/authorized"
};

exports.service_provider_id = process.env.SP_ID || '1';
exports.service_provider_name = process.env.SP_NAME || 'STATION_NAME';
<|endoftext|>


<commit_before>/**
 * Licensed under the Apache License, Version 2.0 (the 'License');
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an 'AS IS' BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

goog.provide('org.apache.flex.binding.WatcherBase');

/**
 * @constructor
 */
org.apache.flex.binding.WatcherBase = function() {

  /**
     * @protected
     * @type {Object}
     */
  this.listeners = null;

  /**
     * @protected
     * @type {Object}
     * Children of this watcher are watching sub values.
     */
  this.children = null;

};

/**
 * Metadata
 *
 * @type {Object.<string, Array.<Object>>}
 */
org.apache.flex.binding.WatcherBase.prototype.FLEXJS_CLASS_INFO =
    { names: [{ name: 'WatcherBase',
                qName: 'org.apache.flex.binding.WatcherBase'}] };

/**
 *  @expose
 *  @type {Object|number|string|boolean}
 *  The value itself.
 */
org.apache.flex.binding.WatcherBase.prototype.value = null;

/**
 *  @expose
 *  This is an abstract method that subclasses implement.
 *  @this {org.apache.flex.binding.WatcherBase}
 *  @param {Object} parent The new parent.
 */
org.apache.flex.binding.WatcherBase.prototype.parentChanged =
    function(parent) {
};

/**
 *  @expose
 *  Add a child to this watcher, meaning that the child
 *  is watching a sub value of ours.
 *  @this {org.apache.flex.binding.WatcherBase}
 *  @param {Object} child The new child.
 */
org.apache.flex.binding.WatcherBase.prototype.addChild =
    function(child) {
  if (!this.children)
    this.children = [child];
  else
    this.children.push(child);

  child.parentChanged(this);
};

/**
 *  @expose
 *  Add a binding to this watcher, meaning that the binding
 *  is notified when our value changes.
 *  @this {org.apache.flex.binding.WatcherBase}
 *  @param {Object} binding The new binding.
 */
org.apache.flex.binding.WatcherBase.prototype.addBinding =
    function(binding) {
  if (!this.listeners)
    this.listeners = [binding];
  else
    this.listeners.push(binding);

  binding.valueChanged(this.value);
};

/**
 *  @expose
 *  @this {org.apache.flex.binding.WatcherBase}
 *  We have probably changed, so go through
 *  and make sure our children are updated.
 */
org.apache.flex.binding.WatcherBase.prototype.updateChildren = function() {
  if (this.children)
  {
    var n = this.children.length;
    for (var i = 0; i < n; ++i)
    {
      this.children[i].parentChanged(this);
    }
  }
};

/**
 *  @protected
 *  @this {org.apache.flex.binding.WatcherBase}
 *  @param {Object} oldValue The prior value.
 *  @return {boolean} True if value changed.
 */
org.apache.flex.binding.WatcherBase.prototype.valueChanged =
    function(oldValue) {

  if (oldValue == null && this.value == null)
    return false;

  var valType = typeof(this.value);

  // The first check is meant to catch the delayed instantiation case
  // where a control comes into existence but its value is still
  // the equivalent of not having been filled in.
  // Otherwise we simply return whether the value has changed.

  if (valType == 'string')
  {
    if (oldValue == null && this.value === '')
      return false;
    else
      return oldValue != this.value;
  }

  if (valType == 'number')
  {
    if (oldValue == null && this.value === 0)
      return false;
    else
      return oldValue != this.value;
  }

  if (valType == 'boolean')
  {
    if (oldValue == null && this.value === false)
      return false;
    else
      return oldValue != this.value;
  }

  return true;
};

/**
 *  @protected
 *  @this {org.apache.flex.binding.WatcherBase}
 *  @param {function(?): ?} wrappedFunction The function to call.
 */
org.apache.flex.binding.WatcherBase.prototype.wrapUpdate =
    function(wrappedFunction) {
  try
  {
    wrappedFunction.apply(this);
  }
  catch (error)
  {
    var staticClass = org.apache.flex.binding.WatcherBase;
    var n = staticClass.allowedErrorTypes.length;
    for (var i = 0; i < n; i++)
    {
      if (org.apache.flex.utils.Language.is(error, staticClass.allowedErrorTypes[i].type))
      {
        var handler = staticClass.allowedErrorTypes[i].handler;
        if (handler != null)
          this.value = handler(this, wrappedFunction);
        else
          this.value = null;
      }
    }

    if (error.errorID && staticClass.allowedErrors.indexOf(error.errorID) == -1) {
      throw error;
    }
  }
};

/**
 * Certain errors are normal when executing an update, so we swallow them:
 */
org.apache.flex.binding.WatcherBase.allowedErrors = [
  1006, //   Error #1006: Call attempted on an object
  //                that is not a function.
  1009, //   Error #1009: null has no properties.
  1010, //   Error #1010: undefined has no properties.
  1055, //   Error #1055: - has no properties.
  1069, //   Error #1069: Property - not found on - and
  //                there is no default value
  1507 //   Error #1507: - invalid null argument.
];

/**
 * Certain types of errors are normal when executing an update,
 * so we custom handle them or swallow them:
 */
org.apache.flex.binding.WatcherBase.allowedErrorTypes = [
  { type: RangeError /*,
              handler: function(w:WatcherBase,
                    wrappedFunction:Function):Object { return null }*/
  }
];

/**
 *  @protected
 *  @this {org.apache.flex.binding.WatcherBase}
 */
org.apache.flex.binding.WatcherBase.prototype.notifyListeners = function()
    {
  if (this.listeners)
  {
    var n = this.listeners.length;

    for (var i = 0; i < n; i++)
    {
      this.listeners[i].valueChanged(this.value);
    }
  }
};
<commit_msg>fix watcher chaining<commit_after>/**
 * Licensed under the Apache License, Version 2.0 (the 'License');
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an 'AS IS' BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

goog.provide('org.apache.flex.binding.WatcherBase');

/**
 * @constructor
 */
org.apache.flex.binding.WatcherBase = function() {

  /**
     * @protected
     * @type {Object}
     */
  this.listeners = null;

  /**
     * @protected
     * @type {Object}
     * Children of this watcher are watching sub values.
     */
  this.children = null;

};

/**
 * Metadata
 *
 * @type {Object.<string, Array.<Object>>}
 */
org.apache.flex.binding.WatcherBase.prototype.FLEXJS_CLASS_INFO =
    { names: [{ name: 'WatcherBase',
                qName: 'org.apache.flex.binding.WatcherBase'}] };

/**
 *  @expose
 *  @type {Object|number|string|boolean}
 *  The value itself.
 */
org.apache.flex.binding.WatcherBase.prototype.value = null;

/**
 *  @expose
 *  This is an abstract method that subclasses implement.
 *  @this {org.apache.flex.binding.WatcherBase}
 *  @param {Object} parent The new parent.
 */
org.apache.flex.binding.WatcherBase.prototype.parentChanged =
    function(parent) {
};

/**
 *  @expose
 *  Add a child to this watcher, meaning that the child
 *  is watching a sub value of ours.
 *  @this {org.apache.flex.binding.WatcherBase}
 *  @param {Object} child The new child.
 */
org.apache.flex.binding.WatcherBase.prototype.addChild =
    function(child) {
  if (!this.children)
    this.children = [child];
  else
    this.children.push(child);

  child.parentChanged(this.value);
};

/**
 *  @expose
 *  Add a binding to this watcher, meaning that the binding
 *  is notified when our value changes.
 *  @this {org.apache.flex.binding.WatcherBase}
 *  @param {Object} binding The new binding.
 */
org.apache.flex.binding.WatcherBase.prototype.addBinding =
    function(binding) {
  if (!this.listeners)
    this.listeners = [binding];
  else
    this.listeners.push(binding);

  binding.valueChanged(this.value);
};

/**
 *  @expose
 *  @this {org.apache.flex.binding.WatcherBase}
 *  We have probably changed, so go through
 *  and make sure our children are updated.
 */
org.apache.flex.binding.WatcherBase.prototype.updateChildren = function() {
  if (this.children)
  {
    var n = this.children.length;
    for (var i = 0; i < n; ++i)
    {
      this.children[i].parentChanged(this);
    }
  }
};

/**
 *  @protected
 *  @this {org.apache.flex.binding.WatcherBase}
 *  @param {Object} oldValue The prior value.
 *  @return {boolean} True if value changed.
 */
org.apache.flex.binding.WatcherBase.prototype.valueChanged =
    function(oldValue) {

  if (oldValue == null && this.value == null)
    return false;

  var valType = typeof(this.value);

  // The first check is meant to catch the delayed instantiation case
  // where a control comes into existence but its value is still
  // the equivalent of not having been filled in.
  // Otherwise we simply return whether the value has changed.

  if (valType == 'string')
  {
    if (oldValue == null && this.value === '')
      return false;
    else
      return oldValue != this.value;
  }

  if (valType == 'number')
  {
    if (oldValue == null && this.value === 0)
      return false;
    else
      return oldValue != this.value;
  }

  if (valType == 'boolean')
  {
    if (oldValue == null && this.value === false)
      return false;
    else
      return oldValue != this.value;
  }

  return true;
};

/**
 *  @protected
 *  @this {org.apache.flex.binding.WatcherBase}
 *  @param {function(?): ?} wrappedFunction The function to call.
 */
org.apache.flex.binding.WatcherBase.prototype.wrapUpdate =
    function(wrappedFunction) {
  try
  {
    wrappedFunction.apply(this);
  }
  catch (error)
  {
    var staticClass = org.apache.flex.binding.WatcherBase;
    var n = staticClass.allowedErrorTypes.length;
    for (var i = 0; i < n; i++)
    {
      if (org.apache.flex.utils.Language.is(error, staticClass.allowedErrorTypes[i].type))
      {
        var handler = staticClass.allowedErrorTypes[i].handler;
        if (handler != null)
          this.value = handler(this, wrappedFunction);
        else
          this.value = null;
      }
    }

    if (error.errorID && staticClass.allowedErrors.indexOf(error.errorID) == -1) {
      throw error;
    }
  }
};

/**
 * Certain errors are normal when executing an update, so we swallow them:
 */
org.apache.flex.binding.WatcherBase.allowedErrors = [
  1006, //   Error #1006: Call attempted on an object
  //                that is not a function.
  1009, //   Error #1009: null has no properties.
  1010, //   Error #1010: undefined has no properties.
  1055, //   Error #1055: - has no properties.
  1069, //   Error #1069: Property - not found on - and
  //                there is no default value
  1507 //   Error #1507: - invalid null argument.
];

/**
 * Certain types of errors are normal when executing an update,
 * so we custom handle them or swallow them:
 */
org.apache.flex.binding.WatcherBase.allowedErrorTypes = [
  { type: RangeError /*,
              handler: function(w:WatcherBase,
                    wrappedFunction:Function):Object { return null }*/
  }
];

/**
 *  @protected
 *  @this {org.apache.flex.binding.WatcherBase}
 */
org.apache.flex.binding.WatcherBase.prototype.notifyListeners = function()
    {
  if (this.listeners)
  {
    var n = this.listeners.length;

    for (var i = 0; i < n; i++)
    {
      this.listeners[i].valueChanged(this.value);
    }
  }
};
<|endoftext|>


<commit_before>/*
  An easy Node.js package for work with Faragate Online Payment api.
  Developer: Erfan Sahafnejad
  Email: Erfan.Sahaf@gmail.com
  Github: http://github.com/erfansahaf/
  License: Apache License V2.0

  This sample is on Development mode. For production see faragate-nodejs github repository.
*/
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var faragate = require("./faragate");

var app = express();
var marchent = "YOUR_MARCHENT_CODE";

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));

app.get('/', function(req, res){
    faragate.paymentRequest(res, marchent, "10000", "http://localhost:3000/","0123456789", {SandBox:true});
});
app.post("/", function(req, res){
    var token = req.body.Token;
    faragate.verifyPayment(marchent, token, function(status, code, message){
        var text = "Payment status: " + status + "
Code: " + code + "
Message: " + message;
        res.send(text);
    }, true);
})

app.get('/balance', function(req, res){
    faragate.getBalance("username", "password", function(balance, code, message){
      res.send(balance + " Rial" + "
Message: " + message);
    });
});

app.listen(3000, function(){console.log("Server is running...");})

module.exports = app;
<commit_msg>Update sample<commit_after>/*
  An easy Node.js package for work with Faragate Online Payment api.
  Developer: Erfan Sahafnejad
  Email: Erfan.Sahaf@gmail.com
  Github: http://github.com/erfansahaf/
  License: Apache License V2.0

  This sample is on Development mode. For production see faragate-nodejs github repository.
*/
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var faragate = require("./faragate");

var app = express();
var marchent = "YOUR_MARCHENT_CODE";

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));

app.get('/', function(req, res){
    faragate.paymentRequest(res, marchent, "10000", "http://localhost:3000/","0123456789", {SandBox:true});
});
app.post("/", function(req, res){
    var token = req.body.Token;
    var sandBox = req.body.SandBox ? true : false;
    // You can get invoice number of previous payment request by req.body.InvoiceNumber
    var invoiceNumber = req.body.InvoiceNumber;

    faragate.verifyPayment(marchent, token, function(status, code, message){
        var text = "Payment status: " + status + "
Code: " + code + "
Message: " + message;
        res.send(text);
    }, sandbox);
})

app.get('/balance', function(req, res){
    faragate.getBalance("username", "password", function(balance, code, message){
      res.send(balance + " Rial" + "
Message: " + message);
    });
});

app.listen(3000, function(){console.log("Server is running...");})

module.exports = app;
<|endoftext|>


<commit_before>'use strict';
const fs = require('fs-extra');
const path = require('path');
const structurePath = path.resolve(__dirname, './__EXT_CONTAINER_STRUCTURE');

function getExtensionPaths(options) {
  if (options.source !== 'npm') {
    throw new Error('invalid extension type');
  }
  return {
    package: path.join(this.config.app_root, 'node_modules', options.name, 'package.json'),
    ext: path.join(this.config.app_root, 'node_modules', options.name, 'periodicjs.ext.json'),
  };
}

function getExtensionDoc(options) {
  const createdat = new Date(); //Date.now();
  const updatedat = new Date(); //Date.now();
  const { ext_package_json, ext_config_json, ext_source, } = options;
  // console.log({ ext_config_json });
  const ext = Object.assign({},
    ext_config_json, {
      name: ext_package_json.name,
      version: ext_package_json.version,
      author: ext_package_json.author,
      contributors: ext_package_json.contributors,
      description: ext_package_json.description,
      source: ext_source,
      enabled: (typeof options.enabled === 'boolean') ? options.enabled : true,
      createdat,
      updatedat,
    });

  // console.log({ ext_package_json, ext_config_json, ext_source, ext })
  if (!ext.name) {
    throw new Error('Extension package.json is missing a name');
  }
  if (!ext.version) {
    throw new Error('Extension package.json is missing a version');
  }
  if (typeof ext.periodic_type !== 'number') {
    throw new Error('Extension periodicjs.ext.json is missing a periodic_type classification (0-core, 1-communication, 2-auth, 3-uac, 4-api, 5-admin,6-data,7-ui)');
  }
  if (typeof ext.periodic_priority !== 'number') {
    throw new Error('Extension periodicjs.ext.json is missing a periodic_priority');
  }
  if (!ext.periodic_compatibility) {
    throw new Error('Extension periodicjs.ext.json is missing a periodic_compatibility');
  }
  if (!ext.periodic_config) {
    throw new Error('Extension periodicjs.ext.json is missing a periodic_config');
  }

  return ext;
}

function create(options) {
  return new Promise((resolve, reject) => {
    try {
      const newdocOptions = Object.assign({}, options);
      if (typeof options === 'string') {
        newdocOptions.source = 'npm';
        newdocOptions.name = options;
      }
      const ext_source = newdocOptions.source;
      const extensionDB = this.datas.get('extension');
      const extPath = getExtensionPaths.call(this, newdocOptions);
      let createdExt;
      switch (ext_source) {
        case 'npm':
        default:
          Promise.all([
              fs.readJSON(extPath.package),
              fs.readJSON(extPath.ext),
            ])
            .then(results => {
              const [ext_package_json, ext_config_json, ] = results;
              const newdoc = getExtensionDoc({ ext_package_json, ext_config_json, ext_source, });
              return extensionDB.create({ newdoc, });
            })
            .then(createdDoc => {
              createdExt = createdDoc;
              return this.tasks.resetExtensions();
            })
            .then(resetedExtensions => {
              /** TODO: @irisdan should copy public directory from extension if it exists */
              resolve(createdExt);
            })
            .catch(reject);
          break;
      }
    } catch (e) {
      reject(e);
    }
  });
}

function update(options) {
  return new Promise((resolve, reject) => {
    const { ext, _id, } = options;
    const createdat = Date.now();
    const updatedat = Date.now();
    const extensionDB = this.datas.get('extension');
    let updatedDoc;
    try {
      extensionDB.update({
          updatedoc: Object.assign({},
            ext,
            (_id) ? { _id, } : {}, {
              createdat,
              updatedat,
            }),
        })
        .then(updatedExt => {
          updatedDoc = updatedExt;
          return this.tasks.resetExtensions();
        })
        .then(resetedExtensions => {
          resolve(updatedDoc);
        })
        .catch(reject);
      // resolve();
    } catch (e) {
      reject(e);
    }
  });
}

function remove(options) {
  return new Promise((resolve, reject) => {
    let { name, _id, } = options;
    const extensionDB = this.datas.get('extension');
    let deletedDoc;
    try {
      if (typeof options === 'string') {
        name = options;
      }
      // this.logger.info({ name, _id, });
      if (_id) {
        extensionDB.delete({
            id: _id,
          })
          .then(result => {
            // console.log({result,options});
            deletedDoc = result;
            return this.tasks.resetExtensions();
          })
          .then(resetedExtensions => {
            // console.log('DELETED ID',{deletedDoc})
            resolve(deletedDoc);
          })
          .catch(reject);

        resolve();
      } else {
        extensionDB.load({ docid: 'name', query: name, })
          .then(result => {
            if (!result) {
              resolve('extension not found');
            } else {
              return extensionDB.delete({ id: result._id, });
            }
          })
          .then(result => {
            deletedDoc = result;
            return this.tasks.resetExtensions();
          })
          .then(resetedExtensions => {
            // console.log({deletedDoc,options});
            resolve(deletedDoc);
          })
          .catch(reject);
      }
    } catch (e) {
      reject(e);
    }
  });
}

function list(options) {
  return new Promise((resolve, reject) => {
    try {
      this.datas.get('extension')
        .search({
          query: {},
          limit: 1000,
          sort: {
            periodic_type: 1,
            periodic_priority: 1,
          },
          //$p.crud.ext.list().then(console.log).catch(console.error);
          // $p.datas.get('extension').search({ query:{}, limit:1000,
          // sort: [
          // [ 'periodic_type', 'ASC' ],
          // [ 'periodic_priority', 'ASC' ],
          // ],
          // }).then(result => { console.log({ result }) }).catch(console.error);
        })
        .then(resolve)
        .catch(reject);
    } catch (e) {
      reject(e);
    }
  });
}

function init(container, options) {
  //
  return new Promise((resolve, reject) => {
    try {
      const extensionName = options.toString();
      const extensionPath = (container) ?
        path.join(this.config.app_root, 'content/container', extensionName) :
        path.join(this.config.app_root, 'node_modules', extensionName);
      const extensionPackageJsonPath = path.join(extensionPath, 'package.json');
      //create directory for extension
      fs.ensureDir(extensionPath)
        .then(() => {
          //copy structure
          return fs.copy(structurePath, extensionPath, { overwrite: false, });
        })
        .then(() => {
          return fs.readJSON(extensionPackageJsonPath);
        })
        .then(extPackageJson => {
          const updatedJSON = Object.assign({}, extPackageJson);
          updatedJSON.name = extensionName;
          updatedJSON.scripts.postinstall = `cd ../../ && periodicjs aex ${extensionName}`;
          updatedJSON.scripts.postuninstall = `cd ../../ && periodicjs rex ${extensionName}`;
          updatedJSON.name = extensionName;
          //update package.json
          return fs.outputJSON(extensionPackageJsonPath, updatedJSON, { spaces: 2, });
        })
        .then(() => {
          //update readme
          resolve(fs.outputFile(path.join(extensionPath, 'README.md'), generateREADME({ extensionName })));
        })
        .catch(reject);
    } catch (e) {
      reject(e);
    }
  });
}

function generateREADME(options) {
  const { extensionName, repoUserName = 'githubUserOrgName', repoPackageName = '' } = options;
  return `# ${extensionName} [![Coverage Status](https://coveralls.io/repos/github/${repoUserName}/${repoPackageName ||extensionName}/badge.svg?branch=master)](https://coveralls.io/github/${repoUserName}/${repoPackageName || extensionName}?branch=master) [![Build Status](https://travis-ci.org/${repoUserName}/${repoPackageName || extensionName}.svg?branch=master)](https://travis-ci.org/${repoUserName}/${repoPackageName || extensionName})

  A simple extension.

  [API Documentation](https://github.com/${repoUserName}/${repoPackageName || extensionName}/blob/master/doc/api.md)

  ## Usage

  ### CLI TASK

  You can preform a task via CLI
  \`\`\`
  $ cd path/to/application/root
  ### Using the CLI
  $ periodicjs ext ${extensionName} hello
  ### Calling Manually
  $ node index.js --cli --command --ext --name=${extensionName} --task=hello
  \`\`\`

  ## Configuration

  You can configure ${extensionName}

  ### Default Configuration
  \`\`\`javascript
  {
    settings: {
      defaults: true,
    },
    databases: {
    },
  };
  \`\`\`

  ## Installation

  ### Installing the Extension

  Install like any other extension, run \`npm run install ${extensionName}\` from your periodic application root directory and then normally you would run \`periodicjs addExtension ${extensionName}\`, but this extension does this in the post install npm script.
  \`\`\`
  $ cd path/to/application/root
  $ npm run install ${extensionName}
  $ periodicjs addExtension ${extensionName} //this extension does this in the post install script
  \`\`\`
  ### Uninstalling the Extension

  Run \`npm run uninstall ${extensionName}\` from your periodic application root directory and then normally you would run \`periodicjs removeExtension ${extensionName}\` but this extension handles this in the npm post uninstall script.
  \`\`\`
  $ cd path/to/application/root
  $ npm run uninstall ${extensionName}
  $ periodicjs removeExtension ${extensionName} // this is handled in the npm postinstall script
  \`\`\`

  ## Testing
  *Make sure you have grunt installed*
  \`\`\`
  $ npm install -g grunt-cli
  \`\`\`

  Then run grunt test or npm test
  \`\`\`
  $ grunt test && grunt coveralls #or locally $ npm test
  \`\`\`
  For generating documentation
  \`\`\`
  $ grunt doc
  $ jsdoc2md commands/**/*.js config/**/*.js controllers/**/*.js  transforms/**/*.js utilities/**/*.js index.js > doc/api.md
  \`\`\`
  ## Notes
  * Check out https://github.com/typesettin/periodicjs for the full Periodic Documentation`;
}

module.exports = {
  getExtensionPaths,
  getExtensionDoc,
  generateREADME,
  create,
  remove,
  update,
  list,
  init,
};<commit_msg>copying extension files<commit_after>'use strict';
const fs = require('fs-extra');
const path = require('path');
const structurePath = path.resolve(__dirname, './__EXT_CONTAINER_STRUCTURE');

function getExtensionPaths(options) {
  if (options.source !== 'npm') {
    throw new Error('invalid extension type');
  }
  return {
    package: path.join(this.config.app_root, 'node_modules', options.name, 'package.json'),
    ext: path.join(this.config.app_root, 'node_modules', options.name, 'periodicjs.ext.json'),
  };
}

function getExtensionDoc(options) {
  const createdat = new Date(); //Date.now();
  const updatedat = new Date(); //Date.now();
  const { ext_package_json, ext_config_json, ext_source, } = options;
  // console.log({ ext_config_json });
  const ext = Object.assign({},
    ext_config_json, {
      name: ext_package_json.name,
      version: ext_package_json.version,
      author: ext_package_json.author,
      contributors: ext_package_json.contributors,
      description: ext_package_json.description,
      source: ext_source,
      enabled: (typeof options.enabled === 'boolean') ? options.enabled : true,
      createdat,
      updatedat,
    });

  // console.log({ ext_package_json, ext_config_json, ext_source, ext })
  if (!ext.name) {
    throw new Error('Extension package.json is missing a name');
  }
  if (!ext.version) {
    throw new Error('Extension package.json is missing a version');
  }
  if (typeof ext.periodic_type !== 'number') {
    throw new Error('Extension periodicjs.ext.json is missing a periodic_type classification (0-core, 1-communication, 2-auth, 3-uac, 4-api, 5-admin,6-data,7-ui)');
  }
  if (typeof ext.periodic_priority !== 'number') {
    throw new Error('Extension periodicjs.ext.json is missing a periodic_priority');
  }
  if (!ext.periodic_compatibility) {
    throw new Error('Extension periodicjs.ext.json is missing a periodic_compatibility');
  }
  if (!ext.periodic_config) {
    throw new Error('Extension periodicjs.ext.json is missing a periodic_config');
  }

  return ext;
}

function create(options) {
  return new Promise((resolve, reject) => {
    try {
      const newdocOptions = Object.assign({}, options);
      if (typeof options === 'string') {
        newdocOptions.source = 'npm';
        newdocOptions.name = options;
      }
      const ext_source = newdocOptions.source;
      const extensionDB = this.datas.get('extension');
      const extPath = getExtensionPaths.call(this, newdocOptions);
      let createdExt;
      switch (ext_source) {
        case 'npm':
        default:
          Promise.all([
              fs.readJSON(extPath.package),
              fs.readJSON(extPath.ext),
            ])
            .then(results => {
              const [ext_package_json, ext_config_json, ] = results;
              const newdoc = getExtensionDoc({ ext_package_json, ext_config_json, ext_source, });
              return extensionDB.create({ newdoc, });
            })
            .then(createdDoc => {
              createdExt = createdDoc;
              return this.tasks.resetExtensions();
            })
            .then(resetedExtensions => {
              /** TODO: @irisdan should copy public directory from extension if it exists */
              const extPath = path.join(this.config.app_root, 'node_modules', newdocOptions.name);
              const extPubPath = path.join(extPath, 'public');
              const appPubExtPath = path.join(this.config.app_root, 'public/extensions', newdocOptions.name);
              if (fs.existsSync(extPubPath)) {
                fs.copy(extPubPath, appPubExtPath, { overwrite: false, })
                  .then(() => {
                    resoleve(createdExt);
                  })
                  .catch(reject);
              } else {
                resolve(createdExt);
              }
            })
            .catch(reject);
          break;
      }
    } catch (e) {
      reject(e);
    }
  });
}

function update(options) {
  return new Promise((resolve, reject) => {
    const { ext, _id, } = options;
    const createdat = Date.now();
    const updatedat = Date.now();
    const extensionDB = this.datas.get('extension');
    let updatedDoc;
    try {
      extensionDB.update({
          updatedoc: Object.assign({},
            ext,
            (_id) ? { _id, } : {}, {
              createdat,
              updatedat,
            }),
        })
        .then(updatedExt => {
          updatedDoc = updatedExt;
          return this.tasks.resetExtensions();
        })
        .then(resetedExtensions => {
          resolve(updatedDoc);
        })
        .catch(reject);
      // resolve();
    } catch (e) {
      reject(e);
    }
  });
}

function remove(options) {
  return new Promise((resolve, reject) => {
    let { name, _id, } = options;
    const extensionDB = this.datas.get('extension');
    let deletedDoc;
    try {
      if (typeof options === 'string') {
        name = options;
      }
      // this.logger.info({ name, _id, });
      if (_id) {
        extensionDB.delete({
            id: _id,
          })
          .then(result => {
            // console.log({result,options});
            deletedDoc = result;
            return this.tasks.resetExtensions();
          })
          .then(resetedExtensions => {
            // console.log('DELETED ID',{deletedDoc})
            resolve(deletedDoc);
          })
          .catch(reject);

        resolve();
      } else {
        extensionDB.load({ docid: 'name', query: name, })
          .then(result => {
            if (!result) {
              resolve('extension not found');
            } else {
              return extensionDB.delete({ id: result._id, });
            }
          })
          .then(result => {
            deletedDoc = result;
            return this.tasks.resetExtensions();
          })
          .then(resetedExtensions => {
            // console.log({deletedDoc,options});
            resolve(deletedDoc);
          })
          .catch(reject);
      }
    } catch (e) {
      reject(e);
    }
  });
}

function list(options) {
  return new Promise((resolve, reject) => {
    try {
      this.datas.get('extension')
        .search({
          query: {},
          limit: 1000,
          sort: {
            periodic_type: 1,
            periodic_priority: 1,
          },
          //$p.crud.ext.list().then(console.log).catch(console.error);
          // $p.datas.get('extension').search({ query:{}, limit:1000,
          // sort: [
          // [ 'periodic_type', 'ASC' ],
          // [ 'periodic_priority', 'ASC' ],
          // ],
          // }).then(result => { console.log({ result }) }).catch(console.error);
        })
        .then(resolve)
        .catch(reject);
    } catch (e) {
      reject(e);
    }
  });
}

function init(container, options) {
  //
  return new Promise((resolve, reject) => {
    try {
      const extensionName = options.toString();
      const extensionPath = (container) ?
        path.join(this.config.app_root, 'content/container', extensionName) :
        path.join(this.config.app_root, 'node_modules', extensionName);
      const extensionPackageJsonPath = path.join(extensionPath, 'package.json');
      //create directory for extension
      fs.ensureDir(extensionPath)
        .then(() => {
          //copy structure
          return fs.copy(structurePath, extensionPath, { overwrite: false, });
        })
        .then(() => {
          return fs.readJSON(extensionPackageJsonPath);
        })
        .then(extPackageJson => {
          const updatedJSON = Object.assign({}, extPackageJson);
          updatedJSON.name = extensionName;
          updatedJSON.scripts.postinstall = `cd ../../ && periodicjs aex ${extensionName}`;
          updatedJSON.scripts.postuninstall = `cd ../../ && periodicjs rex ${extensionName}`;
          updatedJSON.name = extensionName;
          //update package.json
          return fs.outputJSON(extensionPackageJsonPath, updatedJSON, { spaces: 2, });
        })
        .then(() => {
          //update readme
          resolve(fs.outputFile(path.join(extensionPath, 'README.md'), generateREADME({ extensionName })));
        })
        .catch(reject);
    } catch (e) {
      reject(e);
    }
  });
}

function generateREADME(options) {
  const { extensionName, repoUserName = 'githubUserOrgName', repoPackageName = '' } = options;
  return `# ${extensionName} [![Coverage Status](https://coveralls.io/repos/github/${repoUserName}/${repoPackageName ||extensionName}/badge.svg?branch=master)](https://coveralls.io/github/${repoUserName}/${repoPackageName || extensionName}?branch=master) [![Build Status](https://travis-ci.org/${repoUserName}/${repoPackageName || extensionName}.svg?branch=master)](https://travis-ci.org/${repoUserName}/${repoPackageName || extensionName})

  A simple extension.

  [API Documentation](https://github.com/${repoUserName}/${repoPackageName || extensionName}/blob/master/doc/api.md)

  ## Usage

  ### CLI TASK

  You can preform a task via CLI
  \`\`\`
  $ cd path/to/application/root
  ### Using the CLI
  $ periodicjs ext ${extensionName} hello
  ### Calling Manually
  $ node index.js --cli --command --ext --name=${extensionName} --task=hello
  \`\`\`

  ## Configuration

  You can configure ${extensionName}

  ### Default Configuration
  \`\`\`javascript
  {
    settings: {
      defaults: true,
    },
    databases: {
    },
  };
  \`\`\`

  ## Installation

  ### Installing the Extension

  Install like any other extension, run \`npm run install ${extensionName}\` from your periodic application root directory and then normally you would run \`periodicjs addExtension ${extensionName}\`, but this extension does this in the post install npm script.
  \`\`\`
  $ cd path/to/application/root
  $ npm run install ${extensionName}
  $ periodicjs addExtension ${extensionName} //this extension does this in the post install script
  \`\`\`
  ### Uninstalling the Extension

  Run \`npm run uninstall ${extensionName}\` from your periodic application root directory and then normally you would run \`periodicjs removeExtension ${extensionName}\` but this extension handles this in the npm post uninstall script.
  \`\`\`
  $ cd path/to/application/root
  $ npm run uninstall ${extensionName}
  $ periodicjs removeExtension ${extensionName} // this is handled in the npm postinstall script
  \`\`\`

  ## Testing
  *Make sure you have grunt installed*
  \`\`\`
  $ npm install -g grunt-cli
  \`\`\`

  Then run grunt test or npm test
  \`\`\`
  $ grunt test && grunt coveralls #or locally $ npm test
  \`\`\`
  For generating documentation
  \`\`\`
  $ grunt doc
  $ jsdoc2md commands/**/*.js config/**/*.js controllers/**/*.js  transforms/**/*.js utilities/**/*.js index.js > doc/api.md
  \`\`\`
  ## Notes
  * Check out https://github.com/typesettin/periodicjs for the full Periodic Documentation`;
}

module.exports = {
  getExtensionPaths,
  getExtensionDoc,
  generateREADME,
  create,
  remove,
  update,
  list,
  init,
};<|endoftext|>


<commit_before>import assign from 'lodash/object/assign';
import StrongSocket from './StrongSocket';
import * as utils from './utils';
import * as xhr from './xhr';
import i18n from './i18n';
import friendsApi from './lichess/friends';
import challengesApi from './lichess/challenges';
import session from './session';
import signals from './signals';
import m from 'mithril';

var socketInstance;
var errorDetected = false;
var connectedWS = true;

const proxyFailMsg = 'The connection to lichess server has failed. If you see that the problem is persistent it is probably due to a proxy in your network that prevents establishing the connection. In that case, we\'re sorry: lichess won\'t work.';

const defaultHandlers = {
  following_onlines: data => utils.autoredraw(utils.partialf(friendsApi.set, data)),
  following_enters: name => utils.autoredraw(utils.partialf(friendsApi.add, name)),
  following_leaves: name => utils.autoredraw(utils.partialf(friendsApi.remove, name)),
  challengeReminder: o => {
    if (challengesApi.hasKey(o.id)) challengesApi.remind(o.id);
    else xhr.getChallenge(o.id).then(g => challengesApi.add(o.id, g)).then(m.redraw);
  }
};

function destroy() {
  if (socketInstance) {
    socketInstance.destroy();
    socketInstance = null;
  }
}

function createGame(url, version, receiveHandler, gameUrl, userTv) {
  errorDetected = false;
  destroy();
  const opts = {
    options: {
      name: 'game',
      debug: window.lichess.mode !== 'prod',
      ignoreUnknownMessages: true,
      onError: function() {
        // we can't get socket error, so we send an xhr to test whether the
        // rejection is an authorization issue
        if (!errorDetected) {
          // just to be sure that we don't send an xhr every second when the
          // websocket is trying to reconnect
          errorDetected = true;
          xhr.game(gameUrl.substring(1)).then(function() {}, function(err) {
            if (err.message === 'unauthorizedError') {
              window.plugins.toast.show(i18n('unauthorizedError'), 'short', 'center');
              m.route('/');
            }
          });
        }
      },
      onOpen: () => socketInstance.send('following_onlines')
    },
    events: defaultHandlers,
    receive: receiveHandler
  };
  if (userTv) opts.params = { userTv };
  socketInstance = new StrongSocket(url, version, opts);
}

function createAwait(url, version, handlers) {
  destroy();
  socketInstance = new StrongSocket(
    url, version, {
      options: {
        name: 'await',
        debug: window.lichess.mode !== 'prod',
        ignoreUnknownMessages: true,
        pingDelay: 2000,
        onOpen: () => socketInstance.send('following_onlines')
      },
      events: assign({}, defaultHandlers, handlers)
    }
  );
}

function createLobby(lobbyVersion, onOpen, handlers) {
  destroy();
  socketInstance = new StrongSocket(
    '/lobby/socket/v1',
    lobbyVersion, {
      options: {
        name: 'lobby',
        debug: window.lichess.mode !== 'prod',
        ignoreUnknownMessages: true,
        pingDelay: 2000,
        onOpen: () => {
          onOpen();
          socketInstance.send('following_onlines');
        }
      },
      events: assign({}, defaultHandlers, handlers)
    }
  );
}

function createDefault() {
  // default socket is useless when anon.
  if (utils.hasNetwork() && session.isConnected()) {
    destroy();
    socketInstance = new StrongSocket(
      '/socket', 0, {
        options: {
          name: 'default',
          debug: window.lichess.mode !== 'prod',
          pingDelay: 2000,
          onOpen: () => socketInstance.send('following_onlines')
        },
        events: defaultHandlers
      }
    );
  }
}

function onConnected() {
  connectedWS = true;
}

function onDisconnected() {
  var wasOn = connectedWS;
  connectedWS = false;
  if (wasOn) setTimeout(function() {
    // check if disconnection lasts, it could mean a proxy prevents
    // establishing a tunnel
    if (utils.hasNetwork() && !connectedWS)
      window.plugins.toast.show(proxyFailMsg, 'long', 'center');
  }, 10000);
}

signals.socket.connected.add(onConnected);
signals.socket.disconnected.add(onDisconnected);

export default {
  createGame,
  createLobby,
  createAwait,
  createDefault,
  setVersion(version) {
    if (socketInstance) socketInstance.setVersion(version);
  },
  getAverageLag() {
    if (socketInstance) return socketInstance.averageLag;
  },
  send(...args) {
    if (socketInstance) socketInstance.send(...args);
  },
  connect() {
    if (socketInstance) socketInstance.connect();
  },
  disconnect() {
    if (socketInstance) socketInstance.destroy();
  },
  destroy
};
<commit_msg>Tweak default socket ping delay<commit_after>import assign from 'lodash/object/assign';
import StrongSocket from './StrongSocket';
import * as utils from './utils';
import * as xhr from './xhr';
import i18n from './i18n';
import friendsApi from './lichess/friends';
import challengesApi from './lichess/challenges';
import session from './session';
import signals from './signals';
import m from 'mithril';

var socketInstance;
var errorDetected = false;
var connectedWS = true;

const proxyFailMsg = 'The connection to lichess server has failed. If you see that the problem is persistent it is probably due to a proxy in your network that prevents establishing the connection. In that case, we\'re sorry: lichess won\'t work.';

const defaultHandlers = {
  following_onlines: data => utils.autoredraw(utils.partialf(friendsApi.set, data)),
  following_enters: name => utils.autoredraw(utils.partialf(friendsApi.add, name)),
  following_leaves: name => utils.autoredraw(utils.partialf(friendsApi.remove, name)),
  challengeReminder: o => {
    if (challengesApi.hasKey(o.id)) challengesApi.remind(o.id);
    else xhr.getChallenge(o.id).then(g => challengesApi.add(o.id, g)).then(m.redraw);
  }
};

function destroy() {
  if (socketInstance) {
    socketInstance.destroy();
    socketInstance = null;
  }
}

function createGame(url, version, receiveHandler, gameUrl, userTv) {
  errorDetected = false;
  destroy();
  const opts = {
    options: {
      name: 'game',
      debug: window.lichess.mode !== 'prod',
      ignoreUnknownMessages: true,
      onError: function() {
        // we can't get socket error, so we send an xhr to test whether the
        // rejection is an authorization issue
        if (!errorDetected) {
          // just to be sure that we don't send an xhr every second when the
          // websocket is trying to reconnect
          errorDetected = true;
          xhr.game(gameUrl.substring(1)).then(function() {}, function(err) {
            if (err.message === 'unauthorizedError') {
              window.plugins.toast.show(i18n('unauthorizedError'), 'short', 'center');
              m.route('/');
            }
          });
        }
      },
      onOpen: () => socketInstance.send('following_onlines')
    },
    events: defaultHandlers,
    receive: receiveHandler
  };
  if (userTv) opts.params = { userTv };
  socketInstance = new StrongSocket(url, version, opts);
}

function createAwait(url, version, handlers) {
  destroy();
  socketInstance = new StrongSocket(
    url, version, {
      options: {
        name: 'await',
        debug: window.lichess.mode !== 'prod',
        ignoreUnknownMessages: true,
        pingDelay: 2000,
        onOpen: () => socketInstance.send('following_onlines')
      },
      events: assign({}, defaultHandlers, handlers)
    }
  );
}

function createLobby(lobbyVersion, onOpen, handlers) {
  destroy();
  socketInstance = new StrongSocket(
    '/lobby/socket/v1',
    lobbyVersion, {
      options: {
        name: 'lobby',
        debug: window.lichess.mode !== 'prod',
        ignoreUnknownMessages: true,
        pingDelay: 2000,
        onOpen: () => {
          onOpen();
          socketInstance.send('following_onlines');
        }
      },
      events: assign({}, defaultHandlers, handlers)
    }
  );
}

function createDefault() {
  // default socket is useless when anon.
  if (utils.hasNetwork() && session.isConnected()) {
    destroy();
    socketInstance = new StrongSocket(
      '/socket', 0, {
        options: {
          name: 'default',
          debug: window.lichess.mode !== 'prod',
          pingDelay: 6000,
          pingMaxLag: 12000,
          onOpen: () => socketInstance.send('following_onlines')
        },
        events: defaultHandlers
      }
    );
  }
}

function onConnected() {
  connectedWS = true;
}

function onDisconnected() {
  var wasOn = connectedWS;
  connectedWS = false;
  if (wasOn) setTimeout(function() {
    // check if disconnection lasts, it could mean a proxy prevents
    // establishing a tunnel
    if (utils.hasNetwork() && !connectedWS)
      window.plugins.toast.show(proxyFailMsg, 'long', 'center');
  }, 10000);
}

signals.socket.connected.add(onConnected);
signals.socket.disconnected.add(onDisconnected);

export default {
  createGame,
  createLobby,
  createAwait,
  createDefault,
  setVersion(version) {
    if (socketInstance) socketInstance.setVersion(version);
  },
  getAverageLag() {
    if (socketInstance) return socketInstance.averageLag;
  },
  send(...args) {
    if (socketInstance) socketInstance.send(...args);
  },
  connect() {
    if (socketInstance) socketInstance.connect();
  },
  disconnect() {
    if (socketInstance) socketInstance.destroy();
  },
  destroy
};
<|endoftext|>


<commit_before>'use strict'

import create from './component/create'
import control from './component/control'
import ripple from './component/ripple'

import insert from './element/insert'

import emitter from './module/emitter'
import attach from './module/attach'

const defaults = {
  prefix: 'material',
  class: 'button',
  tag: 'button',
  events: [
    ['root.click', '_clickHandler']
  ]
}

/**
 * Class that represents a button
 * @class
 * @since 0.0.1
 * @example
 * var button = new Button({
 *   label: 'Button raised',
 *   type: 'raised',
 *   color: 'primary'
 * }).on('click', function(e) {
 *   console.log('button click', e);
 * }).insert(document.body);
 */
class Button {
  /**
   * The init method of the Button class
   * @param  {Object} options [description]
   * @private
   * @return {Object} The class instance
   */
  constructor (options) {
    this.init(options)
    this.build()
    this.setup()
    this.attach()

    this.emit('ready')

    return this
  }

  /**
   * [init description]
   * @param  {?} options [description]
   * @return {?}         [description]
   */
  init (options) {
    this.options = Object.assign({}, defaults, options || {})

    Object.assign(this, control, emitter, attach, ripple)

    this.element = this.element || {}
    ripple(this)
    this.emit('init')
  }

  /**
   * Build button's method
   * @override
   * @return {void}
   */
  build () {
    this.element = {}

    this.root = create(this.options)

    this.options.label = this.options.label || this.options.text

    this.root.setAttribute('aria-label', this.options.label || this.options.name)

    this.label(this.options.label)
    this.icon(this.options.icon)

    if (this.options.container) {
      insert(this.root, this.options.container)
    }

    this.emit('built', this.root)

    return this
  }

  /**
   * insert method
   * @param  {?} container [description]
   * @param  {?} context   [description]
   * @return {?}           [description]
   */
  insert (container, context) {
    insert(this.root, container, context)

    return this
  }

  /**
   * [setup description]
   * @return {?} [description]
   */
  setup () {
    this.element.input = this.root

    if (this.options.name) {
      this.root.dataset.name = this.options.name
    }

    // if (this.options.label) {
    //   this.root.title = this.options.label
    // }

    if (this.options.content) {
      this.root.innerHTML = this.options.content
    }
  }

  /**
   * Setter
   * @param {string} prop
   * @param {string} value
   * @return {Object} The class instance
   */
  set (prop, value) {
    switch (prop) {
      case 'disabled':
        this.disable(value)
        break
      case 'value':
        this.setValue(value)
        break
      case 'label':
        this.setLabel(value)
        break
      default:
        this.setValue(prop)
    }

    return this
  }

  /**
   * [_onElementMouseDown description]
   * @param  {event} e
   * @return {void}
   */
  _clickHandler (e) {
    e.preventDefault()

    if (this.disabled === true) return
    if (this.options.upload) return

    // this.publish('click');
    this.emit('click', e)

    return this
  }
}

export default Button
<commit_msg>rename private method clickHandler<commit_after>'use strict'

import create from './component/create'
import control from './component/control'
import ripple from './component/ripple'

import insert from './element/insert'

import emitter from './module/emitter'
import attach from './module/attach'

const defaults = {
  prefix: 'material',
  class: 'button',
  tag: 'button',
  events: [
    ['root.click', 'handleClick']
  ]
}

/**
 * Class that represents a button
 * @class
 * @since 0.0.1
 * @example
 * var button = new Button({
 *   label: 'Button raised',
 *   type: 'raised',
 *   color: 'primary'
 * }).on('click', function(e) {
 *   console.log('button click', e);
 * }).insert(document.body);
 */
class Button {
  /**
   * The init method of the Button class
   * @param  {Object} options [description]
   * @private
   * @return {Object} The class instance
   */
  constructor (options) {
    this.init(options)
    this.build()
    this.setup()
    this.attach()

    this.emit('ready')

    return this
  }

  /**
   * [init description]
   * @param  {?} options [description]
   * @return {?}         [description]
   */
  init (options) {
    this.options = Object.assign({}, defaults, options || {})

    Object.assign(this, control, emitter, attach, ripple)

    this.element = this.element || {}
    ripple(this)
    this.emit('init')
  }

  /**
   * Build button's method
   * @override
   * @return {void}
   */
  build () {
    this.element = {}

    this.root = create(this.options)

    this.options.label = this.options.label || this.options.text

    this.root.setAttribute('aria-label', this.options.label || this.options.name)

    this.label(this.options.label)
    this.icon(this.options.icon)

    if (this.options.container) {
      insert(this.root, this.options.container)
    }

    this.emit('built', this.root)

    return this
  }

  /**
   * insert method
   * @param  {?} container [description]
   * @param  {?} context   [description]
   * @return {?}           [description]
   */
  insert (container, context) {
    insert(this.root, container, context)

    return this
  }

  /**
   * [setup description]
   * @return {?} [description]
   */
  setup () {
    this.element.input = this.root

    if (this.options.name) {
      this.root.dataset.name = this.options.name
    }

    // if (this.options.label) {
    //   this.root.title = this.options.label
    // }

    if (this.options.content) {
      this.root.innerHTML = this.options.content
    }
  }

  /**
   * Setter
   * @param {string} prop
   * @param {string} value
   * @return {Object} The class instance
   */
  set (prop, value) {
    switch (prop) {
      case 'disabled':
        this.disable(value)
        break
      case 'value':
        this.setValue(value)
        break
      case 'label':
        this.setLabel(value)
        break
      default:
        this.setValue(prop)
    }

    return this
  }

  /**
   * [_onElementMouseDown description]
   * @param  {event} e
   * @return {void}
   */
  handleClick (e) {
    e.preventDefault()

    if (this.disabled === true) return
    if (this.options.upload) return

    // this.publish('click');
    this.emit('click', e)

    return this
  }
}

export default Button
<|endoftext|>