<commit_before>define(['underscore', 'app', 'backbone', 'backbone.marionette', 'nusmods',
    'hbs!../templates/select', 'hbs!../templates/select_result','select2'],
  function(_, App, Backbone, Marionette, NUSMods, template, selectResultTemplate) {
    'use strict';

    var codes, titles, modsLength;
    var codesAndTitlesPromise = NUSMods.getCodesAndTitles().then(function (data) {
      codes = _.keys(data);
      titles = _.values(data);
      modsLength = codes.length;
    });

    return Marionette.ItemView.extend({
      className: 'form-group',
      template: template,

      events: {
        'select2-selecting': 'onSelect2Selecting'
      },

      ui: {
        'input': 'input'
      },

      onAdd: function (event) {
        App.request('addModule', $(event.currentTarget).data('code'));
        this.ui.input.select2('focus');
      },

      onRemove: function (event) {
        App.request('removeModule', $(event.currentTarget).data('code'));
        this.ui.input.select2('focus');
      },

      onSelect2Open: function () {
        $('#select2-drop')
          .on('mouseup', '.add', this.onAdd)
          .on('mouseup', '.remove', this.onRemove);
      },

      onSelect2Selecting: function(event) {
        event.preventDefault();
        Backbone.history.navigate('modules/' + event.val, {trigger: true});
        this.ui.input.select2('focus');
      },

      onShow: function () {
        _.bindAll(this, 'onAdd', 'onRemove', 'onSelect2Open');

        var PAGE_SIZE = 50;
        this.ui.input.select2({
          multiple: true,
          formatResult: function (object) {
            return selectResultTemplate(object);
          },
          query: function (options) {
            codesAndTitlesPromise.then(function () {
              var i,
                results = [],
                pushResult = function (i) {
                  return results.push({
                    id: codes[i],
                    selected: App.request('isModuleSelected', codes[i]),
                    text: codes[i] + ' ' + titles[i]
                  });
                };
              if (options.term) {
                var re = new RegExp(options.term, 'i');
                for (i = options.context || 0; i < modsLength; i++) {
                  if (codes[i].search(re) !== -1 || titles[i].search(re) !== -1) {
                    if (pushResult(i) === PAGE_SIZE) {
                      i++;
                      break;
                    }
                  }
                }
              } else {
                for (i = (options.page - 1) * PAGE_SIZE; i < options.page * PAGE_SIZE; i++) {
                  pushResult(i);
                }
              }
              options.callback({
                context: i,
                more: i < modsLength,
                results: results
              });
            });
          }
        });

        this.ui.input.one('select2-open', this.onSelect2Open);
      }
    });
  });
<commit_msg>Close instead of focusing select after selecting module<commit_after>define(['underscore', 'app', 'backbone', 'backbone.marionette', 'nusmods',
    'hbs!../templates/select', 'hbs!../templates/select_result','select2'],
  function(_, App, Backbone, Marionette, NUSMods, template, selectResultTemplate) {
    'use strict';

    var codes, titles, modsLength;
    var codesAndTitlesPromise = NUSMods.getCodesAndTitles().then(function (data) {
      codes = _.keys(data);
      titles = _.values(data);
      modsLength = codes.length;
    });

    return Marionette.ItemView.extend({
      className: 'form-group',
      template: template,

      events: {
        'select2-selecting': 'onSelect2Selecting'
      },

      ui: {
        'input': 'input'
      },

      onAdd: function (event) {
        App.request('addModule', $(event.currentTarget).data('code'));
        this.ui.input.select2('focus');
      },

      onRemove: function (event) {
        App.request('removeModule', $(event.currentTarget).data('code'));
        this.ui.input.select2('focus');
      },

      onSelect2Open: function () {
        $('#select2-drop')
          .on('mouseup', '.add', this.onAdd)
          .on('mouseup', '.remove', this.onRemove);
      },

      onSelect2Selecting: function(event) {
        event.preventDefault();
        Backbone.history.navigate('modules/' + event.val, {trigger: true});
        this.ui.input.select2('close');
      },

      onShow: function () {
        _.bindAll(this, 'onAdd', 'onRemove', 'onSelect2Open');

        var PAGE_SIZE = 50;
        this.ui.input.select2({
          multiple: true,
          formatResult: function (object) {
            return selectResultTemplate(object);
          },
          query: function (options) {
            codesAndTitlesPromise.then(function () {
              var i,
                results = [],
                pushResult = function (i) {
                  return results.push({
                    id: codes[i],
                    selected: App.request('isModuleSelected', codes[i]),
                    text: codes[i] + ' ' + titles[i]
                  });
                };
              if (options.term) {
                var re = new RegExp(options.term, 'i');
                for (i = options.context || 0; i < modsLength; i++) {
                  if (codes[i].search(re) !== -1 || titles[i].search(re) !== -1) {
                    if (pushResult(i) === PAGE_SIZE) {
                      i++;
                      break;
                    }
                  }
                }
              } else {
                for (i = (options.page - 1) * PAGE_SIZE; i < options.page * PAGE_SIZE; i++) {
                  pushResult(i);
                }
              }
              options.callback({
                context: i,
                more: i < modsLength,
                results: results
              });
            });
          }
        });

        this.ui.input.one('select2-open', this.onSelect2Open);
      }
    });
  });
<|endoftext|>


<commit_before>/**
 * @ngdoc service
 * @name  core.service:WsApi
 * @requires ng.$q
 * @requires core.service:RestApi
 * @requires core.service:WsService
 *
 * @description
 *  A service wrapper for the webservices api.
 *
 */
core.service("WsApi", function ($q, $location, $rootScope, RestApi, WsService) {

    var WsApi = this;

    var listenCount = 0;

    var subscriptions = {};

    var routeBasedChannels = {};

    $rootScope.$on("$routeChangeStart", function (evt, next, current) {
        WsService.unsubscribeAll();
    });

    $rootScope.$on("$routeChangeSuccess", function (evt, next, current) {
        var path = $location.path();
        var channels = routeBasedChannels[path];
        if (channels) {
            for (var i in channels) {
                WsApi.listen(channels[i]);
            }
        }
    });

    /**
     * @ngdoc method
     * @name  core.service:WsApi#WsApi.listen
     * @methodOf core.service:WsApi
     * @param {object} apiReq
     *  An apireq which containes the channel, controller and method
     *  which should be listened to.
     * @returns {Promsie} A promise from a websocket subscription subscription
     *
     * @description
     *  This method gives a promise which is notified upon
     *  websocket communication on the desired channel
     *
     */
    WsApi.listen = function (apiReq) {
        var channel;
        if (typeof apiReq === 'string') {
            channel = apiReq;
        } else {
            channel = apiReq.endpoint + "/" + apiReq.controller;
            if (apiReq.method) {
                channel += "/" + apiReq.method;
            }
        }
        if (subscriptions[channel] === undefined) {
            console.log('subscribed', channel);
            subscriptions[channel] = WsService.subscribe(channel, listenCount++, true, function () {
                console.log('unsubscribed', channel);
                delete subscriptions[channel];
                listenCount--;
            }).defer.promise;

            var path = $location.path();
            var channels = routeBasedChannels[path];
            if (channels === undefined) {
                routeBasedChannels[path] = channels = [];
            }
            channels.push(channel);
        }
        return subscriptions[channel]
    };

    WsApi.clearSubscriptions = function () {
        WsService.unsubscribeAll();
        listenCount = 0;
    };

    /**
     * @ngdoc method
     * @name  core.service:WsApi#WsApi.fetch
     * @methodOf core.service:WsApi
     * @param {object} apiReq
     *  An apireq which containes the channel, controller and method
     *  which should be listened to.
     * @returns {Promsie} A promise from the WsService send method
     *
     * @description
     *  This method gives a promise which is resolved by id upon
     *  websocket communication on the desired channel
     *
     */
    WsApi.fetch = function (initialReq, manifest, query) {

        var apiReq = angular.copy(initialReq);

        if (manifest && manifest.pathValues) {
            for (var key in manifest.pathValues) {
                var value = manifest.pathValues[key];
                apiReq.method = apiReq.method.replace(new RegExp(':' + key, 'g'), value);
            }
        }

        if (manifest && manifest.data) {
          apiReq.data = manifest.data;
        }

        if (manifest && manifest.query) {
          apiReq.query = manifest.query;
        }

        if (apiReq.useWebSockets) {
            var request = '/ws/' + apiReq.controller + '/' + apiReq.method;
            var channel = apiReq.endpoint + "/" + apiReq.controller + "/" + apiReq.method;

            var headers = {
                'jwt': sessionStorage.token
            };

            var payload = apiReq.data !== undefined && apiReq.data !== null ? JSON.stringify(apiReq.data) : JSON.stringify({});

            return WsService.send(request, headers, payload, channel);
        }

        var restSend = RestApi.get;

        if(manifest && manifest.method) {
          restSend = RestApi[manifest.method];
        } else {
          restSend = (apiReq.data !== undefined && apiReq.data !== null) ? RestApi.post : restSend;
        }

        return $q(function (resolve, reject) {
            restSend(apiReq).then(function (res) {
                resolve({
                    body: angular.toJson(res)
                });
            });
        });
    };

    return WsApi;

});<commit_msg>Update wsApi.js<commit_after>/**
 * @ngdoc service
 * @name  core.service:WsApi
 * @requires ng.$q
 * @requires core.service:RestApi
 * @requires core.service:WsService
 *
 * @description
 *  A service wrapper for the webservices api.
 *
 */
core.service("WsApi", function ($q, $location, $rootScope, RestApi, WsService) {

    var WsApi = this;

    var listenCount = 0;

    var subscriptions = {};

    var routeBasedChannels = {};

    $rootScope.$on("$routeChangeStart", function (evt, next, current) {
        WsService.unsubscribeAll();
    });

    $rootScope.$on("$routeChangeSuccess", function (evt, next, current) {
        var path = $location.path();
        var channels = routeBasedChannels[path];
        if (channels) {
            for (var i in channels) {
                WsApi.listen(channels[i]);
            }
        }
    });

    /**
     * @ngdoc method
     * @name  core.service:WsApi#WsApi.listen
     * @methodOf core.service:WsApi
     * @param {object} apiReq
     *  An apireq which containes the channel, controller and method
     *  which should be listened to.
     * @returns {Promsie} A promise from a websocket subscription subscription
     *
     * @description
     *  This method gives a promise which is notified upon
     *  websocket communication on the desired channel
     *
     */
    WsApi.listen = function (apiReq) {
        var channel;
        if (typeof apiReq === 'string') {
            channel = apiReq;
        } else {
            channel = apiReq.endpoint + "/" + apiReq.controller;
            if (apiReq.method) {
                channel += "/" + apiReq.method;
            }
        }
        if (subscriptions[channel] === undefined) {
            console.log('subscribed', channel);
            subscriptions[channel] = WsService.subscribe(channel, listenCount++, true, function () {
                console.log('unsubscribed', channel);
                delete subscriptions[channel];
                listenCount--;
            }).defer.promise;

            var path = $location.path();
            var channels = routeBasedChannels[path];
            if (channels === undefined) {
                routeBasedChannels[path] = channels = [];
            }
            channels.push(channel);
        }
        return subscriptions[channel]
    };

    WsApi.clearSubscriptions = function () {
        WsService.unsubscribeAll();
        listenCount = 0;
    };

    /**
     * @ngdoc method
     * @name  core.service:WsApi#WsApi.fetch
     * @methodOf core.service:WsApi
     * @param {object} apiReq
     *  An apireq which containes the channel, controller and method
     *  which should be listened to.
     * @returns {Promsie} A promise from the WsService send method
     *
     * @description
     *  This method gives a promise which is resolved by id upon
     *  websocket communication on the desired channel
     *
     */
    WsApi.fetch = function (initialReq, manifest) {

        var apiReq = angular.copy(initialReq);

        if (manifest && manifest.pathValues) {
            for (var key in manifest.pathValues) {
                var value = manifest.pathValues[key];
                apiReq.method = apiReq.method.replace(new RegExp(':' + key, 'g'), value);
            }
        }

        if (manifest && manifest.data) {
          apiReq.data = manifest.data;
        }

        if (manifest && manifest.query) {
          apiReq.query = manifest.query;
        }

        if (apiReq.useWebSockets) {
            var request = '/ws/' + apiReq.controller + '/' + apiReq.method;
            var channel = apiReq.endpoint + "/" + apiReq.controller + "/" + apiReq.method;

            var headers = {
                'jwt': sessionStorage.token
            };

            var payload = apiReq.data !== undefined && apiReq.data !== null ? JSON.stringify(apiReq.data) : JSON.stringify({});

            return WsService.send(request, headers, payload, channel);
        }

        var restSend = RestApi.get;

        if(manifest && manifest.method) {
          restSend = RestApi[manifest.method];
        } else {
          restSend = (apiReq.data !== undefined && apiReq.data !== null) ? RestApi.post : restSend;
        }

        return $q(function (resolve, reject) {
            restSend(apiReq).then(function (res) {
                resolve({
                    body: angular.toJson(res)
                });
            });
        });
    };

    return WsApi;

});
<|endoftext|>


<commit_before>var md5 = require( 'md5' );

module.exports = function( redisClient, options ){
    if( !options ){
        options = {};
    }
    var defaultOptions = {
        ttl: options.ttl || 60,
        keyValue: options.keyValue || 'req.authorization.credentials',
        prefix: options.prefix || ''
    };
    function _buildHash( req ){
        var request;
        var string;

        if( req.params.body === Object && Object.keys( req.params.body ).length > 0 ){
            request = req.params.body;
        }
        else{
            request = req.params;
        }

        try{
            string = JSON.stringify( request );
        }
        catch( err ){
            return err;
        }
        return md5( string );
    }

    function _setHash( req, res, next, redisKey ){
        redisClient.set( redisKey, _buildHash( req ), function( err ){
            if( !!err ){
                res.send( 500, { errors: [ 'An internal errors has occurred' ] } );
            }
            redisClient.expire( redisKey, defaultOptions.ttl );
            return next();
        } );
    }

    return {
        findHash: function( req, res, next ){
            if( eval( defaultOptions.keyValue ) ){
                var redisKey = '';
                if( defaultOptions.prefix ){
                    redisKey += defaultOptions.prefix
                }
                redisKey += eval( defaultOptions.keyValue );
            }
            else{
                res.send( 400, { errors: [ 'Cannot pass undefined or null as the key value' ] } );
            }
            redisClient.get( redisKey, function( err, redisRes ){
                if( !!err ){
                    res.send( 500, { errors: [ 'An internal errors has occurred' ] } );
                }
                else if( !redisRes ){
                    _setHash( req, res, next, redisKey );
                }
                else{
                    if( _buildHash( req ) === redisRes ){
                        res.send( 409, { errors: [ 'This is a duplicate' ] } );
                    }
                    else{
                        return next();
                    }
                }
            } );
        }
    }
};<commit_msg>Added flag to ignore empty object<commit_after>var md5 = require( 'md5' );

module.exports = function( redisClient, options ){
    if( !options ){
        options = {};
    }
    var defaultOptions = {
        ttl: options.ttl || 60,
        keyValue: options.keyValue || 'req.authorization.credentials',
        prefix: options.prefix || '',
        ignoreEmptyBody: options.ignoreEmptyBody || true
    };
    function _buildHash( req ){
        var request;
        var string;

        if( req.params.body === Object && Object.keys( req.params.body ).length > 0 ){
            request = req.params.body;
        }
        else{
            request = req.params;
        }

        if( Object.keys( request ).length === 0 && defaultOptions.ignoreEmptyBody ){
            return '';
        }

        try{
            string = JSON.stringify( request );
        }
        catch( err ){
            return err;
        }
        return md5( string );
    }

    function _setHash( req, res, next, redisKey ){
        var hash = _buildHash( req );

        if( !!hash ){
            redisClient.set( redisKey, hash, function( err ){
                if( !!err ){
                    res.send( 500, { errors: [ 'An internal errors has occurred' ] } );
                }
                redisClient.expire( redisKey, defaultOptions.ttl );
                return next();
            } );
        }
        else{
            return next();
        }
    }

    return {
        findHash: function( req, res, next ){
            if( eval( defaultOptions.keyValue ) ){
                var redisKey = '';
                if( defaultOptions.prefix ){
                    redisKey += defaultOptions.prefix
                }
                redisKey += eval( defaultOptions.keyValue );
            }
            else{
                res.send( 400, { errors: [ 'Cannot pass undefined or null as the key value' ] } );
            }
            redisClient.get( redisKey, function( err, redisRes ){
                if( !!err ){
                    res.send( 500, { errors: [ 'An internal errors has occurred' ] } );
                }
                else if( !redisRes ){
                    _setHash( req, res, next, redisKey );
                }
                else{
                    if( _buildHash( req ) === redisRes ){
                        res.send( 409, { errors: [ 'This is a duplicate' ] } );
                    }
                    else{
                        return next();
                    }
                }
            } );
        }
    }
};<|endoftext|>


<commit_before>/**
 * SessionManager.js
 *
 * @author: Harish Anchu <harishanchu@gmail.com>
 * @copyright 2015, Harish Anchu. All rights reserved.
 * @license Licensed under MIT
 */

var FileSessionHandler = require('./handler/FileSessionHandler');
var DatabaseSessionHandler = require('./handler/DatabaseSessionHandler');
var Store = require('./store/Store');
var EncryptedStore = require('./store/EncryptedStore');
var Waterline = require('waterline');
var deasync = require('deasync');
var crypto = require('crypto');

/**
 * Create a session manager instance.
 *
 * @param {Object} config
 * @param {Object} [encrypter]
 *
 * @constructor
 */
function SessionManager(config, encrypter) {
    /**
     * The configuration object
     *
     * @var Object
     * @protected
     */
    this.__config = config;

    /**
     * The registered custom driver creators.
     *
     * @var Object
     * @protected
     */
    this.__customCreators = {};

    /**
     * The encrypter instance.
     * An encrypter implements encrypt and decrypt methods.
     *
     * @var Object
     * @protected
     */
    this.__encrypter = encrypter;

    /**
     * The session database model instance
     *
     * @var Object
     * @protected
     */
    this.__sessionModel;
}

/**
 * Get the default driver name.
 *
 * @return {String}
 */
SessionManager.prototype.getDefaultDriver = function () {
    return this.__config.driver;
};
/**
 * Get a driver instance.
 *
 * @param  {string} driver
 * @return {Object}
 */
SessionManager.prototype.driver = function (driver) {
    driver = driver ? driver : this.getDefaultDriver();

    return this.__createDriver(driver);
};

/**
 * Create a new driver instance.
 *
 * @param  {String} driver
 * @return {*}
 * throws Error if specified given driver creator method doesn't exists.
 * @protected
 */
SessionManager.prototype.__createDriver = function (driver) {
    var method = '__create' + driver.charAt(0).toUpperCase() + driver.slice(1) + 'Driver';

    // We'll check to see if a creator method exists for the given driver. If not we
    // will check for a custom driver creator, which allows developers to create
    // drivers using their own customized driver creator Closure to create it.
    if (this.__customCreators[driver]) {
        return this.__callCustomCreator(driver);
    } else if (typeof this[method] === 'function') {
        return this[method]();
    }

    throw new Error("Driver " + driver + " not supported.");
};

/**
 * Call a custom driver creator.
 *
 * @param  {String} driver
 * @return {*}
 * @protected
 */
SessionManager.prototype.__callCustomCreator = function (driver) {
    return this.__customCreators[driver](this.__config);
};

/**
 * Register a custom driver creator Closure.
 *
 * @param  {String} driver
 * @param  {function} callback
 * @return {SessionManager}
 */
SessionManager.prototype.registerHandler = function(driver, callback) {
    this.__customCreators[driver] = callback;

    return this;
};

/**
 * Create an instance of the file session driver.
 *
 * @return {Object} Session driver instance
 * @protected
 */
SessionManager.prototype.__createFileDriver = function () {
    return this.__createNativeDriver();
};

/**
 * Create an instance of the file session driver.
 *
 * @return {Object} Session driver instance
 * @protected
 */
SessionManager.prototype.__createNativeDriver = function () {
    var path = this.__config.files;

    return this.__buildSession(new FileSessionHandler(path));
};

/**
 * Create an instance of the database session driver.
 *
 * @return {Object} Session driver instance
 * @protected
 */
SessionManager.prototype.__createDatabaseDriver = function () {
    var model = this.__getSessionModel();

    return this.__buildSession(new DatabaseSessionHandler(model));
};

/**
 * Get the database session table model for the database driver.
 *
 * @return {object}
 * @protected
 */
SessionManager.prototype.__getSessionModel = function () {
    if (!this.__sessionModel) {
        this.__sessionModel = this.__createSessionModel();
    }

    return this.__sessionModel;
};

/**
 * Create a waterline session model instance
 *
 * @return {Object  }
 * @protected
 */
SessionManager.prototype.__createSessionModel = function () {
    var self = this;
    var waterlineConnectionName = crypto.randomBytes(5).toString('hex');
    var adapters = {};
    var orm = new Waterline();
    var modelReady = false;
    var SessionModel = Waterline.Collection.extend({
        identity: this.__config.table,
        connection: waterlineConnectionName,
        migrate: 'safe',
        autoCreatedAt: false,
        autoUpdatedAt: false,
        attributes: {
            id: {
                type: 'string',
                unique: true
            },
            payload: 'string',
            lastActivity: 'integer'
        }
    });

    // Load the Models into the ORM
    orm.loadCollection(SessionModel);

    adapters[this.__config.connection.adapter] = require(this.__config.connection.adapter);

    var initConf = {
        adapters: adapters,
        connections:{}
    };
    initConf.connections[waterlineConnectionName] = this.__config.connection;

    orm.initialize(initConf, function (err, models) {
        if (err) {
            throw err;
        }

        SessionModel = models.collections[self.__config.table];
        modelReady = true;
    });

    while (!modelReady) {
        deasync.runLoopOnce();
    }

    return SessionModel;
};

/**
 * Build the session instance.
 *
 * @param  handler
 * @return {Object} Session instance
 */
SessionManager.prototype.__buildSession = function (handler) {
    if (this.__config.encrypt) {
        return new EncryptedStore(
            this.__config.cookie, handler, this.__encrypter, this.__config.secret
        );
    } else {
        return new Store(this.__config.cookie, handler);
    }
};

module.exports = SessionManager;<commit_msg>Use provided table name as collection name in waterline<commit_after>/**
 * SessionManager.js
 *
 * @author: Harish Anchu <harishanchu@gmail.com>
 * @copyright 2015, Harish Anchu. All rights reserved.
 * @license Licensed under MIT
 */

var FileSessionHandler = require('./handler/FileSessionHandler');
var DatabaseSessionHandler = require('./handler/DatabaseSessionHandler');
var Store = require('./store/Store');
var EncryptedStore = require('./store/EncryptedStore');
var Waterline = require('waterline');
var deasync = require('deasync');
var crypto = require('crypto');

/**
 * Create a session manager instance.
 *
 * @param {Object} config
 * @param {Object} [encrypter]
 *
 * @constructor
 */
function SessionManager(config, encrypter) {
    /**
     * The configuration object
     *
     * @var Object
     * @protected
     */
    this.__config = config;

    /**
     * The registered custom driver creators.
     *
     * @var Object
     * @protected
     */
    this.__customCreators = {};

    /**
     * The encrypter instance.
     * An encrypter implements encrypt and decrypt methods.
     *
     * @var Object
     * @protected
     */
    this.__encrypter = encrypter;

    /**
     * The session database model instance
     *
     * @var Object
     * @protected
     */
    this.__sessionModel;
}

/**
 * Get the default driver name.
 *
 * @return {String}
 */
SessionManager.prototype.getDefaultDriver = function () {
    return this.__config.driver;
};
/**
 * Get a driver instance.
 *
 * @param  {string} driver
 * @return {Object}
 */
SessionManager.prototype.driver = function (driver) {
    driver = driver ? driver : this.getDefaultDriver();

    return this.__createDriver(driver);
};

/**
 * Create a new driver instance.
 *
 * @param  {String} driver
 * @return {*}
 * throws Error if specified given driver creator method doesn't exists.
 * @protected
 */
SessionManager.prototype.__createDriver = function (driver) {
    var method = '__create' + driver.charAt(0).toUpperCase() + driver.slice(1) + 'Driver';

    // We'll check to see if a creator method exists for the given driver. If not we
    // will check for a custom driver creator, which allows developers to create
    // drivers using their own customized driver creator Closure to create it.
    if (this.__customCreators[driver]) {
        return this.__callCustomCreator(driver);
    } else if (typeof this[method] === 'function') {
        return this[method]();
    }

    throw new Error("Driver " + driver + " not supported.");
};

/**
 * Call a custom driver creator.
 *
 * @param  {String} driver
 * @return {*}
 * @protected
 */
SessionManager.prototype.__callCustomCreator = function (driver) {
    return this.__customCreators[driver](this.__config);
};

/**
 * Register a custom driver creator Closure.
 *
 * @param  {String} driver
 * @param  {function} callback
 * @return {SessionManager}
 */
SessionManager.prototype.registerHandler = function(driver, callback) {
    this.__customCreators[driver] = callback;

    return this;
};

/**
 * Create an instance of the file session driver.
 *
 * @return {Object} Session driver instance
 * @protected
 */
SessionManager.prototype.__createFileDriver = function () {
    return this.__createNativeDriver();
};

/**
 * Create an instance of the file session driver.
 *
 * @return {Object} Session driver instance
 * @protected
 */
SessionManager.prototype.__createNativeDriver = function () {
    var path = this.__config.files;

    return this.__buildSession(new FileSessionHandler(path));
};

/**
 * Create an instance of the database session driver.
 *
 * @return {Object} Session driver instance
 * @protected
 */
SessionManager.prototype.__createDatabaseDriver = function () {
    var model = this.__getSessionModel();

    return this.__buildSession(new DatabaseSessionHandler(model));
};

/**
 * Get the database session table model for the database driver.
 *
 * @return {object}
 * @protected
 */
SessionManager.prototype.__getSessionModel = function () {
    if (!this.__sessionModel) {
        this.__sessionModel = this.__createSessionModel();
    }

    return this.__sessionModel;
};

/**
 * Create a waterline session model instance
 *
 * @return {Object  }
 * @protected
 */
SessionManager.prototype.__createSessionModel = function () {
    var self = this;
    var adapters = {};
    var orm = new Waterline();
    var modelReady = false;
    var SessionModel = Waterline.Collection.extend({
        identity: this.__config.table,
        connection: this.__config.table,
        migrate: 'safe',
        autoCreatedAt: false,
        autoUpdatedAt: false,
        attributes: {
            id: {
                type: 'string',
                unique: true
            },
            payload: 'string',
            lastActivity: 'integer'
        }
    });

    // Load the Models into the ORM
    orm.loadCollection(SessionModel);

    adapters[this.__config.connection.adapter] = require(this.__config.connection.adapter);

    // Tear down previous session adapter connection with same adapter.
    adapters[this.__config.connection.adapter].teardown(this.__config.table, function(){});

    var initConf = {
        adapters: adapters,
        connections:{}
    };
    initConf.connections[this.__config.table] = this.__config.connection;

    orm.initialize(initConf, function (err, models) {
        if (err) {
            throw err;
        }

        SessionModel = models.collections[self.__config.table];
        modelReady = true;
    });

    while (!modelReady) {
        deasync.runLoopOnce();
    }

    return SessionModel;
};

/**
 * Build the session instance.
 *
 * @param  handler
 * @return {Object} Session instance
 */
SessionManager.prototype.__buildSession = function (handler) {
    if (this.__config.encrypt) {
        return new EncryptedStore(
            this.__config.cookie, handler, this.__encrypter, this.__config.secret
        );
    } else {
        return new Store(this.__config.cookie, handler);
    }
};

module.exports = SessionManager;<|endoftext|>


<commit_before>// Karma configuration
// http://karma-runner.github.io/0.10/config/configuration-file.html

module.exports = function (config) {
    config.set({
        // base path, that will be used to resolve files and exclude
        basePath: '',

        // testing framework to use (jasmine/mocha/qunit/...)
        frameworks: ['jasmine'],

        // list of files / patterns to load in the browser
        files: [
            'src/bower_components/angular/angular.js',
            'src/bower_components/angular-mocks/angular-mocks.js',
            'src/bower_components/angular-sanitize/angular-sanitize.js',
            'src/ya-treeview/*.js',
            'src/ya-treeview/**/*.js',
            'test/mock/**/*.js',
            'test/spec/**/*.js'
        ],

        // list of files / patterns to exclude
        exclude: [],

        // web server port
        port: 8080,

        // level of logging
        // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
        logLevel: config.LOG_INFO,

        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: false,

        // Start these browsers, currently available:
        // - Chrome
        // - ChromeCanary
        // - Firefox
        // - Opera
        // - Safari (only Mac)
        // - PhantomJS
        // - IE (only Windows)
        browsers: ['ChromeCanary'],

        // Continuous Integration mode
        // if true, it capture browsers, run tests and exit
        singleRun: false
    });
};
<commit_msg>changing karma to phantomjs<commit_after>// Karma configuration
// http://karma-runner.github.io/0.10/config/configuration-file.html

module.exports = function (config) {
    config.set({
        // base path, that will be used to resolve files and exclude
        basePath: '',

        // testing framework to use (jasmine/mocha/qunit/...)
        frameworks: ['jasmine'],

        // list of files / patterns to load in the browser
        files: [
            'src/bower_components/angular/angular.js',
            'src/bower_components/angular-mocks/angular-mocks.js',
            'src/bower_components/angular-sanitize/angular-sanitize.js',
            'src/ya-treeview/*.js',
            'src/ya-treeview/**/*.js',
            'test/mock/**/*.js',
            'test/spec/**/*.js'
        ],

        // list of files / patterns to exclude
        exclude: [],

        // web server port
        port: 8080,

        // level of logging
        // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
        logLevel: config.LOG_INFO,

        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: false,

        // Start these browsers, currently available:
        // - Chrome
        // - ChromeCanary
        // - Firefox
        // - Opera
        // - Safari (only Mac)
        // - PhantomJS
        // - IE (only Windows)
        browsers: ['PhantomJS'],

        // Continuous Integration mode
        // if true, it capture browsers, run tests and exit
        singleRun: false
    });
};
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2016 BreizhCamp
 * [http://breizhcamp.org]
 *
 * This file is part of CFP.io.
 *
 * CFP.io is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program 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.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

'use strict';

angular.module('CallForPaper').controller('AdminStatsCtrl', function($scope, $http, currentUser, Rates, Tracks) {

    $scope.currentUser = currentUser;

    Rates.stats().then(function successCallback(stats) {

        var users = [];
        var rated = [];
        Object.keys(stats).forEach(function(key) {
            users.push(key);
            rated.push(stats[key])
        });

        $scope.rates_labels = users;
        $scope.rates_series = ['Rated'];
        $scope.rates_data = [rated];
    });

    Tracks.stats().then(function successCallback(stats) {

        var tracks = [];
        var counts = [];
        Object.keys(stats).forEach(function(key) {
            tracks.push(key);
            counts.push(stats[key])
        });

        $scope.tracks_labels = tracks;
        $scope.tracks_series = ['Tracks'];
        $scope.tracks_data = [counts];
    });

    Tracks.stats('ACCEPTED').then(function successCallback(stats) {

        var tracks = [];
        var counts = [];
        Object.keys(stats).forEach(function(key) {
            tracks.push(key);
            counts.push(stats[key])
        });

        $scope.tracks_data.push(counts);
    });

});
<commit_msg>Fix cfpio/callForPapers#187<commit_after>/*
 * Copyright (c) 2016 BreizhCamp
 * [http://breizhcamp.org]
 *
 * This file is part of CFP.io.
 *
 * CFP.io is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program 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.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

'use strict';

angular.module('CallForPaper').controller('AdminStatsCtrl', function($scope, $http, currentUser, Rates, Tracks) {

    $scope.currentUser = currentUser;

    Rates.stats().then(function successCallback(stats) {

        var users = [];
        var rated = [];
        Object.keys(stats).forEach(function(key) {
            users.push(key);
            rated.push(stats[key])
        });

        $scope.rates_labels = users;
        $scope.rates_series = ['Rated'];
        $scope.rates_data = [rated];
    });

    Tracks.stats().then(function successCallback(stats) {

        var tracks = [];
        var counts = [];
        Object.keys(stats).forEach(function(key) {
            tracks.push(key);
            counts.push(stats[key])
        });

        $scope.tracks_labels = tracks;
        $scope.tracks_series = ['Tracks'];
        $scope.tracks_all_data = [counts];
    }).then(function() {
        return Tracks.stats("ACCEPTED");
    }).then(function successCallback(stats) {

            var tracks = [];
            var counts = [];
            Object.keys(stats).forEach(function(key) {
                tracks.push(key);
                counts.push(stats[key])
            });

            $scope.tracks_data = [];
            $scope.tracks_data.push($scope.tracks_all_data);
            $scope.tracks_data.push(counts);
      });

});
<|endoftext|>


<commit_before>// initializes the application and links it with the GUI

// require core modules
// const nodeInfo = require('./src/core/nodeInfo.js')
const printTotalNodes = require('./core/printTotalNodes.js')
const hoverNodeInfo = require('./core/hoverNodeInfo.js')
const editMenu = require('./core/editMenu.js')
const editEdge = require('./core/editEdge.js')

// require helper functions
const rmElement = require('./helpers/rmElement.js')
// require buttons and keybindings
const buttons = require('./buttons.js')
const keybindings = require('./keybindings.js')

module.exports = function initialize (cy, phase) {
  // initial label render
  cy.nodes().addClass('label-nodes')
  cy.edges().addClass('label-edges')

  // global variables, used in cy.on
  let selectedNode = {}
  let oldSelectedNode = {}
  let selectedEdge = {}
  let srcNode = {}
  let trgNode = {}
  // initialize export variables to prevent undefined errors
  selectedNode.out = {}
  oldSelectedNode.out = {}
  selectedEdge.out = {}
  srcNode.out = {}
  trgNode.out = {}

  // stores the initial state of the nodes in the graph
  const graphNodes = cy.nodes()
  // counter variable to create unique sequential node ids in addComponents.js
  const initialCount = cy.nodes().length

  // cy.on performs actions on intrection with the graph
  // actions when tapping on node
  cy.on('tap', 'node', selection => {
    // removes previous selections classes
    cy.elements().removeClass('selection')
    cy.elements().removeClass('attention')
    cy.elements().removeClass('protect')
    cy.nodes().removeClass('old-selection')

    oldSelectedNode.out = selectedNode.out
    selectedNode.out = selection.target[0]
    selectedNode.out.addClass('selection')

    // adds the old-selection class to the previous selection
    if (Object.keys(oldSelectedNode.out).length !== 0) {
      oldSelectedNode.out.addClass('old-selection')
    }

    srcNode.out = trgNode.out // second selection
    trgNode.out = selectedNode.out.data() // first selection

    selectedEdge.out = {} // clear token

    printTotalNodes(cy) // show number of nodes

    rmElement('message-area-id', 'form-id') // remove the edit node element
    rmElement('window-id', 'nodeMenu-id') // remove node menu element
    rmElement('window-id', 'stageMenu-id') // remove stage menu element
  })
  // actions when tapping on an edge
  cy.on('tap', 'edge', selection => {
    // removes previous selections
    cy.elements().removeClass('selection')
    cy.elements().removeClass('attention')
    cy.elements().removeClass('protect')
    cy.nodes().removeClass('old-selection')
    selection.target.addClass('selection')

    // clear tokens
    selectedNode.out = {}
    oldSelectedNode.out = {}

    selectedEdge.out = selection.target[0]

    printTotalNodes(cy) // show number of nodes

    rmElement('message-area-id', 'form-id') // remove the edit node element
    rmElement('window-id', 'nodeMenu-id') // remove node menu element
    rmElement('window-id', 'stageMenu-id') // remove stage menu element
  })
  // actions when tapping the stage
  cy.on('tap', selection => {
    // checks if only the stage was clicked
    if (selection.target === cy) {
      // removes previous selections
      cy.elements().removeClass('faded')
      cy.elements().removeClass('selection')
      cy.elements().removeClass('attention')
      cy.elements().removeClass('protect')
      cy.nodes().removeClass('old-selection')

      // clear tokens
      selectedNode.out = {}
      oldSelectedNode.out = {}
      selectedEdge.out = {}

      printTotalNodes(cy) // show nubmer of nodes

      rmElement('message-area-id', 'form-id') // remove the edit node element
      rmElement('window-id', 'nodeMenu-id') // remove node menu element
      rmElement('window-id', 'stageMenu-id') // remove stage menu element
    }
  })
  // right clicking on node
  cy.on('cxttap', 'node', selection => {
    selectedNode.out = selection.target[0]
    editMenu.nodeMenu(cy, selection, selectedNode.out)

    // clear tokens
    selectedNode.out = {}
    oldSelectedNode.out = {}
    selectedEdge.out = {}

    rmElement('window-id', 'stageMenu-id') // remove stage menu element
  })
  // right click on edge to edit
  // only available in state diagrams
  if (phase === 'state') {
    cy.on('cxttap', 'edge', selection => {
      editEdge.formEdge(selection.target[0])
    })
  }
  // right clicking on stage
  cy.on('cxttap', selection => {
    // checks if only the stage was clicked
    if (selection.target === cy) {
      // removes the stage menu if it exists
      rmElement('window-id', 'stageMenu-id')
      editMenu.stageMenu(cy, selection)
    }
  })
  // actions when hovering over a node
  cy.on('mouseover', 'node', event => {
    hoverNodeInfo(event.target[0]) // global module
  })
  // actions when hovering out of a node
  cy.on('mouseout', 'node', event => {
    // hides the hover container
    document.getElementById('container-node-id').style.display = 'none'
  })

  // load the buttons for each phase

  // declaration of global buttons
  buttons(
    cy,
    selectedNode,
    selectedEdge,
    srcNode,
    trgNode,
    initialCount,
    phase,
    graphNodes
  )
  // enable keybindings
  keybindings(
    cy,
    selectedNode,
    selectedEdge,
    srcNode,
    trgNode,
    phase,
    graphNodes
  )
  printTotalNodes(cy) // initial node count
}
<commit_msg>:bug: fix node counter bug<commit_after>// initializes the application and links it with the GUI

// require core modules
// const nodeInfo = require('./src/core/nodeInfo.js')
const printTotalNodes = require('./core/printTotalNodes.js')
const hoverNodeInfo = require('./core/hoverNodeInfo.js')
const editMenu = require('./core/editMenu.js')
const editEdge = require('./core/editEdge.js')

// require helper functions
const rmElement = require('./helpers/rmElement.js')
// require buttons and keybindings
const buttons = require('./buttons.js')
const keybindings = require('./keybindings.js')

module.exports = function initialize (cy, phase) {
  // initial label render
  cy.nodes().addClass('label-nodes')
  cy.edges().addClass('label-edges')

  // global variables, used in cy.on
  let selectedNode = {}
  let oldSelectedNode = {}
  let selectedEdge = {}
  let srcNode = {}
  let trgNode = {}
  // initialize export variables to prevent undefined errors
  selectedNode.out = {}
  oldSelectedNode.out = {}
  selectedEdge.out = {}
  srcNode.out = {}
  trgNode.out = {}

  // stores the initial state of the nodes in the graph
  const graphNodes = cy.nodes()
  // counter variable to create unique sequential node ids in addComponents.js
  let nodeCounter = ''
  cy.nodes().map(node => {
    nodeCounter = node.data().id
  })

  // cy.on performs actions on intrection with the graph
  // actions when tapping on node
  cy.on('tap', 'node', selection => {
    // removes previous selections classes
    cy.elements().removeClass('selection')
    cy.elements().removeClass('attention')
    cy.elements().removeClass('protect')
    cy.nodes().removeClass('old-selection')

    oldSelectedNode.out = selectedNode.out
    selectedNode.out = selection.target[0]
    selectedNode.out.addClass('selection')

    // adds the old-selection class to the previous selection
    if (Object.keys(oldSelectedNode.out).length !== 0) {
      oldSelectedNode.out.addClass('old-selection')
    }

    srcNode.out = trgNode.out // second selection
    trgNode.out = selectedNode.out.data() // first selection

    selectedEdge.out = {} // clear token

    printTotalNodes(cy) // show number of nodes

    rmElement('message-area-id', 'form-id') // remove the edit node element
    rmElement('window-id', 'nodeMenu-id') // remove node menu element
    rmElement('window-id', 'stageMenu-id') // remove stage menu element
  })
  // actions when tapping on an edge
  cy.on('tap', 'edge', selection => {
    // removes previous selections
    cy.elements().removeClass('selection')
    cy.elements().removeClass('attention')
    cy.elements().removeClass('protect')
    cy.nodes().removeClass('old-selection')
    selection.target.addClass('selection')

    // clear tokens
    selectedNode.out = {}
    oldSelectedNode.out = {}

    selectedEdge.out = selection.target[0]

    printTotalNodes(cy) // show number of nodes

    rmElement('message-area-id', 'form-id') // remove the edit node element
    rmElement('window-id', 'nodeMenu-id') // remove node menu element
    rmElement('window-id', 'stageMenu-id') // remove stage menu element
  })
  // actions when tapping the stage
  cy.on('tap', selection => {
    // checks if only the stage was clicked
    if (selection.target === cy) {
      // removes previous selections
      cy.elements().removeClass('faded')
      cy.elements().removeClass('selection')
      cy.elements().removeClass('attention')
      cy.elements().removeClass('protect')
      cy.nodes().removeClass('old-selection')

      // clear tokens
      selectedNode.out = {}
      oldSelectedNode.out = {}
      selectedEdge.out = {}

      printTotalNodes(cy) // show nubmer of nodes

      rmElement('message-area-id', 'form-id') // remove the edit node element
      rmElement('window-id', 'nodeMenu-id') // remove node menu element
      rmElement('window-id', 'stageMenu-id') // remove stage menu element
    }
  })
  // right clicking on node
  cy.on('cxttap', 'node', selection => {
    selectedNode.out = selection.target[0]
    editMenu.nodeMenu(cy, selection, selectedNode.out)

    // clear tokens
    selectedNode.out = {}
    oldSelectedNode.out = {}
    selectedEdge.out = {}

    rmElement('window-id', 'stageMenu-id') // remove stage menu element
  })
  // right click on edge to edit
  // only available in state diagrams
  if (phase === 'state') {
    cy.on('cxttap', 'edge', selection => {
      editEdge.formEdge(selection.target[0])
    })
  }
  // right clicking on stage
  cy.on('cxttap', selection => {
    // checks if only the stage was clicked
    if (selection.target === cy) {
      // removes the stage menu if it exists
      rmElement('window-id', 'stageMenu-id')
      editMenu.stageMenu(cy, selection)
    }
  })
  // actions when hovering over a node
  cy.on('mouseover', 'node', event => {
    hoverNodeInfo(event.target[0]) // global module
  })
  // actions when hovering out of a node
  cy.on('mouseout', 'node', event => {
    // hides the hover container
    document.getElementById('container-node-id').style.display = 'none'
  })

  // load the buttons for each phase

  // declaration of global buttons
  buttons(
    cy,
    selectedNode,
    selectedEdge,
    srcNode,
    trgNode,
    nodeCounter,
    phase,
    graphNodes
  )
  // enable keybindings
  keybindings(
    cy,
    selectedNode,
    selectedEdge,
    srcNode,
    trgNode,
    phase,
    graphNodes
  )
  printTotalNodes(cy) // initial node count
}
<|endoftext|>


<commit_before>/**
 * Created by Ralph Varjabedian.
 * nodetastic is licensed under the [BSD-3 License] https://raw.githubusercontent.com/ralphv/nodetastic/master/LICENSE.
 * do not remove this notice.
 */

// in order to provide abstraction for session access and to allow the flexibility of changing the session modification
// any code using this layer should work with the req.$session instead with the req.session object directly
// this will ensure proper abstraction.

//<editor-fold defaultstate="collapsed" desc="ExpressSessionHandler">
function ExpressSessionHandler(session) {
  this.session = session;
}
ExpressSessionHandler.prototype = {
  get: function(key) {
    return this.session[key];
  },
  has: function(key) {
    return this.session && this.session.hasOwnProperty(key);
  },
  del: function(key) {
    delete this.session[key];
  },
  set: function(key, value) {
    this.session[key] = value;
  },
  getId: function() {
    return (this.session && this.session.id) ? this.session.id : null;
  },
  destroy: function(cb) {
    this.session.destroy(cb);
    this.session = null;
  },
  isValid: function() {
    return !!this.session;
  },
  persistNow: function(cb) {
    if (this.session.save) {
      this.session.save();
    }
    if (cb) {
      cb();
    }
  },
  getCoreSession: function() {
    return this.session;
  }
};
//</editor-fold>

function SessionWrapper(req) {
  this.req = req;
  this.store = new ExpressSessionHandler(this.req.session);
}

SessionWrapper.prototype = {
  get: function(key) {
    return this.store.get(key);
  },
  has: function(key) {
    return this.store.has(key);
  },
  del: function(key) {
    return this.store.del(key);
  },
  set: function(key, value) {
    return this.store.set(key, value);
  },
  getId: function() {
    return this.store.getId();
  },
  destroy: function(cb) {
    return this.store.destroy(cb);
  },
  isValid: function() {
    return this.store.isValid();
  },
  persistNow: function(cb) {
    return this.store.persistNow(cb);
  },
  getCoreSession: function() {
    return this.store.getCoreSession();
  }
};

module.exports = SessionWrapper;<commit_msg>1.0.4<commit_after>/**
 * Created by Ralph Varjabedian.
 * nodetastic is licensed under the [BSD-3 License] https://raw.githubusercontent.com/ralphv/nodetastic/master/LICENSE.
 * do not remove this notice.
 */

// in order to provide abstraction for session access and to allow the flexibility of changing the session modification
// any code using this layer should work with the req.$session instead with the req.session object directly
// this will ensure proper abstraction.

//<editor-fold defaultstate="collapsed" desc="ExpressSessionHandler">
function ExpressSessionHandler(session) {
  this.session = session;
}
ExpressSessionHandler.prototype = {
  get: function(key) {
    return this.session && this.session[key];
  },
  has: function(key) {
    return this.session && this.session.hasOwnProperty(key);
  },
  del: function(key) {
    if (this.session) {
      delete this.session[key];
    }
  },
  set: function(key, value) {
    if (this.session) {
      this.session[key] = value;
    }
  },
  getId: function() {
    return (this.session && this.session.id) ? this.session.id : null;
  },
  destroy: function(cb) {
    if (this.session) {
      this.session.destroy(cb);
      this.session = null;
    }
  },
  isValid: function() {
    return !!this.session;
  },
  persistNow: function(cb) {
    if (this.session && this.session.save) {
      this.session.save();
    }
    if (cb) {
      cb();
    }
  },
  getCoreSession: function() {
    return this.session;
  }
};
//</editor-fold>

function SessionWrapper(req) {
  this.req = req;
  this.store = new ExpressSessionHandler(this.req.session);
}

SessionWrapper.prototype = {
  get: function(key) {
    return this.store.get(key);
  },
  has: function(key) {
    return this.store.has(key);
  },
  del: function(key) {
    return this.store.del(key);
  },
  set: function(key, value) {
    return this.store.set(key, value);
  },
  getId: function() {
    return this.store.getId();
  },
  destroy: function(cb) {
    return this.store.destroy(cb);
  },
  isValid: function() {
    return this.store.isValid();
  },
  persistNow: function(cb) {
    return this.store.persistNow(cb);
  },
  getCoreSession: function() {
    return this.store.getCoreSession();
  }
};

module.exports = SessionWrapper;<|endoftext|>


<commit_before>module.exports = function (config) {
    config.set({
        basePath: 'nextcloudappstore/core/static/',
        frameworks: ['jasmine'],
        mime: { 'text/x-typescript': ['ts','tsx'] },
        files: [
            {pattern: 'assets/app/**/*Spec.ts', watched: false}
        ],
        exclude: [],
        preprocessors: {
            'assets/app/**/*.ts': ['webpack']
        },
        webpackMiddleware: {
            noInfo: true,
            stats: {
                chunks: false,
                colors: true
            }
        },
        webpack: {
            resolve: {
                extensions: ['.js', '.ts', '.tsx']
            },
            module: {
                loaders: [
                    {test: /\.tsx?$/, loader: 'ts-loader'}
                ]
            },
            stats: {
                colors: true,
                modules: true,
                reasons: true,
                errorDetails: true
            },
            devtool: 'inline-source-map',
        },
        reporters: ['progress'],
        port: 9876,
        colors: true,
        logLevel: config.LOG_INFO,
        autoWatch: true,
        browsers: ['Firefox'],
        singleRun: false,
        concurrency: Infinity,
    })
};
<commit_msg>fix js tests<commit_after>module.exports = function (config) {
    config.set({
        basePath: 'nextcloudappstore/core/static/',
        frameworks: ['jasmine'],
        mime: { 'text/x-typescript': ['ts','tsx'] },
        files: [
            {pattern: 'assets/app/**/*Spec.ts', watched: false}
        ],
        exclude: [],
        preprocessors: {
            'assets/app/**/*.ts': ['webpack']
        },
        webpackMiddleware: {
            noInfo: true,
            stats: {
                chunks: false,
                colors: true
            }
        },
        webpack: {
            resolve: {
                extensions: ['.js', '.ts', '.tsx']
            },
            module: {
                rules: [
                    {
                        test: /\.tsx?$/,
                        loader: 'ts-loader'
                    }
                ]
            },
            stats: {
                colors: true,
                modules: true,
                reasons: true,
                errorDetails: true
            },
            devtool: 'inline-source-map',
            mode: 'production'
        },
        reporters: ['progress'],
        port: 9876,
        colors: true,
        logLevel: config.LOG_INFO,
        autoWatch: true,
        browsers: ['Firefox'],
        singleRun: false,
        concurrency: Infinity,
    })
};
<|endoftext|>


<commit_before>/*
KEYSHANC: KEYboard SHA-based eNCrypter
Javascript Implementation

Copyright (c) 2012 Andrew C. Reed

License: The MIT License
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

//NOTE: This script requires sha512-min.js and sha256-min.js
//Both can be obtained from http://pajhome.org.uk/crypt/md5/jshash-2.2.zip

//create keys[95]
var keys = new Array(95);

//initialize keys[95]
for (x = 0; x < 95; x++) {
    keys[x] = (x + 32);
}

function keyshanc(password) {
    var i = new String(hex_sha512(password));
    var j = new String(hex_sha256(password));

    //this loop resets keys[95] prior to shuffling
    for (x = 0; x < 95; x++) {
        keys[x] = (x + 32);
    }

    //exit function if no password provided
    //this effectively turns Keyshanc OFF
    if (password.length == 0) {
        return;
    }

    var shuffleCode = new Array(95);
    var hexString = new String("");
    var numByte;

    //build the first 64 positions in shuffleCode[] with the entire SHA512 hash
    for (x = 0; x < 64; x++) {
        hexString = hexString.concat(i.charAt(x*2));
        hexString = hexString.concat(i.charAt((x*2)+1));
        numByte = parseInt(hexString, 16);
        shuffleCode[x] = numByte%95;
        hexString = "";
    }

    //build the last 31 positions in shuffleCode[] with the first 31 bytes of the SHA256 hash
    for (x = 0; x < 31; x++) {
        hexString = hexString.concat(j.charAt(x*2));
        hexString = hexString.concat(j.charAt((x*2)+1));
        numByte = parseInt(hexString, 16);
        shuffleCode[x+64] = numByte%95;
        hexString = "";
    }

    //shuffle keys[] using shuffleCode[] for swap positions
    for (x = 0; x < 95; x++) {
        var temp = keys[x];
        keys[x] = keys[shuffleCode[x]];
        keys[shuffleCode[x]] = temp;
    }
}

function decryptKeyshanc() {
    s1 = new String(document.getElementById('inText').value);

    var s2 = new String("");

    for (x = 0; x < s1.length; x++) {
        if (s1.charCodeAt(x) >= 32 && s1.charCodeAt(x) <= 126)
        {
            for (y = 0; y < 95; y++) {
                if (s1.charAt(x) == String.fromCharCode(keys[y]))
                {
                    s2 = s2.concat(String.fromCharCode(y+32));
                    break;
                }
            }
        }
        else
        {
            s2 = s2.concat(s1.charAt(x));
        }
    }

    document.getElementById('outText').value = s2;
}
<commit_msg>Added code to generate a dynamic Tweet button.<commit_after>/*
KEYSHANC: KEYboard SHA-based eNCrypter
Javascript Implementation

Copyright (c) 2012 Andrew C. Reed

License: The MIT License
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

//NOTE: This script requires sha512-min.js and sha256-min.js
//Both can be obtained from http://pajhome.org.uk/crypt/md5/jshash-2.2.zip

//ALSO: The dynamicTweet/generateTweet portions require jQuery
//Available from http://jquery.com

//create keys[95]
var keys = new Array(95);

//initialize keys[95]
for (x = 0; x < 95; x++) {
    keys[x] = (x + 32);
}

//jQuery code for the Dynamic Tweet button which sends the ciphertext
//    Place the following DIV in your html where you want the Dynamic Tweet
//    button to appear
//

$('#dynamicTweet').html('');

function keyshanc(password) {
    var i = new String(hex_sha512(password));
    var j = new String(hex_sha256(password));

    //this loop resets keys[95] prior to shuffling
    for (x = 0; x < 95; x++) {
        keys[x] = (x + 32);
    }

    //exit function if no password provided
    //this effectively turns Keyshanc OFF
    if (password.length == 0) {
        return;
    }

    var shuffleCode = new Array(95);
    var hexString = new String("");
    var numByte;

    //build the first 64 positions in shuffleCode[] with the entire SHA512 hash
    for (x = 0; x < 64; x++) {
        hexString = hexString.concat(i.charAt(x*2));
        hexString = hexString.concat(i.charAt((x*2)+1));
        numByte = parseInt(hexString, 16);
        shuffleCode[x] = numByte%95;
        hexString = "";
    }

    //build the last 31 positions in shuffleCode[] with the first 31 bytes of the SHA256 hash
    for (x = 0; x < 31; x++) {
        hexString = hexString.concat(j.charAt(x*2));
        hexString = hexString.concat(j.charAt((x*2)+1));
        numByte = parseInt(hexString, 16);
        shuffleCode[x+64] = numByte%95;
        hexString = "";
    }

    //shuffle keys[] using shuffleCode[] for swap positions
    for (x = 0; x < 95; x++) {
        var temp = keys[x];
        keys[x] = keys[shuffleCode[x]];
        keys[shuffleCode[x]] = temp;
    }
}

function decryptKeyshanc() {
    s1 = new String(document.getElementById('inText').value);

    var s2 = new String("");

    for (x = 0; x < s1.length; x++) {
        if (s1.charCodeAt(x) >= 32 && s1.charCodeAt(x) <= 126)
        {
            for (y = 0; y < 95; y++) {
                if (s1.charAt(x) == String.fromCharCode(keys[y]))
                {
                    s2 = s2.concat(String.fromCharCode(y+32));
                    break;
                }
            }
        }
        else
        {
            s2 = s2.concat(s1.charAt(x));
        }
    }

    document.getElementById('outText').value = s2;
}

function encryptKeyshanc() {
    s1 = new String(document.getElementById('inText').value);

    var s2 = new String("");

    for (x = 0; x < s1.length; x++) {
        if (s1.charCodeAt(x) >= 32 && s1.charCodeAt(x) <= 126)
        {
            s2 = s2.concat(String.fromCharCode(keys[((s1.charCodeAt(x))-32)]));
        }
        else
        {
            s2 = s2.concat(s1.charAt(x));
        }
    }

    document.getElementById('outText').value = s2;
}

function generateTweet(tweetText) {
    $('#dynamicTweet').html("\
\

");
}
<|endoftext|>


<commit_before>/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

/*
 * Copyright (c) 2014, Joyent, Inc.
 */

var fs = require('fs');
var util = require('util');
var path = require('path');
var verror = require('verror');
var restify = require('restify');
var assert = require('assert-plus');

var allocator = require('./allocator');
var boot_params = require('./boot_params');
var fw = require('./fw');
var ModelImage = require('../models/image');
var ModelServer = require('../models/server');
var images = require('./images');
var nics = require('./nics');
var platforms = require('./platforms');
var servers = require('./servers');
var waitlist = require('./waitlist');
var tasks = require('./tasks');
var ur = require('./ur');
var vms = require('./vms');
var zfs = require('./zfs');

var CONNECTION_CHECKS = {
    transport: ensureConnectedToTransport,
    moray: ensureConnectedToMoray,
    amqp: ensureConnectedToAMQP,
    workflow: ensureConnectedToWorkflow
};

var PREPOPULATE_FNS = {
    server: prepopulateServer,
    vm: prepopulateVm,
    image: prepopulateImage
};

function ensureConnectedToMoray(opts, req, res, next) {
    if (!opts.app.moray.connected) {
        next(new restify.InternalError(
            'Precondition failed: no connection moray'));
        return;
    }
    next();
}

function ensureConnectedToAMQP(opts, req, res, next) {
    if (!opts.app.amqpConnection.connected) {
        next(new restify.InternalError(
            'Precondition failed: no connection to AMQP'));
        return;
    }
    next();
}

function ensureConnectedToTransport(opts, req, res, next) {
    // if transport is AMQP this will ensure it's connected
    var transport = req.stash.server.getValue().transport;
    if (transport === 'amqp') {
        ensureConnectedToAMQP(opts, req, res, next);
        return;
    }
    next();
}

function ensureConnectedToWorkflow(opts, req, res, next) {
    if (!opts.app.workflow.connected) {
        next(new restify.InternalError(
            'Precondition failed: no connection to Workflow API'));
        return;
    }
    next();
}

function ensureConnectionTimeout(opts, req, res, next) {
    req.connection.setTimeout(opts.connectionTimeoutSeconds * 1000);
    next();
}

function prepopulateServer(opts, req, res, next) {
    assert.string(req.params.server_uuid, 'server_uuid');

    ModelServer.get(
        req.params.server_uuid,
        function (err, servermodel, server) {
            if (err) {
                req.log.error(err);
                next(new restify.InternalError(err.message));
                return;
            }

            // Check if any servers were returned
            if (!server) {
                var errorMsg = 'Server ' + req.params.server_uuid
                    + ' not found';
                next(new restify.ResourceNotFoundError(errorMsg));
                return;
            }
            req.stash.server = servermodel;
            next();
        });
}

function prepopulateVm(opts, req, res, next) {
    assert.string(req.params.uuid, 'uuid');

    var uuid = req.params.uuid;

    req.stash.server.getRaw(function (error, server) {
        if (error) {
            req.log.error(error);
            next(new restify.InternalError(error.message));
            return;
        }

        // Check if any servers were returned
        if (!server) {
            var errorMsg = 'Server ' + req.params.server_uuid + ' not found';
            next(new restify.ResourceNotFoundError(errorMsg));
            return;
        }

        if (!server.vms || !server.vms[uuid]) {
            errorMsg = 'VM ' + uuid + ' not found';
            next(new restify.ResourceNotFoundError(errorMsg));
            return;
        }

        req.stash.vm = req.stash.server.getVM(uuid);
        next();
    });
}

function prepopulateImage(opts, req, res, next) {
    assert.string(req.params.server_uuid, 'server_uuid');
    req.stash.image = new ModelImage({
        serverUuid: req.params.server_uuid,
        uuid: req.params.uuid
    });
    next();
}

function ensure(opts) {
    var fns = [];

    opts.log = opts.app.getLog();
    opts.connectionTimeoutSeconds = opts.connectionTimeoutSeconds || 60 * 60;

    // Override timeout
    fns.push(function (req, res, next) {
        if (!req.stash) {
            req.stash = {};
            req.stash.app = opts.app;
        }
        next();
    });

    fns.push(function (req, res, next) {
        ensureConnectionTimeout(opts, req, res, next);
    });

    var connected = opts.connected || [];
    var prepopulate = opts.prepopulate || [];

    // If we're checking moray, do it first.
    var idx = connected.indexOf('moray');
    if (idx !== -1) {
        fns.push(function (req, res, next) {
            CONNECTION_CHECKS['moray'](opts, req, res, next);
        });
        connected.splice(idx, 1);
    }

    prepopulate.forEach(function (resource) {
        if (!PREPOPULATE_FNS.hasOwnProperty(resource)) {
            throw (
                new verror.VError(
                    'unknown resource for prepopulation, %s', resource));
        }

        fns.push(function (req, res, next) {
            PREPOPULATE_FNS[resource](opts, req, res, next);
        });
    });

    connected.forEach(function (service) {
        if (!CONNECTION_CHECKS.hasOwnProperty(service)) {
            throw (
                new verror.VError(
                    'unknown service for precondition check, %s', service));
        }

        fns.push(function (req, res, next) {
            CONNECTION_CHECKS[service](opts, req, res, next);
        });
    });

    return fns;
}

/**
 * Return CNAPI's service status details.
 *
 * @name Ping
 * @endpoint GET /ping
 * @section Miscellaneous API
 *
 * @example GET /ping
 *
 * @response 200 Object Status details.
 */

function ping(app, req, res, next) {
    var services = {
        workflow:
            (app.workflow.client &&
             app.workflow.connected) ? 'online' : 'offline',
        moray:
            (app.moray._morayClient &&
             app.moray.connected) ? 'online' : 'offline',
        amqp:
            (app.amqpConnection &&
             app.amqpConnection.connected) ? 'online' : 'offline'
    };
    res.send(200, {
        ready:
            services.workflow === 'online' &&
            services.moray === 'online' &&
            services.amqp === 'online',
        services: services
    });
    next();
}

function attachTo(http, app) {
    http.post(
        '/loglevel',
        function (req, res, next) {
            var level = req.params.level;
            app.getLog().debug('Setting loglevel to %s', level);
            app.getLog().level(level);
            res.send();
            return next();
        });

    http.get(
        '/loglevel',
        function (req, res, next) {
            res.send({ level: app.getLog().level() });
            return next();
        });

    http.get({path: '/ping', name: 'Ping'}, function (req, res, next) {
        ping(app, req, res, next);
    });

    http.get('/info', function (req, res, next) {
        var info = {};

        fs.readFile(path.join(__dirname, '..', '..', 'package.json'),
        function (error, data) {
            if (error) {
                next(new restify.InternalError(error.message));
                return;
            }
            var pkg = JSON.parse(data.toString());
            info.version = pkg.version;

            res.send(info);
            next();
        });
    });

    http.get('/diagnostics', function (req, res, next) {
        var send = {
            start_timestamp: app.start_timestamp,
            memory: process.memoryUsage()
        };

        var taskCallbacks = {};

        Object.keys(app.taskCallbacks).forEach(function (taskid) {
            taskCallbacks[taskid] = app.taskCallbacks[taskid].map(function (i) {
                return { id: i.id }; });
        });

        send.taskCallbacks = taskCallbacks;
        send.agent_handles_length = 0;
        send.agent_handles = [];

        var tks = app.getTaskClient();

        for (var uuid in tks.agentHandles) {
            send.agent_handles_length++;

            send.agent_handles.push({
                uuid: uuid,
                task_handles_length:
                    Object.keys(
                        tks.agentHandles[uuid].taskHandles).length,
                task_handles_uuid:
                    Object.keys(tks.agentHandles[uuid].taskHandles)
            });
        }

        res.send(send);
    });

    fw.attachTo(http, app);
    images.attachTo(http, app);
    nics.attachTo(http, app);
    platforms.attachTo(http, app);
    servers.attachTo(http, app);
    waitlist.attachTo(http, app);
    vms.attachTo(http, app);
    tasks.attachTo(http, app);
    allocator.attachTo(http, app);
    boot_params.attachTo(http, app);
    ur.attachTo(http, app);
    zfs.attachTo(http, app);
}

exports.attachTo = attachTo;
exports.ensure = ensure;
<commit_msg>CNAPI-586: do not check for VM before attempting action<commit_after>/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

/*
 * Copyright (c) 2014, Joyent, Inc.
 */

var fs = require('fs');
var util = require('util');
var path = require('path');
var verror = require('verror');
var restify = require('restify');
var assert = require('assert-plus');

var allocator = require('./allocator');
var boot_params = require('./boot_params');
var fw = require('./fw');
var ModelImage = require('../models/image');
var ModelServer = require('../models/server');
var images = require('./images');
var nics = require('./nics');
var platforms = require('./platforms');
var servers = require('./servers');
var waitlist = require('./waitlist');
var tasks = require('./tasks');
var ur = require('./ur');
var vms = require('./vms');
var zfs = require('./zfs');

var CONNECTION_CHECKS = {
    transport: ensureConnectedToTransport,
    moray: ensureConnectedToMoray,
    amqp: ensureConnectedToAMQP,
    workflow: ensureConnectedToWorkflow
};

var PREPOPULATE_FNS = {
    server: prepopulateServer,
    vm: prepopulateVm,
    image: prepopulateImage
};

function ensureConnectedToMoray(opts, req, res, next) {
    if (!opts.app.moray.connected) {
        next(new restify.InternalError(
            'Precondition failed: no connection moray'));
        return;
    }
    next();
}

function ensureConnectedToAMQP(opts, req, res, next) {
    if (!opts.app.amqpConnection.connected) {
        next(new restify.InternalError(
            'Precondition failed: no connection to AMQP'));
        return;
    }
    next();
}

function ensureConnectedToTransport(opts, req, res, next) {
    // if transport is AMQP this will ensure it's connected
    var transport = req.stash.server.getValue().transport;
    if (transport === 'amqp') {
        ensureConnectedToAMQP(opts, req, res, next);
        return;
    }
    next();
}

function ensureConnectedToWorkflow(opts, req, res, next) {
    if (!opts.app.workflow.connected) {
        next(new restify.InternalError(
            'Precondition failed: no connection to Workflow API'));
        return;
    }
    next();
}

function ensureConnectionTimeout(opts, req, res, next) {
    req.connection.setTimeout(opts.connectionTimeoutSeconds * 1000);
    next();
}

function prepopulateServer(opts, req, res, next) {
    assert.string(req.params.server_uuid, 'server_uuid');

    ModelServer.get(
        req.params.server_uuid,
        function (err, servermodel, server) {
            if (err) {
                req.log.error(err);
                next(new restify.InternalError(err.message));
                return;
            }

            // Check if any servers were returned
            if (!server) {
                var errorMsg = 'Server ' + req.params.server_uuid
                    + ' not found';
                next(new restify.ResourceNotFoundError(errorMsg));
                return;
            }
            req.stash.server = servermodel;
            next();
        });
}

function prepopulateVm(opts, req, res, next) {
    assert.string(req.params.uuid, 'uuid');

    var uuid = req.params.uuid;

    req.stash.server.getRaw(function (error, server) {
        if (error) {
            req.log.error(error);
            next(new restify.InternalError(error.message));
            return;
        }

        // Check if any servers were returned
        if (!server) {
            var errorMsg = 'Server ' + req.params.server_uuid + ' not found';
            next(new restify.ResourceNotFoundError(errorMsg));
            return;
        }

        req.stash.vm = req.stash.server.getVM(uuid);
        next();
    });
}

function prepopulateImage(opts, req, res, next) {
    assert.string(req.params.server_uuid, 'server_uuid');
    req.stash.image = new ModelImage({
        serverUuid: req.params.server_uuid,
        uuid: req.params.uuid
    });
    next();
}

function ensure(opts) {
    var fns = [];

    opts.log = opts.app.getLog();
    opts.connectionTimeoutSeconds = opts.connectionTimeoutSeconds || 60 * 60;

    // Override timeout
    fns.push(function (req, res, next) {
        if (!req.stash) {
            req.stash = {};
            req.stash.app = opts.app;
        }
        next();
    });

    fns.push(function (req, res, next) {
        ensureConnectionTimeout(opts, req, res, next);
    });

    var connected = opts.connected || [];
    var prepopulate = opts.prepopulate || [];

    // If we're checking moray, do it first.
    var idx = connected.indexOf('moray');
    if (idx !== -1) {
        fns.push(function (req, res, next) {
            CONNECTION_CHECKS['moray'](opts, req, res, next);
        });
        connected.splice(idx, 1);
    }

    prepopulate.forEach(function (resource) {
        if (!PREPOPULATE_FNS.hasOwnProperty(resource)) {
            throw (
                new verror.VError(
                    'unknown resource for prepopulation, %s', resource));
        }

        fns.push(function (req, res, next) {
            PREPOPULATE_FNS[resource](opts, req, res, next);
        });
    });

    connected.forEach(function (service) {
        if (!CONNECTION_CHECKS.hasOwnProperty(service)) {
            throw (
                new verror.VError(
                    'unknown service for precondition check, %s', service));
        }

        fns.push(function (req, res, next) {
            CONNECTION_CHECKS[service](opts, req, res, next);
        });
    });

    return fns;
}

/**
 * Return CNAPI's service status details.
 *
 * @name Ping
 * @endpoint GET /ping
 * @section Miscellaneous API
 *
 * @example GET /ping
 *
 * @response 200 Object Status details.
 */

function ping(app, req, res, next) {
    var services = {
        workflow:
            (app.workflow.client &&
             app.workflow.connected) ? 'online' : 'offline',
        moray:
            (app.moray._morayClient &&
             app.moray.connected) ? 'online' : 'offline',
        amqp:
            (app.amqpConnection &&
             app.amqpConnection.connected) ? 'online' : 'offline'
    };
    res.send(200, {
        ready:
            services.workflow === 'online' &&
            services.moray === 'online' &&
            services.amqp === 'online',
        services: services
    });
    next();
}

function attachTo(http, app) {
    http.post(
        '/loglevel',
        function (req, res, next) {
            var level = req.params.level;
            app.getLog().debug('Setting loglevel to %s', level);
            app.getLog().level(level);
            res.send();
            return next();
        });

    http.get(
        '/loglevel',
        function (req, res, next) {
            res.send({ level: app.getLog().level() });
            return next();
        });

    http.get({path: '/ping', name: 'Ping'}, function (req, res, next) {
        ping(app, req, res, next);
    });

    http.get('/info', function (req, res, next) {
        var info = {};

        fs.readFile(path.join(__dirname, '..', '..', 'package.json'),
        function (error, data) {
            if (error) {
                next(new restify.InternalError(error.message));
                return;
            }
            var pkg = JSON.parse(data.toString());
            info.version = pkg.version;

            res.send(info);
            next();
        });
    });

    http.get('/diagnostics', function (req, res, next) {
        var send = {
            start_timestamp: app.start_timestamp,
            memory: process.memoryUsage()
        };

        var taskCallbacks = {};

        Object.keys(app.taskCallbacks).forEach(function (taskid) {
            taskCallbacks[taskid] = app.taskCallbacks[taskid].map(function (i) {
                return { id: i.id }; });
        });

        send.taskCallbacks = taskCallbacks;
        send.agent_handles_length = 0;
        send.agent_handles = [];

        var tks = app.getTaskClient();

        for (var uuid in tks.agentHandles) {
            send.agent_handles_length++;

            send.agent_handles.push({
                uuid: uuid,
                task_handles_length:
                    Object.keys(
                        tks.agentHandles[uuid].taskHandles).length,
                task_handles_uuid:
                    Object.keys(tks.agentHandles[uuid].taskHandles)
            });
        }

        res.send(send);
    });

    fw.attachTo(http, app);
    images.attachTo(http, app);
    nics.attachTo(http, app);
    platforms.attachTo(http, app);
    servers.attachTo(http, app);
    waitlist.attachTo(http, app);
    vms.attachTo(http, app);
    tasks.attachTo(http, app);
    allocator.attachTo(http, app);
    boot_params.attachTo(http, app);
    ur.attachTo(http, app);
    zfs.attachTo(http, app);
}

exports.attachTo = attachTo;
exports.ensure = ensure;
<|endoftext|>


<commit_before>'use strict';

describe('The translate storage test suite', function () {
    var $translateStorage, en, ru;

    beforeEach(function () {
        module('mutant-ng-translate');

        inject(function (_$translateStorage_) {
            $translateStorage = _$translateStorage_;
        });

        en = {
            lang: 'en',
            values: {
                'apple': 'Hello, Apple!',
                'pear': 'Hello, Pear!'
            },
            moreValues: {
                'apple': 'Hello, Apple 2!',
                'peach': 'Hello, Peach!'
            },
            mergedValues: {
                'apple': 'Hello, Apple 2!',
                'pear': 'Hello, Pear!',
                'peach': 'Hello, Peach!'
            },
            key: 'apple'
        };

        ru = {
            lang: 'ru',
            values: {
                'apple': 'Привет, Яблоко!',
                'pear': 'Привет, Груша!'
            },
            moreValues: {
                'apple': 'Привет, Яблоко 2!',
                'peach': 'Привет, Персик!'
            },
            mergedValues: {
                'apple': 'Привет, Яблоко 2!',
                'pear': 'Привет, Груша!',
                'peach': 'Привет, Персик!'
            },
            key: 'apple'
        };
    });

    describe('Common tests', function() {
        it('should be defined', function () {
            expect($translateStorage).toBeDefined();
        });

        it('should be an object', function () {
            expect(typeof $translateStorage).toBe('object');
        });
    });

    });
});<commit_msg>implement get/set tests for translate storage suite<commit_after>'use strict';

describe('The translate storage test suite', function () {
    var $translateStorage, en, ru;

    beforeEach(function () {
        module('mutant-ng-translate');

        inject(function (_$translateStorage_) {
            $translateStorage = _$translateStorage_;
        });

        en = {
            lang: 'en',
            values: {
                'apple': 'Hello, Apple!',
                'pear': 'Hello, Pear!'
            },
            moreValues: {
                'apple': 'Hello, Apple 2!',
                'peach': 'Hello, Peach!'
            },
            mergedValues: {
                'apple': 'Hello, Apple 2!',
                'pear': 'Hello, Pear!',
                'peach': 'Hello, Peach!'
            },
            key: 'apple'
        };

        ru = {
            lang: 'ru',
            values: {
                'apple': 'Привет, Яблоко!',
                'pear': 'Привет, Груша!'
            },
            moreValues: {
                'apple': 'Привет, Яблоко 2!',
                'peach': 'Привет, Персик!'
            },
            mergedValues: {
                'apple': 'Привет, Яблоко 2!',
                'pear': 'Привет, Груша!',
                'peach': 'Привет, Персик!'
            },
            key: 'apple'
        };
    });

    describe('Common tests', function() {
        it('should be defined', function () {
            expect($translateStorage).toBeDefined();
        });

        it('should be an object', function () {
            expect(typeof $translateStorage).toBe('object');
        });
    });

    describe('Get/set tests', function() {
        it('should return an empty object if called without lang', function () {
            var values = $translateStorage.getValues();

            expect(values).toEqual({});
        });

        it('should return an empty object if called before set', function () {
            var values = $translateStorage.getValues(en.key);

            expect(values).toEqual({});
        });

        it('should return the values set before', function () {
            $translateStorage.setValues(en.lang, en.values);
            $translateStorage.setValues(ru.lang, ru.values);

            var enValues = $translateStorage.getValues(en.lang);
            var ruValues = $translateStorage.getValues(ru.lang);

            expect(enValues).toEqual(en.values);
            expect(ruValues).toEqual(ru.values);
        });

        it('should not change values if called without values', function () {
            $translateStorage.setValues(en.lang, en.values);
            $translateStorage.setValues(en.lang);
            var values = $translateStorage.getValues(en.lang);

            expect(values).toEqual(en.values);
        });

        it('should use last value if key already exist', function() {
            $translateStorage.setValues(en.lang, en.values);
            $translateStorage.setValues(en.lang, en.moreValues);
            var values = $translateStorage.getValues(en.lang);

            expect(values).toEqual(en.mergedValues);
        });

        it('should return undefined if called without lang and key', function() {
            var value = $translateStorage.getValue();

            expect(value).toBeUndefined();
        });

        it('should return undefined if called without key', function () {
            $translateStorage.setValues(en.lang, en.values);
            var value = $translateStorage.getValue(en.lang);

            expect(value).toBeUndefined();
        });

        it('should return key if don\'t have this key', function () {
            var value = $translateStorage.getValue(en.lang, en.key);

            expect(value).toEqual(en.key);
        });

        it('should return value by key', function () {
            $translateStorage.setValues(en.lang, en.values);
            var value = $translateStorage.getValue(en.lang, en.key);

            expect(value).toEqual(en.values[en.key]);
        });
    });
});<|endoftext|>


<commit_before>describe('Modal opening', () => {

    beforeEach(() => {
        cy.visitStandaloneScene();
        cy.viewport(768, 800);
        cy.registerAjaxContainerAlias();
        cy.get('.side-menu ul [title="Postacie"]').as('characters');
        cy.get('.side-menu ul [title="Przedmioty"]').as('items');
        cy.get('.side-menu ul [title="Miejsca"]').as('locations');
        cy.get('.side-menu ul [title="Wydarzenia"]').as('events');
    });

    it('opens mobile lists', () => {
        cy.get('@characters').click().then(() => {
            cy.get('.h4').contains('Postacie').should('be.visible');
            cy.get('.h4').contains('Przedmioty').should('not.be.visible');
            cy.get('.h4').contains('Miejsca').should('not.be.visible');
            cy.get('.h4').contains('Wydarzenia').should('not.be.visible');

            cy.get('@characters').parent().find('.js-list-toggle[title="Lista"]').click().then(() => {
                cy.get('@characters').parent().find('.js-list-container').should('be.visible');
                cy.get('@characters').parent().find('[title="Nowa postać"]').click().then(() => {
                    cy.get('@ajax-container').contains('Nowa postać').should('be.visible');
                });
            });
        });

        cy.get('@items').click().then(() => {
            cy.get('.h4').contains('Postacie').should('not.be.visible');
            cy.get('.h4').contains('Przedmioty').should('be.visible');
            cy.get('.h4').contains('Miejsca').should('not.be.visible');
            cy.get('.h4').contains('Wydarzenia').should('not.be.visible');

            cy.get('@items').parent().find('.js-list-toggle[title="Lista"]').click().then(() => {
                cy.get('@items').parent().find('.js-list-container').should('be.visible');
                cy.get('@items').parent().find('[title="Nowy przedmiot"]').click().then(() => {
                    cy.get('@ajax-container').contains('Nowy przedmiot').should('be.visible');
                });
            });
        });

        cy.get('@locations').click().then(() => {
            cy.get('.h4').contains('Postacie').should('not.be.visible');
            cy.get('.h4').contains('Przedmioty').should('not.be.visible');
            cy.get('.h4').contains('Miejsca').should('be.visible');
            cy.get('.h4').contains('Wydarzenia').should('not.be.visible');

            cy.get('@locations').parent().find('.js-list-toggle[title="Lista"]').click().then(() => {
                cy.get('@locations').parent().find('.js-list-container').should('be.visible');
                cy.get('@locations').parent().find('[title="Nowe miejsce"]').click().then(() => {
                    cy.get('@ajax-container').contains('Nowe miejsce').should('be.visible');
                });
            });
        });

        cy.get('@events').click().then(() => {
            cy.get('.h4').contains('Postacie').should('not.be.visible');
            cy.get('.h4').contains('Przedmioty').should('not.be.visible');
            cy.get('.h4').contains('Miejsca').should('not.be.visible');
            cy.get('.h4').contains('Wydarzenia').should('be.visible');

            cy.get('@events').parent().find('.js-list-toggle[title="Lista"]').click().then(() => {
                cy.get('@events').parent().find('.js-list-container').should('be.visible');
                cy.get('@events').parent().find('[title="Nowe wydarzenie"]').click().then(() => {
                    cy.get('@events').parent().find('.js-list-container').should('be.visible');
                    cy.get('@events').parent().find('.js-list-container [title="Nowe spotkanie"]').click().then(() => {
                        cy.get('@ajax-container').contains('Nowe wydarzenie').should('be.visible');
                    });
                });
            });
        });
    });
});
<commit_msg>Fixed event mobile toggle Cypress test<commit_after>describe('Modal opening', () => {

    beforeEach(() => {
        cy.visitStandaloneScene();
        cy.viewport(768, 800);
        cy.registerAjaxContainerAlias();
        cy.get('.side-menu ul [title="Postacie"]').as('characters');
        cy.get('.side-menu ul [title="Przedmioty"]').as('items');
        cy.get('.side-menu ul [title="Miejsca"]').as('locations');
        cy.get('.side-menu ul [title="Wydarzenia"]').as('events');
    });

    it('opens mobile lists', () => {
        cy.get('@characters').click().then(() => {
            cy.get('.h4').contains('Postacie').should('be.visible');
            cy.get('.h4').contains('Przedmioty').should('not.be.visible');
            cy.get('.h4').contains('Miejsca').should('not.be.visible');
            cy.get('.h4').contains('Wydarzenia').should('not.be.visible');

            cy.get('@characters').parent().find('.js-list-toggle[title="Lista"]').click().then(() => {
                cy.get('@characters').parent().find('.js-list-container').should('be.visible');
                cy.get('@characters').parent().find('[title="Nowa postać"]').click().then(() => {
                    cy.get('@ajax-container').contains('Nowa postać').should('be.visible');
                });
            });
        });

        cy.get('@items').click().then(() => {
            cy.get('.h4').contains('Postacie').should('not.be.visible');
            cy.get('.h4').contains('Przedmioty').should('be.visible');
            cy.get('.h4').contains('Miejsca').should('not.be.visible');
            cy.get('.h4').contains('Wydarzenia').should('not.be.visible');

            cy.get('@items').parent().find('.js-list-toggle[title="Lista"]').click().then(() => {
                cy.get('@items').parent().find('.js-list-container').should('be.visible');
                cy.get('@items').parent().find('[title="Nowy przedmiot"]').click().then(() => {
                    cy.get('@ajax-container').contains('Nowy przedmiot').should('be.visible');
                });
            });
        });

        cy.get('@locations').click().then(() => {
            cy.get('.h4').contains('Postacie').should('not.be.visible');
            cy.get('.h4').contains('Przedmioty').should('not.be.visible');
            cy.get('.h4').contains('Miejsca').should('be.visible');
            cy.get('.h4').contains('Wydarzenia').should('not.be.visible');

            cy.get('@locations').parent().find('.js-list-toggle[title="Lista"]').click().then(() => {
                cy.get('@locations').parent().find('.js-list-container').should('be.visible');
                cy.get('@locations').parent().find('[title="Nowe miejsce"]').click().then(() => {
                    cy.get('@ajax-container').contains('Nowe miejsce').should('be.visible');
                });
            });
        });

        cy.get('@events').click().then(() => {
            cy.get('.h4').contains('Postacie').should('not.be.visible');
            cy.get('.h4').contains('Przedmioty').should('not.be.visible');
            cy.get('.h4').contains('Miejsca').should('not.be.visible');
            cy.get('.h4').contains('Wydarzenia').should('be.visible');

            cy.get('@events').parent().find('.js-list-toggle[title="Lista"]').click().then(() => {
                cy.get('@events').parent().find('.js-list-container').should('be.visible');
                cy.get('@events').parent().find('[title="Nowe wydarzenie"]').click().then(() => {
                    cy.get('@ajax-container').contains('Nowe wydarzenie').should('be.visible');
                });
            });
        });
    });
});
<|endoftext|>