<commit_before>/* eslint-env node */

import express from 'express';
import http from 'http';
import socketIO from 'socket.io';
import uuid from 'uuid';
import { getRabbitConnection } from './rabbit-connection';

const app = express();
const server = http.createServer(app);
const io = socketIO(server, { path: '/' });
const corrToSock = {}; // correlation ID to socket ID map

server.listen(3001);

class Router {
  constructor(ch, socket) {
    this.ch = ch;
    this.socket = socket;
    this.nodeId = uuid.v4();
  }

  route(event, key) {
    this.ch.assertQueue(`${key}.listener.${this.nodeId}`, { exclusive: true })
      .then(q => {
        this.ch.consume(q.queue, msg => {
          const socketId = corrToSock[msg.properties.correlationId];
          const data = JSON.parse(msg.content.toString());
          io.to(socketId).emit(event, data);
        }, { noAck: true });

        this.socket.on(event, data => {
          const correlationId = uuid.v4();

          this.ch.assertExchange('events', 'topic', { durable: true });
          this.ch.publish(
            'events',
            key,
            new Buffer(JSON.stringify(typeof data === 'undefined' ? null : data)),
            { persistent: true, correlationId, replyTo: q.queue }
          );
          corrToSock[correlationId] = this.socket.id;
        });
      });
  }
}

io.on('connection', socket => {
  getRabbitConnection()
    .then(conn => conn.createChannel())
    .then(ch => {
      const router = new Router(ch, socket);
      router.route('LOAD_DECISIONS', 'decisions.load');
      router.route('UPDATE_DECISION', 'decisions.update');
      router.route('CREATE_DECISION', 'decisions.create');
      router.route('LOAD_FLATS', 'flats.load');
      router.route('UPDATE_FLAT', 'flats.update');
      router.route('CREATE_FLAT', 'flats.create');
      router.route('LOAD_HOUSES', 'houses.load');
      router.route('UPDATE_HOUSE', 'houses.update');
      router.route('CREATE_HOUSE', 'houses.create');
      router.route('LOAD_SERVICES', 'services.load');
      router.route('UPDATE_SERVICE', 'services.update');
      router.route('CREATE_SERVICE', 'services.create');
      router.route('LOGIN', 'auth.login');
      router.route('LOGOUT', 'auth.logout');
    });
});
<commit_msg>users, cooperatives<commit_after>/* eslint-env node */

import express from 'express';
import http from 'http';
import socketIO from 'socket.io';
import uuid from 'uuid';
import { getRabbitConnection } from './rabbit-connection';

const app = express();
const server = http.createServer(app);
const io = socketIO(server, { path: '/' });
const corrToSock = {}; // correlation ID to socket ID map

server.listen(3001);

class Router {
  constructor(ch, socket) {
    this.ch = ch;
    this.socket = socket;
    this.nodeId = uuid.v4();
  }

  route(event, key) {
    this.ch.assertQueue(`${key}.listener.${this.nodeId}`, { exclusive: true })
      .then(q => {
        this.ch.consume(q.queue, msg => {
          const socketId = corrToSock[msg.properties.correlationId];
          const data = JSON.parse(msg.content.toString());
          io.to(socketId).emit(event, data);
        }, { noAck: true });

        this.socket.on(event, data => {
          const correlationId = uuid.v4();

          this.ch.assertExchange('events', 'topic', { durable: true });
          this.ch.publish(
            'events',
            key,
            new Buffer(JSON.stringify(typeof data === 'undefined' ? null : data)),
            { persistent: true, correlationId, replyTo: q.queue }
          );
          corrToSock[correlationId] = this.socket.id;
        });
      });
  }
}

io.on('connection', socket => {
  getRabbitConnection()
    .then(conn => conn.createChannel())
    .then(ch => {
      const router = new Router(ch, socket);
      router.route('LOAD_DECISIONS', 'decisions.load');
      router.route('UPDATE_DECISION', 'decisions.update');
      router.route('CREATE_DECISION', 'decisions.create');
      router.route('LOAD_FLATS', 'flats.load');
      router.route('UPDATE_FLAT', 'flats.update');
      router.route('CREATE_FLAT', 'flats.create');
      router.route('LOAD_HOUSES', 'houses.load');
      router.route('UPDATE_HOUSE', 'houses.update');
      router.route('CREATE_HOUSE', 'houses.create');
      router.route('LOAD_SERVICES', 'services.load');
      router.route('UPDATE_SERVICE', 'services.update');
      router.route('CREATE_SERVICE', 'services.create');
      router.route('LOAD_USERS', 'users.load');
      router.route('UPDATE_USER', 'users.update');
      router.route('CREATE_USER', 'users.create');
      router.route('LOAD_COOPERATIVES', 'cooperatives.load');
      router.route('UPDATE_COOPERATIVE', 'cooperatives.update');
      router.route('CREATE_COOPERATIVE', 'cooperatives.create');
      router.route('LOGIN', 'auth.login');
      router.route('LOGOUT', 'auth.logout');
    });
});
<|endoftext|>


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

 function editableFieldDirective($document, $parse, $rootScope, $timeout, packaging) {
  return {
    require: '^?editableFieldContainer',
    restrict: 'A',
    link: function(scope, element, attrs, editableFieldContainerController) {
      element.addClass('editable-field');

      var editableFieldType;
      if (attrs.editableField.length > 0){
        editableFieldType = $parse(attrs.editableField)(scope);
      }

      if (attrs.editableFieldRegisterCallbacks){
        var registerCallbacksFn = $parse(attrs.editableFieldRegisterCallbacks).bind(undefined, scope);
        registerCallbacksFn({focus: focusElement, blur: blurElement}) ;
      }

      function focusElement() {
        function doFocusElement(){
          element[0].focus();
          if (packaging === 'android-cordova'){
            // In Android we need to force the keyboard up
            cordova.plugins.Keyboard.show();
          }
        }
        // https://developer.mozilla.org/en-US/docs/Web/API/document.activeElement
        if ($document[0].activeElement !== element[0]){
          if ($rootScope.$$phase || scope.$$phase){
            // It seems $timeout can not be avoided here:
            // https://github.com/angular/angular.js/issues/1250
            // "In the future, this will (hopefully) be solved with Object.observe."
            $timeout(function(){
              doFocusElement();
            });
          }else {
            doFocusElement();
          }
        }
      }

      var unfocusInProgress = false;
      function blurElement(deactivateAfterBlur) {
        function doBlurElement(){
          element[0].blur();
          if (deactivateAfterBlur && editableFieldContainerController)
            editableFieldContainerController.deactivateContainer();
        }

        if ($document[0].activeElement === element[0]){
          unfocusInProgress = true;
          if ($rootScope.$$phase || scope.$$phase){
            $timeout(function(){
              doBlurElement();
            });
          }else {
            doBlurElement();
          }
        }
      }

      var refocusInProgress = false;
      function reFocusEditableField(){
        refocusInProgress = true;
        focusElement();
      }

      var editableFieldClicked = function() {
        if (editableFieldContainerController) editableFieldContainerController.notifyFocus();
        reFocusEditableField();
      };

      var editableFieldFocus = function() {
        if (!refocusInProgress){
          if (editableFieldContainerController) editableFieldContainerController.notifyFocus();
          element.addClass('active');
        }
        refocusInProgress = false;
      };

      var editableFieldBlur = function() {
        if (editableFieldType === 'sticky' && !unfocusInProgress){
          reFocusEditableField();
          if (editableFieldContainerController) editableFieldContainerController.notifyReFocus(blurElement);
        }else{
          element.removeClass('active');
          unfocusInProgress = false;
          if (packaging === 'android-cordova'){
            // In Android we need to force the keyboard down
            cordova.plugins.Keyboard.close();
          }
        }
      };

      var editableFieldKeydown = function(event){
        // ESC button
        if (event.keyCode === 27){
          editableFieldBlur();
          if (editableFieldContainerController) editableFieldContainerController.deactivateContainer();
        }
      };

      angular.element(element).bind('focus', editableFieldFocus);
      angular.element(element).bind('blur', editableFieldBlur);
      angular.element(element).bind('keydown', editableFieldKeydown);
      if (editableFieldType === 'sticky')
        angular.element(element).bind('click', editableFieldClicked);

      scope.$on('$destroy', function() {
        angular.element(element).unbind('focus', editableFieldFocus);
        angular.element(element).unbind('blur', editableFieldBlur);
        angular.element(element).unbind('keydown', editableFieldKeydown);
        if (editableFieldType === 'sticky')
          angular.element(element).bind('click', editableFieldClicked);
      });
    }
  };
}
editableFieldDirective['$inject'] = ['$document', '$parse', '$rootScope', '$timeout', 'packaging'];
angular.module('common').directive('editableField', editableFieldDirective);
<commit_msg>Fixed double bind to unbind in editable field directive<commit_after>/* Copyright 2013-2014 Extended Mind Technologies Oy
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 'use strict';

 function editableFieldDirective($document, $parse, $rootScope, $timeout, packaging) {
  return {
    require: '^?editableFieldContainer',
    restrict: 'A',
    link: function(scope, element, attrs, editableFieldContainerController) {
      element.addClass('editable-field');

      var editableFieldType;
      if (attrs.editableField.length > 0){
        editableFieldType = $parse(attrs.editableField)(scope);
      }

      if (attrs.editableFieldRegisterCallbacks){
        var registerCallbacksFn = $parse(attrs.editableFieldRegisterCallbacks).bind(undefined, scope);
        registerCallbacksFn({focus: focusElement, blur: blurElement}) ;
      }

      function focusElement() {
        function doFocusElement(){
          element[0].focus();
          if (packaging === 'android-cordova'){
            // In Android we need to force the keyboard up
            cordova.plugins.Keyboard.show();
          }
        }
        // https://developer.mozilla.org/en-US/docs/Web/API/document.activeElement
        if ($document[0].activeElement !== element[0]){
          if ($rootScope.$$phase || scope.$$phase){
            // It seems $timeout can not be avoided here:
            // https://github.com/angular/angular.js/issues/1250
            // "In the future, this will (hopefully) be solved with Object.observe."
            $timeout(function(){
              doFocusElement();
            });
          }else {
            doFocusElement();
          }
        }
      }

      var unfocusInProgress = false;
      function blurElement(deactivateAfterBlur) {
        function doBlurElement(){
          element[0].blur();
          if (deactivateAfterBlur && editableFieldContainerController)
            editableFieldContainerController.deactivateContainer();
        }

        if ($document[0].activeElement === element[0]){
          unfocusInProgress = true;
          if ($rootScope.$$phase || scope.$$phase){
            $timeout(function(){
              doBlurElement();
            });
          }else {
            doBlurElement();
          }
        }
      }

      var refocusInProgress = false;
      function reFocusEditableField(){
        refocusInProgress = true;
        focusElement();
      }

      var editableFieldClicked = function() {
        if (editableFieldContainerController) editableFieldContainerController.notifyFocus();
        reFocusEditableField();
      };

      var editableFieldFocus = function() {
        if (!refocusInProgress){
          if (editableFieldContainerController) editableFieldContainerController.notifyFocus();
          element.addClass('active');
        }
        refocusInProgress = false;
      };

      var editableFieldBlur = function() {
        if (editableFieldType === 'sticky' && !unfocusInProgress){
          reFocusEditableField();
          if (editableFieldContainerController) editableFieldContainerController.notifyReFocus(blurElement);
        }else{
          element.removeClass('active');
          unfocusInProgress = false;
          if (packaging === 'android-cordova'){
            // In Android we need to force the keyboard down
            cordova.plugins.Keyboard.close();
          }
        }
      };

      var editableFieldKeydown = function(event){
        // ESC button
        if (event.keyCode === 27){
          editableFieldBlur();
          if (editableFieldContainerController) editableFieldContainerController.deactivateContainer();
        }
      };

      angular.element(element).bind('focus', editableFieldFocus);
      angular.element(element).bind('blur', editableFieldBlur);
      angular.element(element).bind('keydown', editableFieldKeydown);
      if (editableFieldType === 'sticky')
        angular.element(element).bind('click', editableFieldClicked);

      scope.$on('$destroy', function() {
        angular.element(element).unbind('focus', editableFieldFocus);
        angular.element(element).unbind('blur', editableFieldBlur);
        angular.element(element).unbind('keydown', editableFieldKeydown);
        if (editableFieldType === 'sticky')
          angular.element(element).unbind('click', editableFieldClicked);
      });
    }
  };
}
editableFieldDirective['$inject'] = ['$document', '$parse', '$rootScope', '$timeout', 'packaging'];
angular.module('common').directive('editableField', editableFieldDirective);
<|endoftext|>


<commit_before>(function(app) {
  'use strict';

  var jCore = require('jcore');
  var dom = app.dom || require('../dom.js');

  var SidebarHeader = jCore.Component.inherits(function() {
    this.searchInput = new SidebarHeader.SearchInput({ element: this.findElement('.search-input') });
  });

  SidebarHeader.prototype.loadSearchText = function() {
    // apply initial value of input
    this.searchInput.oninput();
  };

  SidebarHeader.prototype.oninit = function() {
    this.searchInput.on('input', this.emit.bind(this, 'search'));
  };

  SidebarHeader.SearchInput = (function() {
    var SearchInput = jCore.Component.inherits(function() {
      this.isFocused = this.prop(false);
    });

    SearchInput.prototype.oninit = function() {
      this.isFocused(dom.isFocused(this.element()));
      dom.on(this.element(), dom.eventType('start'), this.onstart.bind(this));
      dom.on(this.element(), 'click', this.onclick.bind(this));
      dom.on(this.element(), 'input', this.oninput.bind(this));
    };

    SearchInput.prototype.onstart = function() {
      this.isFocused(dom.isFocused(this.element()));
    };

    SearchInput.prototype.onclick = function() {
      if (!this.isFocused() && !dom.hasSelection(this.element())) {
        dom.selectAll(this.element());
      }
    };

    SearchInput.prototype.oninput = function() {
      this.emit('input', dom.value(this.element()));
    };

    return SearchInput;
  })();

  if (typeof module !== 'undefined' && module.exports) {
    module.exports = SidebarHeader;
  } else {
    app.SidebarHeader = SidebarHeader;
  }
})(this.app || (this.app = {}));
<commit_msg>Rename event for pointing search-input element<commit_after>(function(app) {
  'use strict';

  var jCore = require('jcore');
  var dom = app.dom || require('../dom.js');

  var SidebarHeader = jCore.Component.inherits(function() {
    this.searchInput = new SidebarHeader.SearchInput({ element: this.findElement('.search-input') });
  });

  SidebarHeader.prototype.loadSearchText = function() {
    // apply initial value of input
    this.searchInput.oninput();
  };

  SidebarHeader.prototype.oninit = function() {
    this.searchInput.on('input', this.emit.bind(this, 'search'));
  };

  SidebarHeader.SearchInput = (function() {
    var SearchInput = jCore.Component.inherits(function() {
      this.isFocused = this.prop(false);
    });

    SearchInput.prototype.oninit = function() {
      this.isFocused(dom.isFocused(this.element()));
      dom.on(this.element(), dom.eventType('start'), this.onpoint.bind(this));
      dom.on(this.element(), 'click', this.onclick.bind(this));
      dom.on(this.element(), 'input', this.oninput.bind(this));
    };

    SearchInput.prototype.onpoint = function() {
      this.isFocused(dom.isFocused(this.element()));
    };

    SearchInput.prototype.onclick = function() {
      if (!this.isFocused() && !dom.hasSelection(this.element())) {
        dom.selectAll(this.element());
      }
    };

    SearchInput.prototype.oninput = function() {
      this.emit('input', dom.value(this.element()));
    };

    return SearchInput;
  })();

  if (typeof module !== 'undefined' && module.exports) {
    module.exports = SidebarHeader;
  } else {
    app.SidebarHeader = SidebarHeader;
  }
})(this.app || (this.app = {}));
<|endoftext|>


<commit_before>'use strict';
var cl = function (val) {
    return console.log(val);
};

// Declare app level module which depends on filters, and services
var KMCModule = angular.module('KMCModule',
    ['pascalprecht.translate', 'ngRoute', 'KMC.controllers', 'KMC.filters',
        'KMC.services', 'KMC.directives', 'ngAnimate', 'LocalStorageModule', 'KMC.menu']);

KMCModule.config(['$routeProvider', '$locationProvider', '$httpProvider', '$tooltipProvider', '$translateProvider', function ($routeProvider, $locationProvider, $httpProvider, $tooltipProvider, $translateProvider) {
        $translateProvider.useStaticFilesLoader({
            prefix: 'i18n/',
            suffix: '.json'
        });
        $translateProvider.preferredLanguage('en_US');
        $translateProvider.fallbackLanguage('en_US');
        if (window.location.href.indexOf('debug') != -1) {
            $translateProvider.useMissingTranslationHandlerLog();
        }
        $translateProvider.useStorage('localStorageService');
        $tooltipProvider.options({ placement: 'right', 'appendToBody': true, 'popupDelay': 800 });
        // set event name for opening and closing the tooltips
        $tooltipProvider.setTriggers({
            'customShow': 'customShow'
        });

        $httpProvider.defaults.useXDomain = true; // cors support (TODO - check if we can remove, should be true by default in this angular version)
        delete $httpProvider.defaults.headers.common['X-Requested-With']; // IE8 cors support

        //request loading indication
        var $http, interceptor = ['$q', '$injector',
            function ($q, $injector) {
                var notificationChannel;

                function success(response) {
                    // get $http via $injector because of circular dependency problem
                    $http = $http || $injector.get('$http');
                    // don't send notification until all requests are complete
                    if ($http.pendingRequests.length < 1) {
                        // get requestNotificationChannel via $injector because of circular dependency problem
                        notificationChannel = notificationChannel || $injector.get('requestNotificationChannel');
                        // send a notification requests are complete
                        notificationChannel.requestEnded();
                    }
                    return response;
                }

                function error(response) {
                    logTime('httpRequest failed -');
                    // get $http via $injector because of circular dependency problem
                    $http = $http || $injector.get('$http');
                    // don't send notification until all requests are complete
                    if ($http.pendingRequests.length < 1) {
                        // get requestNotificationChannel via $injector because of circular dependency problem
                        notificationChannel = notificationChannel || $injector.get('requestNotificationChannel');
                        // send a notification requests are complete
                        notificationChannel.requestEnded();
                    }
                    return $q.reject(response);
                }

                return function (promise) {
                    // get requestNotificationChannel via $injector because of circular dependency problem
                    notificationChannel = notificationChannel || $injector.get('requestNotificationChannel');
                    // send a notification requests are complete
                    notificationChannel.requestStarted();
                    return promise.then(success, error);
                };
            }];
        // add the interceptor to the httpProvider
        $httpProvider.responseInterceptors.push(interceptor);
        // routing section
        $routeProvider.when('/login', {
                templateUrl: 'view/login.html',
                controller: 'LoginCtrl',
                resolve: {'apiService': ['api', 'apiService', function (api, apiService) {
                    // make sure apiService is available upon invalid KS redirect
                    return apiService;
                }]
                }
            }
        );
        $routeProvider.when('/list', {
                templateUrl: 'view/list.html',
                controller: 'PlayerListCtrl',
                resolve: {
                    'apiService': ['api', 'apiService', 'localStorageService', '$location', function (api, apiService, localStorageService, $location) {
                        // make sure we load the list only if we have valid KS
                        return ksCheck(api, apiService, localStorageService, $location).then(function () {
                            return apiService;
                        });
                    }]
                }
            }
        );
        var ksCheck = function (api, apiService, localStorageService, $location) {
            // Check if we have ks in locaclstorage
            try {
                var kmc = window.parent.kmc;
                if (kmc && kmc.vars) {
                    // got ks from KMC - save to local storage
                    if (kmc.vars.ks)
                        localStorageService.add('ks', kmc.vars.ks);
                }
            } catch (e) {
                cl('Could not located parent.kmc: ' + e);
            }
            var ks = localStorageService.get('ks');
            if (!ks) { //navigate to login
                $location.path("/login");
                return false;
            } else {
                api.then(function () {
                    apiService.setKs(ks);
                });
            }
            return api; // changed to return the promise of the API
        };

        // deep linking to plugin setup
        $routeProvider.when('/edit/:id',
            {templateUrl: 'view/edit.html',
                controller: 'PlayerEditCtrl',
                reloadOnSearch: false,
                resolve: {
                    'PlayerData': ['PlayerService', '$route', 'api', 'apiService', 'localStorageService', '$location', function (PlayerService, $route, api, apiService, localStorageService, $location) {
                        var apiLoaded = ksCheck(api, apiService, localStorageService, $location);
                        if (apiLoaded) {
                            return apiLoaded.then(function (api) {
                                return PlayerService.getPlayer($route.current.params.id);
                            });
                        }
                    }],
                    'editProperties': 'editableProperties',
                    'menuSvc': 'menuSvc'
                }
            }
        );

        // open template screen
        $routeProvider.when('/newByTemplate',
            {templateUrl: 'view/new-template.html',
                controller: 'PlayerCreateCtrl',
                resolve: {
                    'templates': ['playerTemplates', function (playerTemplates) {
                        return  playerTemplates.listSystem();
                    }],
                    'userId': function () {
                        return '1'; //  KMC would need to give us the userID ?
                    }

                }
            }
        );
        $routeProvider.when('/new',
            {templateUrl: 'view/edit.html',
                controller: 'PlayerEditCtrl',
                resolve: {
                    'api': ['api', 'apiService', 'localStorageService', '$location', function (api, apiService, localStorageService, $location) {
                        return ksCheck(api, apiService, localStorageService, $location);
                    }],
                    'PlayerData': function (api, PlayerService) {
                        return api.then(function () {
                            return PlayerService.newPlayer();
                        });
                    },
                    'menuSvc': 'menuSvc'
                }
            }
        );
        $routeProvider.when('/logout', {
            resolve: {'logout': ['localStorageService', 'apiService', '$location', function (localStorageService, apiService, $location) {
                if (localStorageService.isSupported()) {
                    localStorageService.clearAll();
                }
                apiService.unSetks();
                $location.path('/login');
            }]}

        });
        $routeProvider.otherwise({
            resolve: {'res': ['api', 'apiService', 'localStorageService', '$location', function (api, apiService, localStorageService, $location) {
                if (ksCheck(api, apiService, localStorageService, $location)) {
                    return $location.path('/list');
                }
            }]}
        });
    }]).run(function ($rootScope, $rootElement, $location, menuSvc) {
    var appLoad = new Date();
    var debug = false;

    if (1 == 1 || typeof window.parent.kmc != 'undefined') {
        $('html').addClass('inKmc');
    }

    // set the logTime function used in debug mode
    var logTime = function (eventName) {
        if ($location.search()['debug']) {
            var now = new Date();
            var diff = Math.abs(appLoad.getTime() - now.getTime());
            cl(eventName + ' ' + Math.ceil(diff / 1000) + 'sec ' + diff % 1000 + 'ms');
        }
    };
    window.logTime = logTime;
    logTime('AppJsLoad');

    // add functions to $rootScope constructor. $safeApply to prevent apply when digest is already in progress
    $rootScope.constructor.prototype.$safeApply = function (fn) {
        var phase = this.$root.$$phase;
        if (phase == '$apply' || phase == '$digest')
            this.$eval(fn);
        else
            this.$apply(fn);
    };

    // custom show for tooltips
    $rootScope.constructor.prototype.openTooltip = function ($event) {
        if (menuSvc.currentTooltip == $event.target) return;
        menuSvc.currentTooltip = $event.target;
        $($event.target).trigger('customShow');
        $event.preventDefault();
        $event.stopPropagation();
        return false;
    };

    // for css - define the body ID according to route
    $rootScope.routeName = '';
    $rootScope.$on('$routeChangeSuccess', function () {
        appLoad = new Date();
        var url = $location.url().split('/');
        if (debug) {
            $location.search({debug: true});
        }
        if (url[1].indexOf('?') != -1) {
            url[1] = url[1].substr(0, url[1].indexOf('?'));
        }
        $rootScope.routeName = url[1];
    });

    // set debug flag across route changes
    $rootScope.$on('$routeChangeStart', function () {
        if ($location.search()['debug']) {
            debug = true;
        }
        else {
            debug = false;
        }
    });
});
<commit_msg>remove development code<commit_after>'use strict';
var cl = function (val) {
    return console.log(val);
};

// Declare app level module which depends on filters, and services
var KMCModule = angular.module('KMCModule',
    ['pascalprecht.translate', 'ngRoute', 'KMC.controllers', 'KMC.filters',
        'KMC.services', 'KMC.directives', 'ngAnimate', 'LocalStorageModule', 'KMC.menu']);

KMCModule.config(['$routeProvider', '$locationProvider', '$httpProvider', '$tooltipProvider', '$translateProvider', function ($routeProvider, $locationProvider, $httpProvider, $tooltipProvider, $translateProvider) {
        $translateProvider.useStaticFilesLoader({
            prefix: 'i18n/',
            suffix: '.json'
        });
        $translateProvider.preferredLanguage('en_US');
        $translateProvider.fallbackLanguage('en_US');
        if (window.location.href.indexOf('debug') != -1) {
            $translateProvider.useMissingTranslationHandlerLog();
        }
        $translateProvider.useStorage('localStorageService');
        $tooltipProvider.options({ placement: 'right', 'appendToBody': true, 'popupDelay': 800 });
        // set event name for opening and closing the tooltips
        $tooltipProvider.setTriggers({
            'customShow': 'customShow'
        });

        $httpProvider.defaults.useXDomain = true; // cors support (TODO - check if we can remove, should be true by default in this angular version)
        delete $httpProvider.defaults.headers.common['X-Requested-With']; // IE8 cors support

        //request loading indication
        var $http, interceptor = ['$q', '$injector',
            function ($q, $injector) {
                var notificationChannel;

                function success(response) {
                    // get $http via $injector because of circular dependency problem
                    $http = $http || $injector.get('$http');
                    // don't send notification until all requests are complete
                    if ($http.pendingRequests.length < 1) {
                        // get requestNotificationChannel via $injector because of circular dependency problem
                        notificationChannel = notificationChannel || $injector.get('requestNotificationChannel');
                        // send a notification requests are complete
                        notificationChannel.requestEnded();
                    }
                    return response;
                }

                function error(response) {
                    logTime('httpRequest failed -');
                    // get $http via $injector because of circular dependency problem
                    $http = $http || $injector.get('$http');
                    // don't send notification until all requests are complete
                    if ($http.pendingRequests.length < 1) {
                        // get requestNotificationChannel via $injector because of circular dependency problem
                        notificationChannel = notificationChannel || $injector.get('requestNotificationChannel');
                        // send a notification requests are complete
                        notificationChannel.requestEnded();
                    }
                    return $q.reject(response);
                }

                return function (promise) {
                    // get requestNotificationChannel via $injector because of circular dependency problem
                    notificationChannel = notificationChannel || $injector.get('requestNotificationChannel');
                    // send a notification requests are complete
                    notificationChannel.requestStarted();
                    return promise.then(success, error);
                };
            }];
        // add the interceptor to the httpProvider
        $httpProvider.responseInterceptors.push(interceptor);
        // routing section
        $routeProvider.when('/login', {
                templateUrl: 'view/login.html',
                controller: 'LoginCtrl',
                resolve: {'apiService': ['api', 'apiService', function (api, apiService) {
                    // make sure apiService is available upon invalid KS redirect
                    return apiService;
                }]
                }
            }
        );
        $routeProvider.when('/list', {
                templateUrl: 'view/list.html',
                controller: 'PlayerListCtrl',
                resolve: {
                    'apiService': ['api', 'apiService', 'localStorageService', '$location', function (api, apiService, localStorageService, $location) {
                        // make sure we load the list only if we have valid KS
                        return ksCheck(api, apiService, localStorageService, $location).then(function () {
                            return apiService;
                        });
                    }]
                }
            }
        );
        var ksCheck = function (api, apiService, localStorageService, $location) {
            // Check if we have ks in locaclstorage
            try {
                var kmc = window.parent.kmc;
                if (kmc && kmc.vars) {
                    // got ks from KMC - save to local storage
                    if (kmc.vars.ks)
                        localStorageService.add('ks', kmc.vars.ks);
                }
            } catch (e) {
                cl('Could not located parent.kmc: ' + e);
            }
            var ks = localStorageService.get('ks');
            if (!ks) { //navigate to login
                $location.path("/login");
                return false;
            } else {
                api.then(function () {
                    apiService.setKs(ks);
                });
            }
            return api; // changed to return the promise of the API
        };

        // deep linking to plugin setup
        $routeProvider.when('/edit/:id',
            {templateUrl: 'view/edit.html',
                controller: 'PlayerEditCtrl',
                reloadOnSearch: false,
                resolve: {
                    'PlayerData': ['PlayerService', '$route', 'api', 'apiService', 'localStorageService', '$location', function (PlayerService, $route, api, apiService, localStorageService, $location) {
                        var apiLoaded = ksCheck(api, apiService, localStorageService, $location);
                        if (apiLoaded) {
                            return apiLoaded.then(function (api) {
                                return PlayerService.getPlayer($route.current.params.id);
                            });
                        }
                    }],
                    'editProperties': 'editableProperties',
                    'menuSvc': 'menuSvc'
                }
            }
        );

        // open template screen
        $routeProvider.when('/newByTemplate',
            {templateUrl: 'view/new-template.html',
                controller: 'PlayerCreateCtrl',
                resolve: {
                    'templates': ['playerTemplates', function (playerTemplates) {
                        return  playerTemplates.listSystem();
                    }],
                    'userId': function () {
                        return '1'; //  KMC would need to give us the userID ?
                    }

                }
            }
        );
        $routeProvider.when('/new',
            {templateUrl: 'view/edit.html',
                controller: 'PlayerEditCtrl',
                resolve: {
                    'api': ['api', 'apiService', 'localStorageService', '$location', function (api, apiService, localStorageService, $location) {
                        return ksCheck(api, apiService, localStorageService, $location);
                    }],
                    'PlayerData': function (api, PlayerService) {
                        return api.then(function () {
                            return PlayerService.newPlayer();
                        });
                    },
                    'menuSvc': 'menuSvc'
                }
            }
        );
        $routeProvider.when('/logout', {
            resolve: {'logout': ['localStorageService', 'apiService', '$location', function (localStorageService, apiService, $location) {
                if (localStorageService.isSupported()) {
                    localStorageService.clearAll();
                }
                apiService.unSetks();
                $location.path('/login');
            }]}

        });
        $routeProvider.otherwise({
            resolve: {'res': ['api', 'apiService', 'localStorageService', '$location', function (api, apiService, localStorageService, $location) {
                if (ksCheck(api, apiService, localStorageService, $location)) {
                    return $location.path('/list');
                }
            }]}
        });
    }]).run(function ($rootScope, $rootElement, $location, menuSvc) {
    var appLoad = new Date();
    var debug = false;

    if (typeof window.parent.kmc != 'undefined') {
        $('html').addClass('inKmc');
    }

    // set the logTime function used in debug mode
    var logTime = function (eventName) {
        if ($location.search()['debug']) {
            var now = new Date();
            var diff = Math.abs(appLoad.getTime() - now.getTime());
            cl(eventName + ' ' + Math.ceil(diff / 1000) + 'sec ' + diff % 1000 + 'ms');
        }
    };
    window.logTime = logTime;
    logTime('AppJsLoad');

    // add functions to $rootScope constructor. $safeApply to prevent apply when digest is already in progress
    $rootScope.constructor.prototype.$safeApply = function (fn) {
        var phase = this.$root.$$phase;
        if (phase == '$apply' || phase == '$digest')
            this.$eval(fn);
        else
            this.$apply(fn);
    };

    // custom show for tooltips
    $rootScope.constructor.prototype.openTooltip = function ($event) {
        if (menuSvc.currentTooltip == $event.target) return;
        menuSvc.currentTooltip = $event.target;
        $($event.target).trigger('customShow');
        $event.preventDefault();
        $event.stopPropagation();
        return false;
    };

    // for css - define the body ID according to route
    $rootScope.routeName = '';
    $rootScope.$on('$routeChangeSuccess', function () {
        appLoad = new Date();
        var url = $location.url().split('/');
        if (debug) {
            $location.search({debug: true});
        }
        if (url[1].indexOf('?') != -1) {
            url[1] = url[1].substr(0, url[1].indexOf('?'));
        }
        $rootScope.routeName = url[1];
    });

    // set debug flag across route changes
    $rootScope.$on('$routeChangeStart', function () {
        if ($location.search()['debug']) {
            debug = true;
        }
        else {
            debug = false;
        }
    });
});
<|endoftext|>


<commit_before>var assert = require('assert');
var Medea = require('../');

var directory = __dirname + '/tmp/medea_test';
var db;
var setup = function (done) {
  require('rimraf')(directory, function () {
    db = new Medea({ maxFileSize: 100 });
    db.open(directory, done);
  });
}
var shutdown = function (done) {
  db.close(done);
}

describe('Medea#compact', function() {

  describe('Multiple time overwriting same key', function () {
    before(setup);

    for(var i = 0; i < 50; i++) {
      it('successfully overwriting same key', function (done) {
        var buffer1 = new Buffer(50),
          buffer2 = new Buffer(50),
          buffer3 = new Buffer(50);

        buffer1.fill(1);
        buffer2.fill(2);
        buffer3.fill(3);

        db.put('foo1', buffer1, function (err) {
          if (err) return done(err);
          db.put('foo1', buffer2, function (err) {
            if (err) return done(err);
            db.put('foo1', buffer3, function (err) {
              if (err) return done(err);
              db.compact(function (err) {
                if (err) return done(err)
                db.compact(function (err) {
                  if (err) return done(err)

                  db.get('foo1', function (err, value) {
                    assert.deepEqual(value, buffer3);
                    done();
                  })
                });
              });
            });
          });
        });
      });
    }

    after(shutdown);
  });

  describe('Multiple time writing different keys', function () {
    before(setup);

    for(var i = 0; i < 50; i++) {
      it('successfully writing different key', function (done) {
        var test = function (index) {
          if (index === 50)
            return done();

        }
        var buffer1 = new Buffer(50),
          buffer2 = new Buffer(50),
          buffer3 = new Buffer(50);

        buffer1.fill(1);
        buffer2.fill(2);
        buffer3.fill(3);

        db.put('foo1', buffer1, function (err) {
          if (err) return done(err);
          db.put('foo2', buffer2, function (err) {
            if (err) return done(err);
            db.put('foo3', buffer3, function (err) {
              if (err) return done(err);
              db.compact(function (err) {
                if (err) return done(err)
                db.compact(function (err) {
                  if (err) return done(err)
                  db.get('foo1', function (err, value) {
                    assert.deepEqual(value, buffer1);
                    db.get('foo2', function (err, value) {
                      assert.deepEqual(value, buffer2);
                      db.get('foo3', function (err, value) {
                        assert.deepEqual(value, buffer3);

                        done()
                      });
                    });
                  })
                });
              });
            });
          });
        });
      });
    }

    after(shutdown);
  });

  describe('Write large amount of data', function () {
    before(setup);
    var max = 20;

    before(function (done) {
      var put = function(index) {
        if (index === max) {
          return done();
        }

        var buffer = new Buffer(50);

        buffer.fill(index);

        db.put(buffer, buffer, function(err) {
          if (err) return done(err);
          put(++index);
        });
      }

      put(0);
    });

    it('successfully compacts', function (done) {
      db.compact(function (err) {
        if (err) return done(err);
        db.compact(function (err) {
          if (err) return done(err);
          done()
        });
      });
    });

    it('successfully saves data', function (done) {
      var get = function (index) {
        if (index === max) {
          return done();
        }
        var buffer = new Buffer(50);
        buffer.fill(index);

        db.get(buffer, function (err, value) {
          if (err) return done(err);
          assert.deepEqual(value, buffer);
          get(++index);
        });
      }
      get(0);
    });

    after(shutdown);
  })
});
<commit_msg>simplify tests<commit_after>var assert = require('assert');
var Medea = require('../');

var directory = __dirname + '/tmp/medea_test';
var db;
var setup = function (done) {
  require('rimraf')(directory, function () {
    db = new Medea({ maxFileSize: 100 });
    db.open(directory, done);
  });
}
var shutdown = function (done) {
  db.close(done);
}

describe('Medea#compact', function() {

  describe('Multiple time overwriting same key', function () {
    before(setup);

    it('successfully owerwites same key', function (done) {
      var test = function (index) {
        if (index === 50)
          return done();

        var buffer1 = new Buffer(50),
          buffer2 = new Buffer(50),
          buffer3 = new Buffer(50);

        buffer1.fill(1);
        buffer2.fill(2);
        buffer3.fill(3);

        db.put('foo1', buffer1, function (err) {
          if (err) return done(err);
          db.put('foo1', buffer2, function (err) {
            if (err) return done(err);
            db.put('foo1', buffer3, function (err) {
              if (err) return done(err);
              db.compact(function (err) {
                if (err) return done(err)
                db.compact(function (err) {
                  if (err) return done(err)

                  db.get('foo1', function (err, value) {
                    assert.deepEqual(value, buffer3);
                    test(++index);
                  })
                });
              });
            });
          });
        });
      }
      test(0);
    });

    after(shutdown);
  });

  describe('Multiple time writing different keys', function () {
    before(setup);

    it('successfully writing different key', function (done) {
      var test = function (index) {
        if (index === 50)
          return done();

        var buffer1 = new Buffer(50),
          buffer2 = new Buffer(50),
          buffer3 = new Buffer(50);

        buffer1.fill(1);
        buffer2.fill(2);
        buffer3.fill(3);

        db.put('foo1', buffer1, function (err) {
          if (err) return done(err);
          db.put('foo2', buffer2, function (err) {
            if (err) return done(err);
            db.put('foo3', buffer3, function (err) {
              if (err) return done(err);
              db.compact(function (err) {
                if (err) return done(err)
                db.compact(function (err) {
                  if (err) return done(err)
                  db.get('foo1', function (err, value) {
                    assert.deepEqual(value, buffer1);
                    db.get('foo2', function (err, value) {
                      assert.deepEqual(value, buffer2);
                      db.get('foo3', function (err, value) {
                        assert.deepEqual(value, buffer3);

                        test(++index);
                      });
                    });
                  })
                });
              });
            });
          });
        });
      }
      test(0);
    });

    after(shutdown);
  });

  describe('Write large amount of data', function () {
    before(setup);
    var max = 20;

    before(function (done) {
      var put = function(index) {
        if (index === max) {
          return done();
        }

        var buffer = new Buffer(50);

        buffer.fill(index);

        db.put(buffer, buffer, function(err) {
          if (err) return done(err);
          put(++index);
        });
      }

      put(0);
    });

    it('successfully compacts', function (done) {
      db.compact(function (err) {
        if (err) return done(err);
        db.compact(function (err) {
          if (err) return done(err);
          done()
        });
      });
    });

    it('successfully saves data', function (done) {
      var get = function (index) {
        if (index === max) {
          return done();
        }
        var buffer = new Buffer(50);
        buffer.fill(index);

        db.get(buffer, function (err, value) {
          if (err) return done(err);
          assert.deepEqual(value, buffer);
          get(++index);
        });
      }
      get(0);
    });

    after(shutdown);
  })
});
<|endoftext|>


<commit_before>/*
Pajar version 0 - A simple JavaScript library to find DOM nodes by CSS selectors.
Copyright (c) 2012, Peter Michaux
All rights reserved.
Licensed under the Simplified BSD License.
https://github.com/petermichaux/pajar/blob/master/LICENSE
*/<commit_msg>whitespace<commit_after>/*
Pajar version 0 - A simple JavaScript library to find DOM nodes by CSS selectors.
Copyright (c) 2012, Peter Michaux
All rights reserved.
Licensed under the Simplified BSD License.
https://github.com/petermichaux/pajar/blob/master/LICENSE
*/
<|endoftext|>


<commit_before>App = {

    config: {
        debug: true
        , datepickerOptions: {
            format: 'yyyy-mm-dd'
        },
        fullMonthNames: [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ],
        shortMonthNames: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec" ],
        queryColors: ['#e14c11', "#249fc9"],
        queryNames: ['Main Query', 'Comparison Query'],
        cookieOpts: {
            'path': '/',
            'domain': 'www.localhost',
            'expires': 1
        }
    },

    // get the url to a tool
    getToolUrl: function(tool){
      return 'https://'+tool+'.'+App.config.cookieOpts['domain']+'/#'+App.con.queryCollection.dashboardUrl();
    },

    // Take a Collection and return a map using the specified key
    makeMap: function (col, key) {
        dataMap = {};
        col.each(function (datum) {
            dataMap[datum.get(key)] = datum;
        });
        return dataMap;
    },

    /**
     * Given array of date objects, return object with keys:
     * - year
     * - month
     * Each contains the first date object for a given year/month
     */
    dateLabels: function (dates) {
      results = { year: [], month:[] };
      // Find indeces of first occurence of each month
      var lastMonthYear = undefined;
      var lastYear = undefined;
      for (idx in dates){
        var d = dates[idx];
        var thisMonthYear = d.getUTCFullYear()+"-"+d.getUTCMonth();
        var thisYear = d.getUTCFullYear();
        if(thisMonthYear!=lastMonthYear){
          results['month'].push(d);
          lastMonthYear = thisMonthYear;
        }
        if(thisYear!=lastYear){
          results['year'].push(d);
          lastYear= thisYear;
        }
      }
      return results;
    },

    monthName: function (m) {
        return App.config.shortMonthNames[m];
    },

    // Round n to nearest half-integer
    halfint: function (n) {
        return Math.round(n + 0.5) - 0.5;
    },

    debug: function (message) {
        if (App.config.debug) {
            console.log(message);
        }
    }
}
<commit_msg>Change settings for release.<commit_after>App = {

    config: {
        debug: false
        , datepickerOptions: {
            format: 'yyyy-mm-dd'
        },
        fullMonthNames: [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ],
        shortMonthNames: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec" ],
        queryColors: ['#e14c11', "#249fc9"],
        queryNames: ['Main Query', 'Comparison Query'],
        cookieOpts: {
            'path': '/',
            'domain': 'mediameter.org',
            'expires': 1
        }
    },

    // get the url to a tool
    getToolUrl: function(tool){
      return 'https://'+tool+'.'+App.config.cookieOpts['domain']+'/#'+App.con.queryCollection.dashboardUrl();
    },

    // Take a Collection and return a map using the specified key
    makeMap: function (col, key) {
        dataMap = {};
        col.each(function (datum) {
            dataMap[datum.get(key)] = datum;
        });
        return dataMap;
    },

    /**
     * Given array of date objects, return object with keys:
     * - year
     * - month
     * Each contains the first date object for a given year/month
     */
    dateLabels: function (dates) {
      results = { year: [], month:[] };
      // Find indeces of first occurence of each month
      var lastMonthYear = undefined;
      var lastYear = undefined;
      for (idx in dates){
        var d = dates[idx];
        var thisMonthYear = d.getUTCFullYear()+"-"+d.getUTCMonth();
        var thisYear = d.getUTCFullYear();
        if(thisMonthYear!=lastMonthYear){
          results['month'].push(d);
          lastMonthYear = thisMonthYear;
        }
        if(thisYear!=lastYear){
          results['year'].push(d);
          lastYear= thisYear;
        }
      }
      return results;
    },

    monthName: function (m) {
        return App.config.shortMonthNames[m];
    },

    // Round n to nearest half-integer
    halfint: function (n) {
        return Math.round(n + 0.5) - 0.5;
    },

    debug: function (message) {
        if (App.config.debug) {
            console.log(message);
        }
    }
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2012 Memorial Sloan-Kettering Cancer Center.
 * This library is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published
 * by the Free Software Foundation; either version 2.1 of the License, or
 * any later version.
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY, WITHOUT EVEN THE IMPLIED WARRANTY OF
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.  The software and
 * documentation provided hereunder is on an "as is" basis, and
 * Memorial Sloan-Kettering Cancer Center
 * has no obligations to provide maintenance, support,
 * updates, enhancements or modifications.  In no event shall
 * Memorial Sloan-Kettering Cancer Center
 * be liable to any party for direct, indirect, special,
 * incidental or consequential damages, including lost profits, arising
 * out of the use of this software and its documentation, even if
 * Memorial Sloan-Kettering Cancer Center
 * has been advised of the possibility of such damage.  See
 * the GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this library; if not, write to the Free Software Foundation,
 * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
 */

(function(){
    var menuApp = angular.module('menu', []);
    menuApp.controller('MenuController', function($scope) {

        //init -- retrieve data
        init = function() {
            var paramsGetProfiles = {
                cancer_study_id: window.PortalGlobals.getCancerStudyId(),
                case_set_id: window.PortalGlobals.getCaseSetId(),
                case_ids_key: window.PortalGlobals.getCaseIdsKey(),
                gene_list: window.PortalGlobals.getGeneListString()
            };
            $.post("getGeneticProfile.json", paramsGetProfiles, getGeneticProfileCallback, "json");

            function getGeneticProfileCallback(profileDataResult) {
                //get gene list
                $.each(window.PortalGlobals.getGeneList(), function(index, value) {
                    $scope.gene.options.push({'label': value, 'value': value});
                });
                //get profile names & ids
                $.each(profileDataResult[window.PortalGlobals.getGeneList()[0]], function(key, obj) {
                    $scope.profileName.options.push({
                        'label': obj.NAME,
                        'value': obj.STABLE_ID
                    });
                });
                //get clinical attributes
                var paramsGetClinicalAttributes = {
                    cmd : "getAllClinicalData",
                    cancer_study_id: window.PortalGlobals.getCancerStudyId(),
                    case_set_id : window.PortalGlobals.getCaseSetId(),
                    format : "json"
                };
                $.post("webservice.do", paramsGetClinicalAttributes, getClinicalAttrCallBack, "json");
                function getClinicalAttrCallBack(clinicalDataResult) {
                    $.each(clinicalDataResult.attributes, function(key, obj) {
                        $scope.clinicalAttr.options.push(
                            {'label': obj.display_name, 'value': obj.attr_id}
                        );
                    });
                    //register form variables
                    $scope.form = {
                        plotsTypeX: $scope.plotsType.options[0].value,
                        plotsTypeY: $scope.plotsType.options[0].value,
                        profileTypeX: $scope.profileType.options[0].value,
                        profileTypeY: $scope.profileType.options[0].value,
                        profileNameX: $scope.profileName.options[0].value,
                        profileNameY: $scope.profileName.options[0].value,
                        geneX: $scope.gene.options[0].value,
                        geneY: $scope.gene.options[0].value,
                        clinicalAttrX: $scope.clinicalAttr.options[0].value,
                        clinicalAttrY: $scope.clinicalAttr.options[0].value
                    };
                }
            }
        };
        init();

        //general options
        $scope.plotsType = {
            'title': "Plots Type",
            "options": [
                {'label': "Genomic Profile", 'value': "genomic_profile" },
                {'label': "Clinical Attributes", 'value': "clinical_attr"}
            ]
        };
        //genomic profile options
        $scope.profileType = {
            'title': "Profile Type",
            "options": [
                {'label': "mRNA", 'value': "mRNA"},
                {'label': "Copy Number", 'value': "copy-number"},
                {'label': "DNA Methylation", 'value': "DNA Methylation"},
                {'label': "RPPA Protein Level", 'value': "RPPA"}
            ]
        };
        $scope.profileName = {
            'title': "Profile Name",
            "options": []
        };
        $scope.gene = {
            'title': "Gene",
            "options": []
        };
        //clinical attributes options
        $scope.clinicalAttr = {
            "title": "Clinical Attributes",
            "options": []
        };

    });

})();
<commit_msg>temp/not compilable<commit_after>/*
 * Copyright (c) 2012 Memorial Sloan-Kettering Cancer Center.
 * This library is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published
 * by the Free Software Foundation; either version 2.1 of the License, or
 * any later version.
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY, WITHOUT EVEN THE IMPLIED WARRANTY OF
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.  The software and
 * documentation provided hereunder is on an "as is" basis, and
 * Memorial Sloan-Kettering Cancer Center
 * has no obligations to provide maintenance, support,
 * updates, enhancements or modifications.  In no event shall
 * Memorial Sloan-Kettering Cancer Center
 * be liable to any party for direct, indirect, special,
 * incidental or consequential damages, including lost profits, arising
 * out of the use of this software and its documentation, even if
 * Memorial Sloan-Kettering Cancer Center
 * has been advised of the possibility of such damage.  See
 * the GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this library; if not, write to the Free Software Foundation,
 * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
 */

(function(){
    var menuApp = angular.module('menu', []);
    menuApp.controller('MenuController', function($scope) {

        //init -- retrieve data
        init = function() {
            var paramsGetProfiles = {
                cancer_study_id: window.PortalGlobals.getCancerStudyId(),
                case_set_id: window.PortalGlobals.getCaseSetId(),
                case_ids_key: window.PortalGlobals.getCaseIdsKey(),
                gene_list: window.PortalGlobals.getGeneListString()
            };
            $.post("getGeneticProfile.json", paramsGetProfiles, getGeneticProfileCallback, "json");

            function getGeneticProfileCallback(profileDataResult) {
                //get gene list
                $.each(window.PortalGlobals.getGeneList(), function(index, value) {
                    $scope.gene.options.push({'label': value, 'value': value});
                });
                //get profile names & ids
                $.each(profileDataResult[window.PortalGlobals.getGeneList()[0]], function(key, obj) {
                    $scope.profileName.options.push({
                        'label': obj.NAME,
                        'value': obj.STABLE_ID
                    });
                });
                //get clinical attributes
                var paramsGetClinicalAttributes = {
                    cmd : "getAllClinicalData",
                    cancer_study_id: window.PortalGlobals.getCancerStudyId(),
                    case_set_id : window.PortalGlobals.getCaseSetId(),
                    format : "json"
                };
                $.post("webservice.do", paramsGetClinicalAttributes, getClinicalAttrCallBack, "json");
                function getClinicalAttrCallBack(clinicalDataResult) {
                    $.each(clinicalDataResult.attributes, function(key, obj) {
                        $scope.clinicalAttr.options.push(
                            {'label': obj.display_name, 'value': obj.attr_id}
                        );
                    });
                    //register form variables
                    $scope.form = {
                        plotsTypeX: $scope.plotsType.options[0].value,
                        plotsTypeY: $scope.plotsType.options[0].value,
                        profileTypeX: $scope.profileType.options[0].value,
                        profileTypeY: $scope.profileType.options[0].value,
                        profileNameX: $scope.profileName.options[0].value,
                        profileNameY: $scope.profileName.options[0].value,
                        geneX: $scope.gene.options[0].value,
                        geneY: $scope.gene.options[0].value,
                        clinicalAttrX: $scope.clinicalAttr.options[0].value,
                        clinicalAttrY: $scope.clinicalAttr.options[0].value
                    };
                }
            }
        };
        init();

        //general options
        $scope.plotsType = {
            'title': "Plots Type",
            "options": [
                {'label': "Genomic Profile", 'value': "genomic_profile" },
                {'label': "Clinical Attributes", 'value': "clinical_attr"}
            ]
        };
        //genomic profile options
        $scope.profileType = {
            'title': "Profile Type",
            "options": [
                {'label': "mRNA", 'value': "mRNA"},
                {'label': "Copy Number", 'value': "copy-number"},
                {'label': "DNA Methylation", 'value': "DNA Methylation"},
                {'label': "RPPA Protein Level", 'value': "RPPA"}
            ]
        };
        $scope.profileName = {
            'title': "Profile Name",
            "options": []
        };
        $scope.gene = {
            'title': "Gene",
            "options": []
        };
        //clinical attributes options
        $scope.clinicalAttr = {
            "title": "Clinical Attributes",
            "options": []
        };

    });

})();

var PlotsTabSidebar = (function() {

    function fetchProfileMetaData() {
        var paramsGetProfiles = {
            cancer_study_id: window.PortalGlobals.getCancerStudyId(),
            case_set_id: window.PortalGlobals.getCaseSetId(),
            case_ids_key: window.PortalGlobals.getCaseIdsKey(),
            gene_list: window.PortalGlobals.getGeneListString()
        };
        $.post("getGeneticProfile.json", paramsGetProfiles, getGeneticProfileCallback, "json");
    }

    function fetchClinicalAttrMetaData(profileMetaDataResult) {
        var paramsGetClinicalAttributes = {
            cmd : "getAllClinicalData",
            cancer_study_id: window.PortalGlobals.getCancerStudyId(),
            case_set_id : window.PortalGlobals.getCaseSetId(),
            format : "json"
        };
        $.post("webservice.do", paramsGetClinicalAttributes, getClinicalAttrCallBack(profileMetaDataResult), "json");
    }

    function mergeMetaData(clinicalAttrMetaDataResult, profileMetaDataResult) {
        console.log(clinicalAttrMetaDataResult);
        console.log(profileMetaDataResult);
    }

    return {
        init: function() {
            fetchProfileMetaData(); //invoke fetch other meta data in a chain
        }
    }

}());
<|endoftext|>


<commit_before>const fs = require('fs')
const path = require('path')

const coinUtils = require('../coin-utils')

const common = require('./common')

module.exports = {setup}

const coinRec = coinUtils.getCryptoCurrency('BTC')

function setup (dataDir) {
  common.firewall([coinRec.defaultPort])
  const config = buildConfig()
  fs.writeFileSync(path.resolve(dataDir, coinRec.configFile), config)
  const cmd = `/usr/local/bin/${coinRec.daemon} -datadir=${dataDir}`
  common.writeSupervisorConfig(coinRec, cmd)
}

function buildConfig () {
  return `rpcuser=lamassuserver
rpcpassword=${common.randomPass()}
dbcache=500`
}
<commit_msg>fix dash bug in lamassu-coins<commit_after>const fs = require('fs')
const path = require('path')

const coinUtils = require('../coin-utils')

const common = require('./common')

module.exports = {setup}

const coinRec = coinUtils.getCryptoCurrency('DASH')

function setup (dataDir) {
  common.firewall([coinRec.defaultPort])
  const config = buildConfig()
  fs.writeFileSync(path.resolve(dataDir, coinRec.configFile), config)
  const cmd = `/usr/local/bin/${coinRec.daemon} -datadir=${dataDir}`
  common.writeSupervisorConfig(coinRec, cmd)
}

function buildConfig () {
  return `rpcuser=lamassuserver
rpcpassword=${common.randomPass()}
dbcache=500`
}
<|endoftext|>


<commit_before>define(["ShipAction", "process/ui/ShipActionUI"], function(ShipAction, ShipActionUI)
{
    "use strict";
    var ShipActionChooser = React.createClass(
    {
        propTypes:
        {
            callback: React.PropTypes.func.isRequired,
            imageBase: React.PropTypes.string.isRequired,
            shipActions: React.PropTypes.array.isRequired,
            token: React.PropTypes.object.isRequired,
        },

        getInitialState: function()
        {
            var shipActions = this.props.shipActions;

            return (
            {
                selected: (shipActions.length > 0 ? shipActions[0] : undefined),
            });
        },

        render: function()
        {
            var token = this.props.token;
            var message = "Active Ship: " + token.name();
            var shipActions = this.props.shipActions;
            var imageBase = this.props.imageBase;
            var idFunction = function(value)
            {
                return value.toString();
            };
            var labelFunction = function(value)
            {
                var answer = React.DOM.span(
                {}, React.createElement(ShipActionUI,
                {
                    shipAction: ShipAction.properties[value.shipActionKey()],
                    imageBase: imageBase,
                }), " ", value.toString());
                return answer;
            };
            var initialValue = (shipActions.length > 0 ? shipActions[0] : undefined);
            var initialInput = React.createElement(InputPanel,
            {
                type: "radio",
                values: shipActions,
                name: "shipActionRadio",
                idFunction: idFunction,
                labelFunction: labelFunction,
                initialValues: initialValue,
                onChange: this.selectionChanged,
                panelClass: "optionPaneInput",
            });
            var cancelButton = React.DOM.button(
            {
                key: 0,
                onClick: this.cancel
            }, "Cancel");
            var okButton = React.DOM.button(
            {
                key: 1,
                onClick: this.ok
            }, "OK");
            var buttons = React.DOM.span(
            {}, [cancelButton, okButton]);

            return React.createElement(OptionPane,
            {
                panelClass: "optionPane",
                title: "Select Action",
                titleClass: "optionPaneTitle",
                message: message,
                messageClass: "optionPaneMessage",
                initialInput: initialInput,
                buttons: buttons,
                buttonsClass: "optionPaneButtons"
            });
        },

        selectionChanged: function(event)
        {
            var selected = event.target.id;
            var shipActions = this.props.shipActions;

            for (var i = 0; i < shipActions.length; i++)
            {
                var shipAction = shipActions[i];

                if (shipAction.toString() === selected)
                {
                    selected = shipAction;
                    break;
                }
            }

            LOGGER.debug("selectionChanged() selected = " + selected + " typeof selected = " + (typeof selected));

            this.setState(
            {
                selected: selected,
            });
        },

        cancel: function()
        {
            LOGGER.debug("Cancel clicked");
            this.props.callback(undefined);
        },

        ok: function()
        {
            var selected = this.state.selected;
            LOGGER.debug("OK clicked, selected = " + selected);
            this.props.callback(selected);
        },
    });

    return ShipActionChooser;
});
<commit_msg>Changed to use the new AbilityUI.<commit_after>define(["ShipAction", "process/ui/AbilityUI", "process/ui/ShipActionUI"],
    function(ShipAction, AbilityUI, ShipActionUI)
    {
        "use strict";
        var ShipActionChooser = React.createClass(
        {
            propTypes:
            {
                callback: React.PropTypes.func.isRequired,
                imageBase: React.PropTypes.string.isRequired,
                shipActions: React.PropTypes.array.isRequired,
                token: React.PropTypes.object.isRequired,
            },

            getInitialState: function()
            {
                var shipActions = this.props.shipActions;

                return (
                {
                    selected: (shipActions.length > 0 ? shipActions[0] : undefined),
                });
            },

            render: function()
            {
                var token = this.props.token;
                var message = "Active Ship: " + token.name();
                var shipActions = this.props.shipActions;
                var imageBase = this.props.imageBase;
                var idFunction = function(value)
                {
                    return value.toString();
                };
                var labelFunction = function(value)
                {
                    var answer;
                    if (value.shipActionKey() === "criticalDamage")
                    {
                        answer = React.createElement(AbilityUI.Damage,
                        {
                            damage: value.damage(),
                            imageBase: imageBase,
                        });
                    }
                    else if (value.shipActionKey() === "upgrade")
                    {
                        answer = React.createElement(AbilityUI.Upgrade,
                        {
                            upgrade: value.upgrade(),
                            imageBase: imageBase,
                        });
                    }
                    else
                    {
                        answer = React.DOM.span(
                        {}, React.createElement(ShipActionUI,
                        {
                            shipAction: ShipAction.properties[value.shipActionKey()],
                            imageBase: imageBase,
                        }), " ", value.toString());
                    }
                    return answer;
                };
                var initialValue = (shipActions.length > 0 ? shipActions[0] : undefined);
                var initialInput = React.createElement(InputPanel,
                {
                    type: "radio",
                    values: shipActions,
                    name: "shipActionRadio",
                    idFunction: idFunction,
                    labelFunction: labelFunction,
                    initialValues: initialValue,
                    onChange: this.selectionChanged,
                    panelClass: "optionPaneInput",
                });
                var cancelButton = React.DOM.button(
                {
                    key: 0,
                    onClick: this.cancel
                }, "Cancel");
                var okButton = React.DOM.button(
                {
                    key: 1,
                    onClick: this.ok
                }, "OK");
                var buttons = React.DOM.span(
                {}, [cancelButton, okButton]);

                return React.createElement(OptionPane,
                {
                    panelClass: "optionPane",
                    title: "Select Action",
                    titleClass: "optionPaneTitle",
                    message: message,
                    messageClass: "optionPaneMessage",
                    initialInput: initialInput,
                    buttons: buttons,
                    buttonsClass: "optionPaneButtons"
                });
            },

            selectionChanged: function(event)
            {
                var selected = event.target.id;
                var shipActions = this.props.shipActions;

                for (var i = 0; i < shipActions.length; i++)
                {
                    var shipAction = shipActions[i];

                    if (shipAction.toString() === selected)
                    {
                        selected = shipAction;
                        break;
                    }
                }

                LOGGER.debug("selectionChanged() selected = " + selected + " typeof selected = " + (typeof selected));

                this.setState(
                {
                    selected: selected,
                });
            },

            cancel: function()
            {
                LOGGER.debug("Cancel clicked");
                this.props.callback(undefined);
            },

            ok: function()
            {
                var selected = this.state.selected;
                LOGGER.debug("OK clicked, selected = " + selected);
                this.props.callback(selected);
            },
        });

        return ShipActionChooser;
    });
<|endoftext|>


<commit_before>/* @flow */

import React from 'react'

class FixButton extends React.Component {
  handleClick(): void {
    this.props.cb()
  }
  render() {
    return <button className="fix-btn" onClick={() => this.handleClick()}>Fix</button>
  }
}

module.exports = FixButton
<commit_msg>Add props declaration of FixButton<commit_after>/* @flow */

import React from 'react'

class FixButton extends React.Component {
  props: {
      cb: () => void,
  };
  handleClick(): void {
    this.props.cb()
  }
  render() {
    return <button className="fix-btn" onClick={() => this.handleClick()}>Fix</button>
  }
}

module.exports = FixButton
<|endoftext|>


<commit_before>'use strict'
var fs = require('fs');
var path = require('path');
var qs = require('querystring');
var os = require('os');

var request = require('request');
var Promise = require('bluebird');
var _ = require('underscore');
var prompt = require('prompt');
var jws = require('jsonwebtoken');

module.exports = class HapiJWTCouch{
    constructor(){
        this.auth = {};
        this.uri = "";
        this.agentOptions = {};
        this.setServerUri = this.setServer;
    }

    getAuth(){
        return this.auth;
    }

    setServer(uri){
        if(_.isObject(uri)){
            _.extend(this, uri);
        }else{
            this.uri = uri;
        }
    }

    getserver(){
        return this.uri;
    }

    getServer(){
        return this.uri
    }

    setAgentOptions(agentOptions){
        this.agentOptions = agentOptions;
    }

    promptUsernamePassword(){
        var self = this;
        return new Promise(function(resolve, reject){
            var schema = {
                properties: {
                    email: {
                        pattern: /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
                        message: 'Email address',
                        required: true
                    },
                    password: {
                        hidden: true,
                        required: true
                    }
                }
            };
            prompt.get(schema, function (err, result) {
                if(err){
                    reject(err)
                }else{
                    resolve(result);
                }
            });
        });
    }

    promptServer(){
        var self = this;
        return new Promise(function(resolve, reject){
            var schema = {
                properties: {
                    uri: {
                        message: 'Please enter the server uri',
                        required: true
                    }
                }
            };
            prompt.get(schema, function (err, result) {
                if(err){
                    reject(err)
                }else{
                    resolve(result);
                }
            });
        });
    }

    start(){
        var self = this;
        return self.promptServer()
        .then(function(server){
            self.setServer(server);
            return self.promptUsernamePassword()
        })
        .then(function(user){
            return self.userLogin(user);
        })
    }

    testUserToken(token){
        var jwt = jws.decode(token.token);
        var self = this;

        if(jwt.exp && jwt.exp < Date.now() / 1000){
            return false;
        }else if(jwt.exp === undefined){
            console.log("WARNING! The token does not have an expiry date. Tokens without expiry date were deprecated. The server could be running an old version. Please contact the server administrator.");
        }
        return true;
    }

    setUserToken(token){
        var self = this;
        if(_.isObject(token)){
            if(token.token){
                self.auth.bearer = token.token;
            }else{
                console.error("self.setUserToken: ", JSON.stringify(token));
                throw "Invalid token set for auth mechanism, must be an object {'token': 'someAuthToken'}";
            }
        }else{
            self.auth.bearer = token;
        }
    }

    getUserToken(){
        return {
            token: self.auth.bearer
        };
    }

    //Here the implementation of different functions starts
    createUser(user){
        var self = this;
        return new Promise(function(resolve, reject){
            var options = {
                url: self.getServer() + "/auth/user",
                method: 'POST',
                json: user,
                agentOptions: self.agentOptions
            }

            request(options, function(err, res, body){
                if(err){
                    reject(err);
                }else{
                    resolve(body);
                }
            });
        });
    }

    resetPassword(user){
        var self = this;
        return new Promise(function(resolve, reject){
            var options = {
                url: self.getServer() + "/auth/reset",
                method: 'POST',
                json: user,
                agentOptions: self.agentOptions
            }

            request(options, function(err, res, body){
                if(err){
                    reject(err);
                }else{
                    resolve(body);
                }
            });
        });
    }

    userLogin(user){
        var self = this;
        return new Promise(function(resolve, reject){
            var options = {
                url: self.getServer() + "/auth/login",
                method: 'POST',
                json: user,
                agentOptions: self.agentOptions
            }

            request(options, function(err, res, body){
                if(err){
                    reject(err);
                }else{
                    self.auth.bearer = body.token
                    resolve(body);
                }
            });
        });
    }

    getUser(){
        var self = this;
        return new Promise(function(resolve, reject){
            var options = {
                url: self.getServer() + "/auth/user",
                method: 'GET',
                auth: self.auth,
                agentOptions: self.agentOptions
            }

            request(options, function(err, res, body){
                if(err){
                    reject(err);
                }else{
                    resolve(JSON.parse(body));
                }
            });
        });
    }

    getUsers(){
        var self = this;
        return new Promise(function(resolve, reject){
            var options = {
                url: self.getServer() + "/auth/users",
                method: 'GET',
                auth: self.auth,
                agentOptions: self.agentOptions
            }

            request(options, function(err, res, body){
                if(err){
                    reject(err);
                }else{
                    resolve(body);
                }
            });
        });
    }

    updateUser(userinfo){
        var self = this;
        return new Promise(function(resolve, reject){

            var usinfo = _.clone(userinfo);

            if(usinfo.scope){
                delete usinfo.scope;
            }

            var options = {
                url: self.getServer() + "/auth/user",
                method: 'PUT',
                json: usinfo,
                auth: self.auth,
                agentOptions: self.agentOptions
            }

            request(options, function(err, res, body){
                if(err){
                    reject(err);
                }else{
                    resolve(body);
                }
            });
        });
    }

    updateUsers(userinfo){
        var self = this;
        return new Promise(function(resolve, reject){
            var options = {
                url: self.getServer() + "/auth/users",
                method: 'PUT',
                json: userinfo,
                auth: self.auth,
                agentOptions: self.agentOptions
            }

            request(options, function(err, res, body){
                if(err){
                    reject(err);
                }else{
                    resolve(body);
                }
            });
        });
    }

    deleteUser(){
        var self = this;
        return new Promise(function(resolve, reject){
            var options = {
                url: self.getServer() + "/auth/user",
                method: 'DELETE',
                agentOptions: self.agentOptions,
                auth: self.auth
            }

            request(options, function(err, res, body){
                if(err){
                    reject(err);
                }else{
                    resolve(body);
                }
            });
        });
    }

    deleteUsers(user){
        var self = this;
        return new Promise(function(resolve, reject){
            var options = {
                url: self.getServer() + "/auth/users",
                method: 'DELETE',
                agentOptions: self.agentOptions,
                auth: self.auth,
                json: user
            }

            request(options, function(err, res, body){
                if(err){
                    reject(err);
                }else{
                    resolve(body);
                }
            });
        });
    }
}<commit_msg>BUG: Check if the body contains the token. Otherwise, reject with the body<commit_after>'use strict'
var fs = require('fs');
var path = require('path');
var qs = require('querystring');
var os = require('os');

var request = require('request');
var Promise = require('bluebird');
var _ = require('underscore');
var prompt = require('prompt');
var jws = require('jsonwebtoken');

module.exports = class HapiJWTCouch{
    constructor(){
        this.auth = {};
        this.uri = "";
        this.agentOptions = {};
        this.setServerUri = this.setServer;
    }

    getAuth(){
        return this.auth;
    }

    setServer(uri){
        if(_.isObject(uri)){
            _.extend(this, uri);
        }else{
            this.uri = uri;
        }
    }

    getserver(){
        return this.uri;
    }

    getServer(){
        return this.uri
    }

    setAgentOptions(agentOptions){
        this.agentOptions = agentOptions;
    }

    promptUsernamePassword(){
        var self = this;
        return new Promise(function(resolve, reject){
            var schema = {
                properties: {
                    email: {
                        pattern: /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
                        message: 'Email address',
                        required: true
                    },
                    password: {
                        hidden: true,
                        required: true
                    }
                }
            };
            prompt.get(schema, function (err, result) {
                if(err){
                    reject(err)
                }else{
                    resolve(result);
                }
            });
        });
    }

    promptServer(){
        var self = this;
        return new Promise(function(resolve, reject){
            var schema = {
                properties: {
                    uri: {
                        message: 'Please enter the server uri',
                        required: true
                    }
                }
            };
            prompt.get(schema, function (err, result) {
                if(err){
                    reject(err)
                }else{
                    resolve(result);
                }
            });
        });
    }

    start(){
        var self = this;
        return self.promptServer()
        .then(function(server){
            self.setServer(server);
            return self.promptUsernamePassword()
        })
        .then(function(user){
            return self.userLogin(user);
        })
    }

    testUserToken(token){
        var jwt = jws.decode(token.token);
        var self = this;

        if(jwt.exp && jwt.exp < Date.now() / 1000){
            return false;
        }else if(jwt.exp === undefined){
            console.log("WARNING! The token does not have an expiry date. Tokens without expiry date were deprecated. The server could be running an old version. Please contact the server administrator.");
        }
        return true;
    }

    setUserToken(token){
        var self = this;
        if(_.isObject(token)){
            if(token.token){
                self.auth.bearer = token.token;
            }else{
                console.error("self.setUserToken: ", JSON.stringify(token));
                throw "Invalid token set for auth mechanism, must be an object {'token': 'someAuthToken'}";
            }
        }else{
            self.auth.bearer = token;
        }
    }

    getUserToken(){
        return {
            token: self.auth.bearer
        };
    }

    //Here the implementation of different functions starts
    createUser(user){
        var self = this;
        return new Promise(function(resolve, reject){
            var options = {
                url: self.getServer() + "/auth/user",
                method: 'POST',
                json: user,
                agentOptions: self.agentOptions
            }

            request(options, function(err, res, body){
                if(err){
                    reject(err);
                }else{
                    resolve(body);
                }
            });
        });
    }

    resetPassword(user){
        var self = this;
        return new Promise(function(resolve, reject){
            var options = {
                url: self.getServer() + "/auth/reset",
                method: 'POST',
                json: user,
                agentOptions: self.agentOptions
            }

            request(options, function(err, res, body){
                if(err){
                    reject(err);
                }else{
                    resolve(body);
                }
            });
        });
    }

    userLogin(user){
        var self = this;
        return new Promise(function(resolve, reject){
            var options = {
                url: self.getServer() + "/auth/login",
                method: 'POST',
                json: user,
                agentOptions: self.agentOptions
            }

            request(options, function(err, res, body){
                if(err){
                    reject(err);
                }else if(body && body.token){
                    self.auth.bearer = body.token
                    resolve(body);
                }else{
                    reject(body);
                }
            });
        });
    }

    getUser(){
        var self = this;
        return new Promise(function(resolve, reject){
            var options = {
                url: self.getServer() + "/auth/user",
                method: 'GET',
                auth: self.auth,
                agentOptions: self.agentOptions
            }

            request(options, function(err, res, body){
                if(err){
                    reject(err);
                }else{
                    resolve(JSON.parse(body));
                }
            });
        });
    }

    getUsers(){
        var self = this;
        return new Promise(function(resolve, reject){
            var options = {
                url: self.getServer() + "/auth/users",
                method: 'GET',
                auth: self.auth,
                agentOptions: self.agentOptions
            }

            request(options, function(err, res, body){
                if(err){
                    reject(err);
                }else{
                    resolve(body);
                }
            });
        });
    }

    updateUser(userinfo){
        var self = this;
        return new Promise(function(resolve, reject){

            var usinfo = _.clone(userinfo);

            if(usinfo.scope){
                delete usinfo.scope;
            }

            var options = {
                url: self.getServer() + "/auth/user",
                method: 'PUT',
                json: usinfo,
                auth: self.auth,
                agentOptions: self.agentOptions
            }

            request(options, function(err, res, body){
                if(err){
                    reject(err);
                }else{
                    resolve(body);
                }
            });
        });
    }

    updateUsers(userinfo){
        var self = this;
        return new Promise(function(resolve, reject){
            var options = {
                url: self.getServer() + "/auth/users",
                method: 'PUT',
                json: userinfo,
                auth: self.auth,
                agentOptions: self.agentOptions
            }

            request(options, function(err, res, body){
                if(err){
                    reject(err);
                }else{
                    resolve(body);
                }
            });
        });
    }

    deleteUser(){
        var self = this;
        return new Promise(function(resolve, reject){
            var options = {
                url: self.getServer() + "/auth/user",
                method: 'DELETE',
                agentOptions: self.agentOptions,
                auth: self.auth
            }

            request(options, function(err, res, body){
                if(err){
                    reject(err);
                }else{
                    resolve(body);
                }
            });
        });
    }

    deleteUsers(user){
        var self = this;
        return new Promise(function(resolve, reject){
            var options = {
                url: self.getServer() + "/auth/users",
                method: 'DELETE',
                agentOptions: self.agentOptions,
                auth: self.auth,
                json: user
            }

            request(options, function(err, res, body){
                if(err){
                    reject(err);
                }else{
                    resolve(body);
                }
            });
        });
    }
}<|endoftext|>


<commit_before>/*================================================================
 =>                  App = oneHydraMini
 ==================================================================*/
/*global angular*/

var app = angular.module('oneHydraMini', ['ngMessages', 'ngCookies', 'ngResource', 'ngSanitize', 'ngRoute', 'ngAnimate',
    "ui.utils", "ui.bootstrap", "ui.router"]);

app.config(['$stateProvider', '$urlRouterProvider', '$locationProvider', '$httpProvider',
    function ($stateProvider, $urlRouterProvider, $locationProvider, $httpProvider) {
        'use strict';

        $stateProvider

            .state('volume-prediction', {
                url: '/volume-prediction',
                controller: 'VolumePredictionCtrl',
                templateUrl: '../templates/pages/volume-prediction.html'
            })

            .state('about', {
                url: '/about',
                controller: 'AboutCtrl',
                templateUrl: '../templates/pages/about.html'
            });

        $urlRouterProvider.otherwise('/volume-prediction');

        // This is required for Browser Sync to work poperly
        $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
    }]);

/*================================================================
 =>                  oneHydraMini App Run()
 ==================================================================*/

app.run(['$rootScope', function ($rootScope) {
    'use strict';
}]);

/* ---> Do not delete this comment (Values) <--- */

/* ---> Do not delete this comment (Constants) <--- */
<commit_msg>Update app.js<commit_after>/*================================================================
 =>                  App = oneHydraMini
 ==================================================================*/
/*global angular*/

var app = angular.module('oneHydraMini', ['ngMessages', 'ngCookies', 'ngResource', 'ngSanitize', 'ngRoute', 'ngAnimate', 'ui.bootstrap', 'ui.router']);

app.config(['$stateProvider', '$urlRouterProvider', '$locationProvider', '$httpProvider',
    function ($stateProvider, $urlRouterProvider, $locationProvider, $httpProvider) {
        'use strict';

        $stateProvider

            .state('volume-prediction', {
                url: '/volume-prediction',
                controller: 'VolumePredictionCtrl',
                templateUrl: '../templates/pages/volume-prediction.html'
            })

            .state('about', {
                url: '/about',
                controller: 'AboutCtrl',
                templateUrl: '../templates/pages/about.html'
            });

        $urlRouterProvider.otherwise('/volume-prediction');

        // This is required for Browser Sync to work poperly
        $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
    }]);

/*================================================================
 =>                  oneHydraMini App Run()
 ==================================================================*/

app.run(['$rootScope', function ($rootScope) {
    'use strict';
}]);

/* ---> Do not delete this comment (Values) <--- */

/* ---> Do not delete this comment (Constants) <--- */
<|endoftext|>