<commit_before>import path from 'path';
import { getEnvironment } from 'lazy-universal-dotenv';
import findUp from 'find-up';

const projectRoot = () => {
  let result;
  try {
    result = result || path.join(findUp.sync('.git', { type: 'directory' }), '..');
  } catch (e) {
    //
  }
  try {
    result = result || path.join(findUp.sync('.svn', { type: 'directory' }), '..');
  } catch (e) {
    //
  }
  try {
    result = result || __dirname.split('node_modules')[0];
  } catch (e) {
    //
  }

  return result || process.cwd();
};

export const includePaths = [projectRoot()];
export const nodeModulesPaths = path.resolve('./node_modules');

const nodePathsToArray = (nodePath) =>
  nodePath
    .split(process.platform === 'win32' ? ';' : ':')
    .filter(Boolean)
    .map((p) => path.resolve('./', p));

// Load environment variables starts with STORYBOOK_ to the client side.
export function loadEnv(options = {}) {
  const defaultNodeEnv = options.production ? 'production' : 'development';

  const env = {
    NODE_ENV: process.env.NODE_ENV || defaultNodeEnv,
    NODE_PATH: process.env.NODE_PATH || '',
    // This is to support CRA's public folder feature.
    // In production we set this to dot(.) to allow the browser to access these assets
    // even when deployed inside a subpath. (like in GitHub pages)
    // In development this is just empty as we always serves from the root.
    PUBLIC_URL: options.production ? '.' : '',
  };

  Object.keys(process.env)
    .filter((name) => /^STORYBOOK_/.test(name))
    .forEach((name) => {
      env[name] = process.env[name];
    });

  const base = Object.entries(env).reduce(
    (acc, [k, v]) => Object.assign(acc, { [k]: JSON.stringify(v) }),
    {}
  );

  const { stringified, raw } = getEnvironment({ nodeEnv: env.NODE_ENV });

  const fullRaw = { ...env, ...raw };

  fullRaw.NODE_PATH = nodePathsToArray(fullRaw.NODE_PATH || '');

  return {
    stringified: { ...base, ...stringified },
    raw: fullRaw,
  };
}
<commit_msg>feat: add default environment variable<commit_after>import path from 'path';
import { getEnvironment } from 'lazy-universal-dotenv';
import findUp from 'find-up';

const projectRoot = () => {
  let result;
  try {
    result = result || path.join(findUp.sync('.git', { type: 'directory' }), '..');
  } catch (e) {
    //
  }
  try {
    result = result || path.join(findUp.sync('.svn', { type: 'directory' }), '..');
  } catch (e) {
    //
  }
  try {
    result = result || __dirname.split('node_modules')[0];
  } catch (e) {
    //
  }

  return result || process.cwd();
};

export const includePaths = [projectRoot()];
export const nodeModulesPaths = path.resolve('./node_modules');

const nodePathsToArray = (nodePath) =>
  nodePath
    .split(process.platform === 'win32' ? ';' : ':')
    .filter(Boolean)
    .map((p) => path.resolve('./', p));

// Load environment variables starts with STORYBOOK_ to the client side.
export function loadEnv(options = {}) {
  const defaultNodeEnv = options.production ? 'production' : 'development';

  const env = {
    NODE_ENV: process.env.NODE_ENV || defaultNodeEnv,
    NODE_PATH: process.env.NODE_PATH || '',
    STORYBOOK: process.env.STORYBOOK || 'true',
    // This is to support CRA's public folder feature.
    // In production we set this to dot(.) to allow the browser to access these assets
    // even when deployed inside a subpath. (like in GitHub pages)
    // In development this is just empty as we always serves from the root.
    PUBLIC_URL: options.production ? '.' : '',
  };

  Object.keys(process.env)
    .filter((name) => /^STORYBOOK_/.test(name))
    .forEach((name) => {
      env[name] = process.env[name];
    });

  const base = Object.entries(env).reduce(
    (acc, [k, v]) => Object.assign(acc, { [k]: JSON.stringify(v) }),
    {}
  );

  const { stringified, raw } = getEnvironment({ nodeEnv: env.NODE_ENV });

  const fullRaw = { ...env, ...raw };

  fullRaw.NODE_PATH = nodePathsToArray(fullRaw.NODE_PATH || '');

  return {
    stringified: { ...base, ...stringified },
    raw: fullRaw,
  };
}
<|endoftext|>


<commit_before>/*jshint node: true, -W106 */
'use strict';

/*
* Name : tableFlowModel.js
* Module : Lib::DataTier::TableFlowModel
* Location : /lib/dataTier/flow
*
* History :
*
* Version   Date         Programmer         Description
* =========================================================
* 0.0.1     2015-05-16   Samuele Zanella    Initial code
* =========================================================
*/

function TableFlowModel(params) {
	console.dir(params);
}
module.exports = TableFlowModel;<commit_msg>start tableFlow<commit_after>/*jshint node: true, -W106 */
'use strict';

/*
* Name : tableFlowModel.js
* Module : Lib::DataTier::tableFlowModel
* Location : /lib/dataTier/flow
*
* History :
*
* Version   Date         Programmer         Description
* =========================================================
* 0.0.1     2015-05-15   Filippo Rampado    Initial code
* =========================================================
*/
var FlowModel = require('./flowModel.js');
var Helper = require('../../helpers/functionHelper.js');

function TableFlowModel(params) {
	if(params===undefined || params.ID===undefined || typeof params.ID !== 'string'|| params.ID.trim() === ''){ // ID field is required
		console.log('Error: 242');
		return;
	}

	params.type = 'TableFlow';
	this.parent.constructor.call(this, params);

	this._columnKeys=[];
	this._columnFormats=[];
	this._fontColorKey=null;//text black
	this._backgroungColorKey=null;//white background
	this._maxItems=50;//items displayed
	this._maxItemsSaved=500; //items saved

	if(params.columnKeys!==undefined && Array.isArray(params.columnKeys) && params.columnKeys.length>0){
		var validKeys=true;
		var keys=params.columnKeys.length;
		for (var i=0; i<keys; i++){
			if (typeof params.columnKeys[i]!=='string'){
				validKeys=false;
			}
		}
		if (validKeys){
			this._columnKeys=params.columnKeys;
		}
	}
	if(params.columnFormats!==undefined && Array.isArray(params.columnFormats) && params.columnFormats.length>0){
		var validFormat=true;
		var formats=params.columnFormats.length;
		for (var j=0; j<formats; j++){
			if (typeof params.columnFormats[j]!=='string'){
				validFormat=false;
			}
		}
		if (validFormat){
			this._columnFormats=params.columnFormats;
		}
	}

	///////////////////////////////////////

	if(params.maxItems!==undefined && typeof params.maxItems==='number' && params.maxItems>=0){
		this._maxItems=params.maxItems;
	}
	if(params.maxItemsSaved!==undefined && typeof params.maxItemsSaved==='number' && params.maxItemsSaved>=0){
		this._maxItemsSaved=params.maxItemsSaved;
	}
}

TableFlowModel.prototype = Object.create(FlowModel.prototype);
TableFlowModel.prototype.constructor = TableFlowModel;
TableFlowModel.prototype.parent = FlowModel.prototype;

TableFlowModel.prototype.addRecord = function(record){
	if(record!==undefined && typeof record === 'object'){
		this._records.push(record);
		var index=this._records.length-1;
		var ID=this.generateNorrisRecordID(index);
		this._records[index].norrisRecordID=ID;
		this.validateRecord(index);
		return ID;
	}
	console.log('Error: 121');
	return 121;
};

TableFlowModel.prototype.updateRecord = function(ID, record){
	if (record === undefined || record === null || typeof record !== 'object'|| Array.isArray(record)){
		return 223;
	}
	if (typeof ID==='string' && ID.indexOf(this._ID) !== -1) {
		var records=this._records.length;
		var i=0;
		var found=false;
		while (i<records && (!found)){
			if (this._records[i].norrisRecordID===ID){
				found=true;
			}
			else{
				i++;
			}
		}//while
		if (found){//in records[i] there is the ID
			this._records[i]=record;
			this.validateRecord(i);
			return true;
		}
		//no ID in records
		return 224;
	}
	//invalid ID
	return 224;
};

module.exports = TableFlowModel;<|endoftext|>


<commit_before>import React from 'react';

import test from 'ava';
import { shallow } from 'enzyme';
import sinon from 'sinon';
import yaml from 'js-yaml';
import fs from 'fs';
import util from 'util';

import Character from '../src/Character';
import Photo from '../src/photo';

const readFilePromisified = util.promisify(fs.readFile);

const context = {
  setTitle: () => {},
  router: {
    history: {
      replace: () => {},
    },
  },
};

/** @test {Character} */
test('<Character /> should be loaded', t => {
  const wrapper = shallow(<Character match={{ params: { chara: 'kt-kitty' } }} />, { context, disableLifecycleMethods: true });
  const instance = wrapper.instance();
  t.not(instance, null);
});

/** @test {Character} */
test.cb('<Character /> should be loaded with kt-kitty', t => {
  let photoCount = -1;
  const loadPhotosDouble = sinon.stub(Photo, 'loadPhotos');
  loadPhotosDouble.callsFake(async arg => {
    const data = await readFilePromisified(`data/${arg}.yaml`, { encoding: 'utf-8' });
    const arr = yaml.safeLoad(data);
    photoCount = arr.length;
    return arr.map(obj => new Photo(obj));
  });
  try {
    const wrapper = shallow(<Character match={{ params: { chara: 'kt-kitty' } }} />, { context });
    t.is(null, wrapper.state('allPhotos'));
    t.deepEqual([], wrapper.state('photos'));
    setTimeout(() => { // setImmediate does not work?
      t.not(null, wrapper.state('allPhotos'));
      t.is(photoCount, wrapper.state('photos').length);
      t.end();
    }, 100);
  } finally {
    loadPhotosDouble.restore();
  }
});
<commit_msg>Make test defensive in slow environment<commit_after>import React from 'react';

import test from 'ava';
import { shallow } from 'enzyme';
import sinon from 'sinon';
import yaml from 'js-yaml';
import fs from 'fs';
import util from 'util';

import Character from '../src/Character';
import Photo from '../src/photo';

const readFilePromisified = util.promisify(fs.readFile);

const context = {
  setTitle: () => {},
  router: {
    history: {
      replace: () => {},
    },
  },
};

/** @test {Character} */
test('<Character /> should be loaded', t => {
  const wrapper = shallow(<Character match={{ params: { chara: 'kt-kitty' } }} />, { context, disableLifecycleMethods: true });
  const instance = wrapper.instance();
  t.not(instance, null);
});

/** @test {Character} */
test.cb('<Character /> should be loaded with ar-retsuko', t => {
  let photoCount = -1;
  const loadPhotosDouble = sinon.stub(Photo, 'loadPhotos');
  loadPhotosDouble.callsFake(async arg => {
    const data = await readFilePromisified(`data/${arg}.yaml`, { encoding: 'utf-8' });
    const arr = yaml.safeLoad(data);
    photoCount = arr.length;
    return arr.map(obj => new Photo(obj));
  });
  function checkLoaded(wrapper, interval, retry) {
    if (wrapper.state('allPhotos')) {
      t.is(photoCount, wrapper.state('photos').length);
      t.end();
    } else if (retry > 0) {
      setTimeout(() => checkLoaded(wrapper, interval, retry - 1), interval);
    } else {
      t.fail('did not load photos');
    }
  }
  try {
    const wrapper = shallow(<Character match={{ params: { chara: 'ar-retsuko' } }} />, { context });
    t.is(null, wrapper.state('allPhotos'));
    t.deepEqual([], wrapper.state('photos'));
    checkLoaded(wrapper, 100, 10);
  } finally {
    loadPhotosDouble.restore();
  }
});
<|endoftext|>


<commit_before>var async = require('async');
var _ = require('underscore');
module.exports = function(app){
	app.NPCBase = function(options){
		var default_options = {

			age:1,
			size:50,
			energy:1000,
			health:100,
			energy_consumption:1,
			brain:{},
			facing:'down',
			inventory:{},
			_is_blocking:true,
			_is_npc:true//NO Shit
		}
		_.extend(options, default_options);

		var npc_base = new app.PhysicalObjectBase(options);
		//Register it globally as an NPC
		npc_base.world.add_npc(npc_base);
		npc_base.walk = {
			exec:function(x, y){

				if(x == npc_base.x && y == npc_base){
					//No change so no trigger
					return false;
				}

				//Check to see if NPC has energy
				var energy_cost = 1;

				if(npc_base.energy < energy_cost){
					console.log(npc_base.id + " energy is at " + npc_base.energy);
					return false;
				}

				//Collision Detection
				var destination_tile = npc_base.world.getTile(x, y);
				if(!destination_tile){
					//Your at the end of the level
					return false;
				}
				for(var object_id in destination_tile.objects){
					if(destination_tile.objects[object_id].is_blocking()){
						var event = {
							target:npc_base,
							tile:destination_tile
						}
						//console.log(npc_base.id + ' collided with ' + object_id);
						destination_tile.objects[object_id].trigger('collision', event)
						return false;
					}
				}

				npc_base.energy -= energy_cost;
				npc_base.setXY(x, y);

			},
			left:function(){
				npc_base.facing = 'left';
				npc_base.walk.exec(npc_base.x - 1, npc_base.y)

			},
			right:function(){
				npc_base.facing = 'right';
				npc_base.walk.exec(npc_base.x + 1, npc_base.y)
			},
			up:function(){
				npc_base.facing = 'up';
				npc_base.walk.exec(npc_base.x, npc_base.y  - 1);
			},
			down:function(){
				npc_base.facing = 'down';
				npc_base.walk.exec(npc_base.x, npc_base.y  + 1);

			}
		}
		npc_base.interact = function(data){
			var target_x = npc_base.x;

			var target_y = npc_base.y;
			if(npc_base.facing == 'down'){
				target_y += 1;
			}else if(npc_base.facing == 'up'){
				target_y -= 1;
			}else if(npc_base.facing == 'right'){
				target_x += 1;
			}else if(npc_base.facing == 'left'){
				target_x -= 1;
			}
			var target_tile = npc_base.world.getTile(target_x, target_y);
			if(!target_tile){
				return;
			}
			var event = {
				npc: npc_base
			}
			target_tile.trigger('interact', event);
		}
		npc_base.cycle = function(cb){
			//Eventually run through setup logic
			var brain = this.brain;
			return async.eachSeries(
			    Object.keys(this.brain),
				function(key, cb){
					return brain[key].process(cb)
			    },
			    function(errs){
					return cb();
			    }
			)
			/*return cb();*/
		}
		npc_base.addLogicNode = function(inputNode, namespace){
			if(!namespace){
				namespace = this.id + '-logic-node-' + Object.keys(this.brain).length;
			}
			this.brain[namespace] = inputNode;
		}
		npc_base.ingest = function(data){
			if(!npc_base.inventory[data.object.id]){
				console.error("Player attemptng to ingest something not in their inventory");
			}
			npc.remove_from_inventory(data.object.id);
			npc_base.inventory[data.object.id].ingest(npc_base, data, function(){
				//Nothing to do
				//Perhps reflect?
			});
		}
		npc_base.add_to_inventory = function(object){
			npc_base.inventory[object.id] = object;
			npc_base.markUpdated();
		}
		npc_base.remove_from_inventory = function(object_id){
			if(object_id.id){
				object_id = object_id.id;
			}
			if(!npc_base.inventory[object_id]){
				throw new Error("NPC " + npc_base.id + ' does not have inventory_object ' + object_id + ' to remove');
			}
			delete(npc_base.inventory[object_id]);
			npc_base.markUpdated();

		}
		/**
		 * This is where an NPC watches for the pleasure delta(change) and stores it in memory with the inputNode
		 * @param next
		 */
		npc_base.reflect = function(next){

		}
		var _toObject = _.bind(npc_base.toObject, npc_base);
		npc_base.toObject = function(){
			var ret = _toObject();
			ret.inventory = {};
			for(var i in this.inventory){
				ret.inventory[i] = this.inventory[i].toObject();
			}
			return ret;
		}
		return npc_base;
	}

}<commit_msg>Adding Invintory Objects<commit_after>var async = require('async');
var _ = require('underscore');
module.exports = function(app){
	app.NPCBase = function(options){
		var default_options = {

			age:1,
			size:50,
			energy:1000,
			health:100,
			energy_consumption:1,
			brain:{},
			facing:'down',
			inventory:{},
			_is_blocking:true,
			_is_npc:true//NO Shit
		}
		_.extend(options, default_options);

		var npc_base = new app.PhysicalObjectBase(options);
		//Register it globally as an NPC
		npc_base.world.add_npc(npc_base);
		npc_base.walk = {
			exec:function(x, y){

				if(x == npc_base.x && y == npc_base){
					//No change so no trigger
					return false;
				}

				//Check to see if NPC has energy
				var energy_cost = 1;

				if(npc_base.energy < energy_cost){
					console.log(npc_base.id + " energy is at " + npc_base.energy);
					return false;
				}

				//Collision Detection
				var destination_tile = npc_base.world.getTile(x, y);
				if(!destination_tile){
					//Your at the end of the level
					return false;
				}
				for(var object_id in destination_tile.objects){
					if(destination_tile.objects[object_id].is_blocking()){
						var event = {
							target:npc_base,
							tile:destination_tile
						}
						console.log(npc_base.id + ' collided with ' + object_id);
						destination_tile.objects[object_id].trigger('collision', event)
						return false;
					}
				}

				npc_base.energy -= energy_cost;
				npc_base.setXY(x, y);

			},
			left:function(){
				npc_base.facing = 'left';
				npc_base.walk.exec(npc_base.x - 1, npc_base.y)

			},
			right:function(){
				npc_base.facing = 'right';
				npc_base.walk.exec(npc_base.x + 1, npc_base.y)
			},
			up:function(){
				npc_base.facing = 'up';
				npc_base.walk.exec(npc_base.x, npc_base.y  - 1);
			},
			down:function(){
				npc_base.facing = 'down';
				npc_base.walk.exec(npc_base.x, npc_base.y  + 1);

			}
		}
		npc_base.interact = function(data){
			var target_x = npc_base.x;

			var target_y = npc_base.y;
			if(npc_base.facing == 'down'){
				target_y += 1;
			}else if(npc_base.facing == 'up'){
				target_y -= 1;
			}else if(npc_base.facing == 'right'){
				target_x += 1;
			}else if(npc_base.facing == 'left'){
				target_x -= 1;
			}
			var target_tile = npc_base.world.getTile(target_x, target_y);
			if(!target_tile){
				return;
			}
			var event = {
				npc: npc_base
			}
			target_tile.trigger('interact', event);
		}
		npc_base.cycle = function(cb){
			//Eventually run through setup logic
			var brain = this.brain;
			return async.eachSeries(
			    Object.keys(this.brain),
				function(key, cb){
					return brain[key].process(cb)
			    },
			    function(errs){
					return cb();
			    }
			)
			/*return cb();*/
		}
		npc_base.addLogicNode = function(inputNode, namespace){
			if(!namespace){
				namespace = this.id + '-logic-node-' + Object.keys(this.brain).length;
			}
			this.brain[namespace] = inputNode;
		}
		npc_base.ingest = function(data){
			if(!npc_base.inventory[data.object.id]){
				console.error("Player attemptng to ingest something not in their inventory");
			}
			npc.remove_from_inventory(data.object.id);
			npc_base.inventory[data.object.id].ingest(npc_base, data, function(){
				//Nothing to do
				//Perhps reflect?
			});
		}
		npc_base.add_to_inventory = function(object){
			npc_base.inventory[object.id] = object;
			npc_base.markUpdated();
		}
		npc_base.remove_from_inventory = function(object_id){
			if(object_id.id){
				object_id = object_id.id;
			}
			if(!npc_base.inventory[object_id]){
				throw new Error("NPC " + npc_base.id + ' does not have inventory_object ' + object_id + ' to remove');
			}
			delete(npc_base.inventory[object_id]);
			npc_base.markUpdated();

		}
		/**
		 * This is where an NPC watches for the pleasure delta(change) and stores it in memory with the inputNode
		 * @param next
		 */
		npc_base.reflect = function(next){

		}
		var _toObject = _.bind(npc_base.toObject, npc_base);
		npc_base.toObject = function(){
			var ret = _toObject();
			ret.inventory = {};
			for(var i in this.inventory){
				ret.inventory[i] = this.inventory[i].toObject();
			}
			return ret;
		}
		return npc_base;
	}

}<|endoftext|>


<commit_before>'use strict';

(function () {

  var React = require('react');

  var analyticsScript = '(function(i,s,o,g,r,a,m){i[\'GoogleAnalyticsObject\']=r;i[r]=i[r]||function(){' +
    '(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),' +
    'm=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)' +
    '})(window,document,\'script\',\'https://www.google-analytics.com/analytics.js\',\'ga\');' +
    'ga(\'create\', \'UA-64450504-3\', \'auto\');' +
    'ga(\'send\', \'pageview\');';

  var Analytics = React.createClass({
    render: function () {
      return (
        <script type="text/javascript" dangerouslySetInnerHTML={{__html: analyticsScript}} />
      );
    }
  });

  module.exports = Analytics;

})();
<commit_msg>Use double quotes in script<commit_after>'use strict';

(function () {

  var React = require('react');

  var analyticsScript = '(function(i,s,o,g,r,a,m){i["GoogleAnalyticsObject"]=r;i[r]=i[r]||function(){' +
    '(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),' +
    'm=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)' +
    '})(window,document,"script","https://www.google-analytics.com/analytics.js","ga");' +
    'ga("create", "UA-64450504-3", "auto");' +
    'ga("send", "pageview");';

  var Analytics = React.createClass({
    render: function () {
      return (
        <script type="text/javascript" dangerouslySetInnerHTML={{__html: analyticsScript}} />
      );
    }
  });

  module.exports = Analytics;

})();
<|endoftext|>


<commit_before>var service = require('./angular-picturify.service');

module.exports = angular.module('picturify.directive', [service]).directive('picturify', picturifyDirective).name;

picturifyDirective.$inject = [$timeout', 'picturify'];
function picturifyDirective($timeout, picturify) {
  'use strict';

  return {
    restrict: 'A',
    link: function (scope, element, attrs) {

      var opts = angular.extend({}, scope.$eval(attrs.picturify));
      console.log(opts);

      scope.$watch(function(newVal) {
        element.html(picturify.filter(element.html(), opts.target,  (opts.class || opts.width), opts.amount));
      });
    }
  };
}
<commit_msg>Removed unused dependencies and console.log.<commit_after>var service = require('./angular-picturify.service');

module.exports = angular.module('picturify.directive', [service]).directive('picturify', picturifyDirective).name;

picturifyDirective.$inject = ['picturify'];
function picturifyDirective(picturify) {
  'use strict';

  return {
    restrict: 'A',
    link: function (scope, element, attrs) {

      var opts = angular.extend({}, scope.$eval(attrs.picturify));

      scope.$watch(function(newVal) {
        element.html(picturify.filter(element.html(), opts.target,  (opts.class || opts.width), opts.amount));
      });
    }
  };
}
<|endoftext|>


<commit_before>
module.exports = users;
users.list = list;
users.create = create;
users.read = read;
users.delete = deleteUser;
users.update = update;
users.import = importUsers;

users.usage = "\nfhc admin-users list"
             +"\nfhc admin-users create username=<username> [password=<password>] [email=<email>] [name=<name>] [roles=<roles>] [authpolicies=<authpolicies>] [invite=<invitation>] [storeItemGroups=<groups>]"
             +"\nfhc admin-users delete <username>"
             +"\nfhc admin-users read <username>"
             +"\nfhc admin-users update username=<username> [password=<password>] [email=<email>] [name=<name>] [roles=<roles>] [authpolicies=<authpolicies>] [inviation=<invitation>] [enabled=<enabled>] [storeItemGroups=<groups>]"
             +"\nfhc admin-users enable <username>"
             +"\nfhc admin-users disable <username>"
             +"\nfhc admin-users changeroles <username> <roles>"
             +"\nfhc admin-users changeauthpolicies <username> <authpolicies>"
             +"\nfhc admin-users listdevices <username>"
             +"\nfhc admin-users listinstallapps <username>"
  +"\nfhc admin-users import <path-to-csv-file> [invite] [<roles> <authpolicies>]";
            // +"\nfhc admin-storeitems addgroups <storeitem guid> <group_guid>*"
            // +"\nfhc admin-storeitems removegroups <storeitem guid> <group_guid>*";

var log = require("./utils/log");
var fhc = require("./fhc");
var fhreq = require("./utils/request");
var common = require("./common");
var util = require('util');
var async = require('async');
var path = require('path');
var ini = require('./utils/ini');
var Table = require('cli-table');

// Main users entry point
function users (args, cb) {
  if (args.length == 0){
    return list(cb);
  }

  var action = args[0];
  if (action == 'list') {
    return list(cb);
  }else if (action === 'create'){
    if (args.length < 2) return cb("Invalid arguments for 'create':" + users.usage);
    return create(args, cb);
  }else if (action === 'read'){
    if (args.length !== 2) return cb("Invalid arguments for 'read':" + users.usage);
    return read(args[1], cb);
  }else if (action === 'update'){
    if (args.length < 2 ) return cb("Invalid arguments for 'update':" + users.usage);
    return update(args, cb);
  }else if (action === 'delete'){
    if (args.length !== 2) return cb("Invalid arguments for 'delete':" + users.usage);
    return deleteUser(args[1], cb);
  }else if (action === 'enable'){
    if (args.length !== 2) return cb("Invalid arguments for 'enable':" + users.usage);
    return enableUser(args[1], cb);
  }else if (action === 'disable'){
    if (args.length !== 2) return cb("Invalid arguments for 'disable':" + users.usage);
    return disableUser(args[1], cb);
  }else if (action === 'changeroles'){
    if (args.length !== 3) return cb("Invalid arguments for 'changeroles':" + users.usage);
    return changeRoles(args[1], args[2], cb);
  }else if (action === 'changeauthpolicies'){
    if (args.length !== 3) return cb("Invalid arguments for 'changeauthpolicies':" + users.usage);
    return changeAuthPolicies(args[1], args[2], cb);
  }/*else if (action === 'changegroups'){
    if (args.length !== 3) return cb("Invalid arguments for 'changegroups':" + users.usage);
    return changeGroups(args[1], args[2], cb);
  }*/else if (action === 'listdevices'){
    if (args.length !== 2) return cb("Invalid arguments for 'listdevices':" + users.usage);
    return listDevices(args[1], cb);
  }else if (action === 'listinstallapps'){
    if (args.length !== 2) return cb("Invalid arguments for 'listinstallapps':" + users.usage);
    return listInstallApps( args[1], cb);
  }else if(action === 'import'){
    if(args.length < 2) return cb("Invalid arguments for 'import': " + users.usage);
    return importUsers(args, cb);
  // }else if (action === 'addgroups'){
  //   if(args.length < 2) return cb(users.usage);
  //   var act = args.shift();
  //   var username = args.shift();
  //   return addgroups(username, args, cb);
  // }else if (action === 'removegroups'){
  //   if(args.length < 2) return cb(users.usage);
  //   var act = args.shift();
  //   var username = args.shift();
  //   return removegroups(username, args, cb);
  }else if (args.length == 1){
    var appId = fhc.appId(args[0]);
    return read(appId, cb);
  }else{
    return cb(users.usage);
  }
}

// list users
function list(cb) {
  common.doApiCall(fhreq.getFeedHenryUrl(), "/box/srv/1.1/admin/user/list", {}, "Error listing users: ", function(err, users){
    if(err) return cb(err);
    return cb(undefined, users);
  });
}

// create user
function create(args, cb) {
  var data = {};
  args.forEach(function(arg){
    var pair = arg.split("=");
    data[pair[0]] = parseVal(pair[0],pair[1]);
  })
  if(!data.username){
    return cb(new Error("username is undefined"));
  }

  common.doApiCall(fhreq.getFeedHenryUrl(), "/box/srv/1.1/admin/user/create", data, "Error creating user: ", function(err, res){
    if(err) return cb(err);
    return cb(undefined, res);
  });
}

// delete user
function deleteUser(username, cb) {
  var data = {"username" : username};
  common.doApiCall(fhreq.getFeedHenryUrl(), "/box/srv/1.1/admin/user/delete", data, "Error deleting user: ", function(err, res){
    if(err) return cb(err);
    return cb(undefined, res);
  });
}

// update user
function update(args, cb) {
  var data = {};
  args.forEach(function(arg){
    var pair = arg.split("=");
    data[pair[0]] = parseVal(pair[0],pair[1]);
  })
  if(!data.username){
    return cb(new Error("username is undefined"));
  }

  common.doApiCall(fhreq.getFeedHenryUrl(), "/box/srv/1.1/admin/user/update", data, "Error updating user: ", function(err, res){
    if(err) return cb(err);
    return cb(undefined, res);
  });
}

// read user
function read(username, cb) {
  common.doApiCall(fhreq.getFeedHenryUrl(), "/box/srv/1.1/admin/user/read", {"username": username}, "Error reading user: ", function(err, data){
    if(err) return cb(err);
    return cb(undefined, data);
  });
}

function enableUser(username, cb){
  common.doApiCall(fhreq.getFeedHenryUrl(), "/box/srv/1.1/admin/user/update", {username: username, enabled: true}, "Error updating user: ", function(err, res){
    if(err) return cb(err);
    return cb(undefined, res);
  });
}

function disableUser(username, cb){
  common.doApiCall(fhreq.getFeedHenryUrl(), "/box/srv/1.1/admin/user/update", {username: username, enabled: false}, "Error updating user: ", function(err, res){
    if(err) return cb(err);
    return cb(undefined, res);
  });
}

function changeRoles(username, roles, cb){
  update(["username=" + username, "roles=" + roles], cb);
}

function changeAuthPolicies(username, authpolicies, cb){
  update(["username=" + username, "authpolicies=" + authpolicies], cb);
}

function changeGroups(username, groups, cb){
  update(["username=" + username, "groups=" + groups], cb);
}

function listDevices(username, cb){
  common.doApiCall(fhreq.getFeedHenryUrl(), "/box/srv/1.1/admin/user/listdevices", {"username": username}, "Error listing user devices: ", function(err, data){
    if(err) return cb(err);
    return cb(undefined, data);
  });
}

function listInstallApps(username, cb){
  common.doApiCall(fhreq.getFeedHenryUrl(), "/box/srv/1.1/admin/user/liststoreitems", {"username": username}, "Error listing user installed apps: ", function(err, data){
    if(err) return cb(err);
    return cb(undefined, data);
  });
}

function importUsers(args, cb){
  var roles = "";
  var authpolicies = "";
  var filepath = args[1];
  var invite = false;
  if(args.length == 3){
    if(args[2].indexOf("true") > 0 || args[2].indexOf("false") > 0){
      invite = (args[2] === "true");
    } else {
      roles = args[2];
    }
  }
  if(args.length > 3){
    invite = (args[2] === "true");
    roles = args[3];
    authpolicies = args.length > 4 ? args[4] : authpolicies;
  }
  var url = "/box/srv/1.1/admin/user/import";
  fhreq.uploadFile(url, filepath, {"invite": invite, "roles": roles, "authpolicies": authpolicies}, "text/csv", function(err, res){
    if(err) return cb(err);
    if(res.status.toLowerCase() == "ok" && res.cachekey){
      common.waitFor(res.cachekey, cb);
    } else {
      cb(res.message);
    }
  });
}

// function addgroups(username, groups, cb) {
//   common.doApiCall(fhreq.getFeedHenryUrl(), "/box/srv/1.1/admin/user/addgroups", {"username": username,  "groups": groups}, "Error adding groups to user: ", function(err, data){
//     if(err) return cb(err);
//     return cb(undefined, data);
//   });
// }

// function removegroups(username, groups, cb) {
//   common.doApiCall(fhreq.getFeedHenryUrl(), "/box/srv/1.1/admin/user/removegroups", {"username": username,  "groups": groups}, "Error removing groups from user: ", function(err, data){
//     if(err) return cb(err);
//     return cb(undefined, data);
//   });
// }

function parseVal(name, val){
  if(val === "true"){
    return true;
  }
  if(val === "false"){
    return false;
  }
  if(name === "storeItemGroups") {
    var tmp = [];
    val.split(/,/).forEach(function(v){
      if(v.trim() !== "") {
        tmp.push(v);
      }
    });
    val = tmp;
  }
  return val;
}

// bash completion
users.completion = function (opts, cb) {
  var argv = opts.conf.argv.remain;
  if (argv[1] !== "admin-users") argv.unshift("admin-users");
  if (argv.length === 2) {
    var cmds = ["list", "read", "create", "update", "delete", "enable", "disable", "changeroles", "changeauthpolicies", "listdevices", "listinstallapps" /*, "addgroups", "removegroups" */];
    if (opts.partialWord !== "l") cmds.push("list");
    return cb(undefined, cmds);
  }

/*
  var action = argv[2];
  switch (action) {
    case "update":
    case "read":
    case "delete":
      // get users list
      break;
    case "list":
      return cb(null, []);
    default: return cb(null, []);
  }
*/
};
<commit_msg>removed commented-out code<commit_after>
module.exports = users;
users.list = list;
users.create = create;
users.read = read;
users.delete = deleteUser;
users.update = update;
users.import = importUsers;

users.usage = "\nfhc admin-users list"
             +"\nfhc admin-users create username=<username> [password=<password>] [email=<email>] [name=<name>] [roles=<roles>] [authpolicies=<authpolicies>] [invite=<invitation>] [storeItemGroups=<groups>]"
             +"\nfhc admin-users delete <username>"
             +"\nfhc admin-users read <username>"
             +"\nfhc admin-users update username=<username> [password=<password>] [email=<email>] [name=<name>] [roles=<roles>] [authpolicies=<authpolicies>] [inviation=<invitation>] [enabled=<enabled>] [storeItemGroups=<groups>]"
             +"\nfhc admin-users enable <username>"
             +"\nfhc admin-users disable <username>"
             +"\nfhc admin-users changeroles <username> <roles>"
             +"\nfhc admin-users changeauthpolicies <username> <authpolicies>"
             +"\nfhc admin-users listdevices <username>"
             +"\nfhc admin-users listinstallapps <username>"
             +"\nfhc admin-users import <path-to-csv-file> [invite] [<roles> <authpolicies>]";

var log = require("./utils/log");
var fhc = require("./fhc");
var fhreq = require("./utils/request");
var common = require("./common");
var util = require('util');
var async = require('async');
var path = require('path');
var ini = require('./utils/ini');
var Table = require('cli-table');

// Main users entry point
function users (args, cb) {
  if (args.length == 0){
    return list(cb);
  }

  var action = args[0];
  if (action == 'list') {
    return list(cb);
  }else if (action === 'create'){
    if (args.length < 2) return cb("Invalid arguments for 'create':" + users.usage);
    return create(args, cb);
  }else if (action === 'read'){
    if (args.length !== 2) return cb("Invalid arguments for 'read':" + users.usage);
    return read(args[1], cb);
  }else if (action === 'update'){
    if (args.length < 2 ) return cb("Invalid arguments for 'update':" + users.usage);
    return update(args, cb);
  }else if (action === 'delete'){
    if (args.length !== 2) return cb("Invalid arguments for 'delete':" + users.usage);
    return deleteUser(args[1], cb);
  }else if (action === 'enable'){
    if (args.length !== 2) return cb("Invalid arguments for 'enable':" + users.usage);
    return enableUser(args[1], cb);
  }else if (action === 'disable'){
    if (args.length !== 2) return cb("Invalid arguments for 'disable':" + users.usage);
    return disableUser(args[1], cb);
  }else if (action === 'changeroles'){
    if (args.length !== 3) return cb("Invalid arguments for 'changeroles':" + users.usage);
    return changeRoles(args[1], args[2], cb);
  }else if (action === 'changeauthpolicies'){
    if (args.length !== 3) return cb("Invalid arguments for 'changeauthpolicies':" + users.usage);
    return changeAuthPolicies(args[1], args[2], cb);
  }else if (action === 'listdevices'){
    if (args.length !== 2) return cb("Invalid arguments for 'listdevices':" + users.usage);
    return listDevices(args[1], cb);
  }else if (action === 'listinstallapps'){
    if (args.length !== 2) return cb("Invalid arguments for 'listinstallapps':" + users.usage);
    return listInstallApps( args[1], cb);
  }else if(action === 'import'){
    if(args.length < 2) return cb("Invalid arguments for 'import': " + users.usage);
    return importUsers(args, cb);
  }else if (args.length == 1){
    var appId = fhc.appId(args[0]);
    return read(appId, cb);
  }else{
    return cb(users.usage);
  }
}

// list users
function list(cb) {
  common.doApiCall(fhreq.getFeedHenryUrl(), "/box/srv/1.1/admin/user/list", {}, "Error listing users: ", function(err, users){
    if(err) return cb(err);
    return cb(undefined, users);
  });
}

// create user
function create(args, cb) {
  var data = {};
  args.forEach(function(arg){
    var pair = arg.split("=");
    data[pair[0]] = parseVal(pair[0],pair[1]);
  })
  if(!data.username){
    return cb(new Error("username is undefined"));
  }

  common.doApiCall(fhreq.getFeedHenryUrl(), "/box/srv/1.1/admin/user/create", data, "Error creating user: ", function(err, res){
    if(err) return cb(err);
    return cb(undefined, res);
  });
}

// delete user
function deleteUser(username, cb) {
  var data = {"username" : username};
  common.doApiCall(fhreq.getFeedHenryUrl(), "/box/srv/1.1/admin/user/delete", data, "Error deleting user: ", function(err, res){
    if(err) return cb(err);
    return cb(undefined, res);
  });
}

// update user
function update(args, cb) {
  var data = {};
  args.forEach(function(arg){
    var pair = arg.split("=");
    data[pair[0]] = parseVal(pair[0],pair[1]);
  })
  if(!data.username){
    return cb(new Error("username is undefined"));
  }

  common.doApiCall(fhreq.getFeedHenryUrl(), "/box/srv/1.1/admin/user/update", data, "Error updating user: ", function(err, res){
    if(err) return cb(err);
    return cb(undefined, res);
  });
}

// read user
function read(username, cb) {
  common.doApiCall(fhreq.getFeedHenryUrl(), "/box/srv/1.1/admin/user/read", {"username": username}, "Error reading user: ", function(err, data){
    if(err) return cb(err);
    return cb(undefined, data);
  });
}

function enableUser(username, cb){
  common.doApiCall(fhreq.getFeedHenryUrl(), "/box/srv/1.1/admin/user/update", {username: username, enabled: true}, "Error updating user: ", function(err, res){
    if(err) return cb(err);
    return cb(undefined, res);
  });
}

function disableUser(username, cb){
  common.doApiCall(fhreq.getFeedHenryUrl(), "/box/srv/1.1/admin/user/update", {username: username, enabled: false}, "Error updating user: ", function(err, res){
    if(err) return cb(err);
    return cb(undefined, res);
  });
}

function changeRoles(username, roles, cb){
  update(["username=" + username, "roles=" + roles], cb);
}

function changeAuthPolicies(username, authpolicies, cb){
  update(["username=" + username, "authpolicies=" + authpolicies], cb);
}

function changeGroups(username, groups, cb){
  update(["username=" + username, "groups=" + groups], cb);
}

function listDevices(username, cb){
  common.doApiCall(fhreq.getFeedHenryUrl(), "/box/srv/1.1/admin/user/listdevices", {"username": username}, "Error listing user devices: ", function(err, data){
    if(err) return cb(err);
    return cb(undefined, data);
  });
}

function listInstallApps(username, cb){
  common.doApiCall(fhreq.getFeedHenryUrl(), "/box/srv/1.1/admin/user/liststoreitems", {"username": username}, "Error listing user installed apps: ", function(err, data){
    if(err) return cb(err);
    return cb(undefined, data);
  });
}

function importUsers(args, cb){
  var roles = "";
  var authpolicies = "";
  var filepath = args[1];
  var invite = false;
  if(args.length == 3){
    if(args[2].indexOf("true") > 0 || args[2].indexOf("false") > 0){
      invite = (args[2] === "true");
    } else {
      roles = args[2];
    }
  }
  if(args.length > 3){
    invite = (args[2] === "true");
    roles = args[3];
    authpolicies = args.length > 4 ? args[4] : authpolicies;
  }
  var url = "/box/srv/1.1/admin/user/import";
  fhreq.uploadFile(url, filepath, {"invite": invite, "roles": roles, "authpolicies": authpolicies}, "text/csv", function(err, res){
    if(err) return cb(err);
    if(res.status.toLowerCase() == "ok" && res.cachekey){
      common.waitFor(res.cachekey, cb);
    } else {
      cb(res.message);
    }
  });
}

function parseVal(name, val){
  if(val === "true"){
    return true;
  }
  if(val === "false"){
    return false;
  }
  if(name === "storeItemGroups") {
    var tmp = [];
    val.split(/,/).forEach(function(v){
      if(v.trim() !== "") {
        tmp.push(v);
      }
    });
    val = tmp;
  }
  return val;
}

// bash completion
users.completion = function (opts, cb) {
  var argv = opts.conf.argv.remain;
  if (argv[1] !== "admin-users") argv.unshift("admin-users");
  if (argv.length === 2) {
    var cmds = ["list", "read", "create", "update", "delete", "enable", "disable", "changeroles", "changeauthpolicies", "listdevices", "listinstallapps" /*, "addgroups", "removegroups" */];
    if (opts.partialWord !== "l") cmds.push("list");
    return cb(undefined, cmds);
  }

};
<|endoftext|>


<commit_before>var expect = require('chai').expect,
  launcher = require('./helpers/launcher.js'),
  DebuggerAgent = require('../lib/DebuggerAgent.js').DebuggerAgent;

describe('DebuggerAgent', function() {
  after(launcher.stopAllDebuggers);

  describe('sets variable value', function() {
    before(setupDebugScenario);

    toValueType(
      'a string',
      { value: 'string-value' },
      { type: 'string', value: 'string-value', description: 'string-value' }
    );

    toValueType(
      'a number',
      { value: 10 },
      { type: 'number', value: 10, description: '10' }
    );

    toValueType(
      'null',
      { value: null },
      { type: 'null', value: null, description: 'null' }
    );

    toValueType(
      'undefined',
      { },
      { type: 'undefined', description: 'undefined' }
    );

    toRefType(
      'an object',
      'console',
      function(valueId) {
        return {
          type: 'object',
          objectId: valueId,
          className: 'Object',
          description: 'Console'
        };
      }
    );

    toRefType(
      'a function',
      'console.log',
      function(valueId) {
        return {
          type: 'function',
          objectId: valueId,
          className: 'Function',
          description: 'function () { [native code] }'
        };
      }
    );

    // helpers (implementation details) below this line

    var debuggerClient, agent;

    function setupDebugScenario(done) {
      launcher.runOnBreakInFunction(function(client) {
        debuggerClient = client;
        agent = new DebuggerAgent({}, null, debuggerClient, null, null);
        done();
      });
    }

    function to(type, test) {
      it('to ' + type, test);
    }

    function toValueType(type, newValue, expectedResult) {
      to(type, function(done) {
        verifyVariableSetter(
          agent,
          newValue,
          expectedResult,
          done
        );
      });
    }

    function toRefType(type, newValueExpression, expectedResultCb) {
      to(type, function(done) {
        debuggerClient.fetchObjectId(agent, newValueExpression, function(valueId) {
          verifyVariableSetter(
            agent,
            { handle: valueId },
            expectedResultCb(valueId),
            done
          );
        });
      });
    }

    function verifyVariableSetter(agent, newValue, expectedResult, done) {
      agent.setVariableValue(
        {
          scopeNumber: '0',
          callFrameId: '0',
          variableName: 'meta',
          newValue: newValue
        },
        function(err, result) {
          if (!DebuggerAgent.nodeVersionHasSetVariableValue(process.version)) {
            expect(err)
              .to.have.string('does not support setting variable value');
            done();
            return;
          }

          if (err) throw err;

          verifyVariableValue(
            agent,
            'meta',
            expectedResult,
            done);
        }
      );
    }

    function verifyVariableValue(agent,
                                 name,
                                 expectedValue,
                                 callback) {
      agent.evaluateOnCallFrame(
        {
          callFrameId: 0,
          expression: name
        },
        function(err, result) {
          if (err) throw err;

          expect(JSON.stringify(result.result), name)
            .to.equal(JSON.stringify(expectedValue));
          callback();
        }
      );
    }
  });

  describe('nodeVersionHasSetVariableValue', function() {
    it('returns false for v0.8.20', function(done) {
      expect(DebuggerAgent.nodeVersionHasSetVariableValue('v0.8.20'))
        .to.be.false;
      done();
    });

    it('returns false for v0.10.11', function(done) {
      expect(DebuggerAgent.nodeVersionHasSetVariableValue('v0.10.11'))
        .to.be.false;
      done();
    });

    it('returns true for v0.10.12', function(done) {
      expect(DebuggerAgent.nodeVersionHasSetVariableValue('v0.10.12'))
        .to.be.true;
      done();
    });

    it('returns false for v0.11.1', function(done) {
      expect(DebuggerAgent.nodeVersionHasSetVariableValue('v0.11.1'))
        .to.be.false;
      done();
    });

    it('returns true for v0.11.2', function(done) {
      expect(DebuggerAgent.nodeVersionHasSetVariableValue('v0.11.2'))
        .to.be.true;
      done();
    });

    it('returns true for v0.12.0', function(done) {
      expect(DebuggerAgent.nodeVersionHasSetVariableValue('v0.12.0'))
        .to.be.true;
      done();
    });

    it('returns true for v1.0.0', function(done) {
      expect(DebuggerAgent.nodeVersionHasSetVariableValue('v1.0.0'))
        .to.be.true;
      done();
    });
  });

  describe('canGetStringValuesLargerThan80Chars', function() {
    before(setupDebugScenario);

    it('returns large String values of 10000', function(done) {
      var testExpression = "Array(10000).join('a');";
      var expectedValue = Array(10000).join('a');

      agent.evaluateOnCallFrame(
        {
          callFrameId: 0,
          expression: testExpression
        },
        function(err, data) {
          if (err) throw err;

          expect(data.result.value)
            .to.equal(expectedValue);

          done();
        }
      );
    });

    var debuggerClient, agent;

    function setupDebugScenario(done) {
      launcher.runOnBreakInFunction(function(client) {
        debuggerClient = client;
        agent = new DebuggerAgent({}, null, debuggerClient, null, null);
        done();
      });
    }
  });

  describe('canResumeScriptExecutionWithoutError', function() {
    before(setupDebugScenario);

    it('resumes without error', function(done) {
      expect(function () { agent.resume(); })
        .to.not.throw();

      done();
    });

    var debuggerClient, agent;

    function setupDebugScenario(done) {
      launcher.runOnBreakInFunction(function(client) {
        debuggerClient = client;
        agent = new DebuggerAgent({}, null, debuggerClient, null, null);
        done();
      });
    }
  });
});
<commit_msg>test: improved describe/it names<commit_after>var expect = require('chai').expect,
  launcher = require('./helpers/launcher.js'),
  DebuggerAgent = require('../lib/DebuggerAgent.js').DebuggerAgent;

describe('DebuggerAgent', function() {
  after(launcher.stopAllDebuggers);

  describe('sets variable value', function() {
    before(setupDebugScenario);

    toValueType(
      'a string',
      { value: 'string-value' },
      { type: 'string', value: 'string-value', description: 'string-value' }
    );

    toValueType(
      'a number',
      { value: 10 },
      { type: 'number', value: 10, description: '10' }
    );

    toValueType(
      'null',
      { value: null },
      { type: 'null', value: null, description: 'null' }
    );

    toValueType(
      'undefined',
      { },
      { type: 'undefined', description: 'undefined' }
    );

    toRefType(
      'an object',
      'console',
      function(valueId) {
        return {
          type: 'object',
          objectId: valueId,
          className: 'Object',
          description: 'Console'
        };
      }
    );

    toRefType(
      'a function',
      'console.log',
      function(valueId) {
        return {
          type: 'function',
          objectId: valueId,
          className: 'Function',
          description: 'function () { [native code] }'
        };
      }
    );

    // helpers (implementation details) below this line

    var debuggerClient, agent;

    function setupDebugScenario(done) {
      launcher.runOnBreakInFunction(function(client) {
        debuggerClient = client;
        agent = new DebuggerAgent({}, null, debuggerClient, null, null);
        done();
      });
    }

    function to(type, test) {
      it('to ' + type, test);
    }

    function toValueType(type, newValue, expectedResult) {
      to(type, function(done) {
        verifyVariableSetter(
          agent,
          newValue,
          expectedResult,
          done
        );
      });
    }

    function toRefType(type, newValueExpression, expectedResultCb) {
      to(type, function(done) {
        debuggerClient.fetchObjectId(agent, newValueExpression, function(valueId) {
          verifyVariableSetter(
            agent,
            { handle: valueId },
            expectedResultCb(valueId),
            done
          );
        });
      });
    }

    function verifyVariableSetter(agent, newValue, expectedResult, done) {
      agent.setVariableValue(
        {
          scopeNumber: '0',
          callFrameId: '0',
          variableName: 'meta',
          newValue: newValue
        },
        function(err, result) {
          if (!DebuggerAgent.nodeVersionHasSetVariableValue(process.version)) {
            expect(err)
              .to.have.string('does not support setting variable value');
            done();
            return;
          }

          if (err) throw err;

          verifyVariableValue(
            agent,
            'meta',
            expectedResult,
            done);
        }
      );
    }

    function verifyVariableValue(agent,
                                 name,
                                 expectedValue,
                                 callback) {
      agent.evaluateOnCallFrame(
        {
          callFrameId: 0,
          expression: name
        },
        function(err, result) {
          if (err) throw err;

          expect(JSON.stringify(result.result), name)
            .to.equal(JSON.stringify(expectedValue));
          callback();
        }
      );
    }
  });

  describe('nodeVersionHasSetVariableValue', function() {
    it('returns false for v0.8.20', function(done) {
      expect(DebuggerAgent.nodeVersionHasSetVariableValue('v0.8.20'))
        .to.be.false;
      done();
    });

    it('returns false for v0.10.11', function(done) {
      expect(DebuggerAgent.nodeVersionHasSetVariableValue('v0.10.11'))
        .to.be.false;
      done();
    });

    it('returns true for v0.10.12', function(done) {
      expect(DebuggerAgent.nodeVersionHasSetVariableValue('v0.10.12'))
        .to.be.true;
      done();
    });

    it('returns false for v0.11.1', function(done) {
      expect(DebuggerAgent.nodeVersionHasSetVariableValue('v0.11.1'))
        .to.be.false;
      done();
    });

    it('returns true for v0.11.2', function(done) {
      expect(DebuggerAgent.nodeVersionHasSetVariableValue('v0.11.2'))
        .to.be.true;
      done();
    });

    it('returns true for v0.12.0', function(done) {
      expect(DebuggerAgent.nodeVersionHasSetVariableValue('v0.12.0'))
        .to.be.true;
      done();
    });

    it('returns true for v1.0.0', function(done) {
      expect(DebuggerAgent.nodeVersionHasSetVariableValue('v1.0.0'))
        .to.be.true;
      done();
    });
  });

  describe('evaluateOnCallFrame', function() {
    before(setupDebugScenario);

    it('truncates String values at 10,000 characters', function(done) {
      var testExpression = "Array(10000).join('a');";
      var expectedValue = Array(10000).join('a');

      agent.evaluateOnCallFrame(
        {
          callFrameId: 0,
          expression: testExpression
        },
        function(err, data) {
          if (err) throw err;

          expect(data.result.value)
            .to.equal(expectedValue);

          done();
        }
      );
    });

    var debuggerClient, agent;

    function setupDebugScenario(done) {
      launcher.runOnBreakInFunction(function(client) {
        debuggerClient = client;
        agent = new DebuggerAgent({}, null, debuggerClient, null, null);
        done();
      });
    }
  });

  describe('resume()', function() {
    before(setupDebugScenario);

    it('does not throw an error', function(done) {
      expect(function () { agent.resume(); })
        .to.not.throw();

      done();
    });

    var debuggerClient, agent;

    function setupDebugScenario(done) {
      launcher.runOnBreakInFunction(function(client) {
        debuggerClient = client;
        agent = new DebuggerAgent({}, null, debuggerClient, null, null);
        done();
      });
    }
  });
});
<|endoftext|>


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

var config = require('./config.js').consumer;
var dataSrv = require('./DataSrv');
var dataSrvBl = require('./DataSrvBlocking');

var app = express.createServer();

app.get('/block/:id', function (req, res) {
        "use strict";

        var queue_id = req.param("id");
        var max_msgs = req.param("max", config.max_messages);
        console.log("Blocking: "+queue_id + ", " + max_msgs);

        dataSrvBl.blocking_pop({id:queue_id}, max_msgs, config.pop_timeout, function (err, notif) {
            if (err) {
                res.send(String(err), 500);
            }
            else {
                var message = notif && notif[1] ? notif[1] : null;
                res.send(message);
            }
        });
    }
);

app.get('/:id', function (req, res) {
        "use strict";

        var queue_id = req.param("id");
        var max_msgs = req.param("max", config.max_messages);
        console.log(queue_id + ", " + max_msgs);

        dataSrv.pop_notification({id:queue_id}, max_msgs, function (err, notif_list) {
            if (err) {
                res.send(String(err), 500);
            }
            else {
                var message_list = notif_list.map(function (notif) {
                    return notif.payload;
                });
                message_list.reverse();
                res.send(message_list);
            }
        });
    }
);

app.listen(config.port);
<commit_msg>change the module for blocking pop<commit_after>var express = require('express');

var config = require('./config.js').consumer;
var dataSrv = require('./DataSrv');
var dataSrvBl = require('./DataSrvBlocking');

var app = express.createServer();

app.get('/block/:id', function (req, res) {
        "use strict";

        var queue_id = req.param("id");
        var max_msgs = req.param("max", config.max_messages);
        console.log("Blocking: "+queue_id + ", " + max_msgs);

        dataSrv.blocking_pop({id:queue_id}, max_msgs, config.pop_timeout, function (err, notif) {
            if (err) {
                res.send(String(err), 500);
            }
            else {
                var message = notif && notif[1] ? notif[1] : null;
                res.send(message);
            }
        });
    }
);

app.get('/:id', function (req, res) {
        "use strict";

        var queue_id = req.param("id");
        var max_msgs = req.param("max", config.max_messages);
        console.log(queue_id + ", " + max_msgs);

        dataSrv.pop_notification({id:queue_id}, max_msgs, function (err, notif_list) {
            if (err) {
                res.send(String(err), 500);
            }
            else {
                var message_list = notif_list.map(function (notif) {
                    return notif.payload;
                });
                message_list.reverse();
                res.send(message_list);
            }
        });
    }
);

app.listen(config.port);
<|endoftext|>


<commit_before>(function(){
	var perPage = 10;
	var menu = document.getElementById("menu");

	// initialise article list
	var articles = new List("content", {
		valueNames: ["title_link", "title_text", "date", "href", "content", "readmore", "readmore-link", "category"],
		listClass: "list",
		searchClass: "search",
		sortFunction: function(a, b, options) {
			m = (options.order == "desc") ? 1 : -1;
			if (a._values.date == "") return -m;
			if (b._values.date == "") return m;
			return m * b._values.date.localeCompare(a._values.date);
		}
	});
	// limit display to 11 articles and hope the pagination will work
	articles.show(1, 11);

	// fill up the article list
	var getjson = new XMLHttpRequest();
	getjson.onreadystatechange = function() {
		if (getjson.readyState == 4 && getjson.status == 200) {
			var articles = JSON.parse(getjson.responseText);
			addArticles(articles);
		}
	}
	getjson.open("GET", '/articles.json', true);
	getjson.send();

	function addArticles(data) {
		// Add the articles to listjs and redo pagination
		articles.show(1, articles.size());
		for(i=0, len=data.length; i<len; i++) {
			if (articles.get('href', data[i].href).length == 0) {
				articles.add(data[i]);
			}
		}
		navigate(true);
	}

	function showArticle(href) {
		matches = articles.get("href", href);
		if (matches.length == 0) return false;
		var article = matches[0].values();
		document.getElementById("list").style.display = "none";
		document.getElementById("pagination").style.display = "none";
		var full_article = document.getElementById("full-article");
		full_article.innerHTML = "
" + article.title_text + "

" + article.content + article.readmore + "
";
		full_article.style.display = "block";
	}

	function showCategory(category, page) {
		if (page === undefined) page = 1;
		articles.sort("date", {order: "desc"});
		articles.filter(function(item) {
			if (category == "accueil" || item.values().category == category) {
				return true;
			}
			return false;
		});
		articles.show(10 * (page - 1) + 1 + (page==1?0:1), (page==1?perPage+1:perPage));
		document.getElementById("list").style.display = "block";
		document.getElementById("pagination").style.display = "block";
		document.getElementById("full-article").style.display = "none";
		makePagination(category, page);
	}

	function makePagination(category, page) {
		var pagination = document.getElementById("pagination");
		if (pagination !== null) {
			pagination.innerHTML = "";
		} else {
			document.getElementById("content-column").innerHTML += '

';
			pagination = document.getElementById("pagination");
		}

		if (category == "accueil") {
			var total = articles.size();
		} else {
			var total = articles.get("category", category).length;
		}
		//console.log(total);

		href = location.href;
		pos = href.indexOf("/page/");
		if (pos >= 0) {
			href = href.substr(0, pos);
		} else if (category != "accueil") {
			href += "?";
			total = total - 1; // the extra article on the front page
		}
		if (href.substr(-1) != "/") href += "/";
		href += "page/";
		//console.log(href);
		//console.log(total);

		var links = "";
		if (page > 1) {
			// make prev link
			links += '< Articles précédents';
		}
		if (page < total/perPage) {
			// make next link
			links += ' Articles suivants >';
		}

		pagination.innerHTML = links;
	}

	navigate = function(noscroll) {
		var bits = location.href.split("/");
		var categ = "";
		url = "";
		bits.splice(0, 3);
		if (bits.length > 1) { // article asked for
			categ = bits[0];
			if (categ.match(/^[0-9]{4}$/)) categ = "";
			url = "/" + bits.join("/");
		}
		else { // category list asked for
			if (bits[0] == "page") { //accueil
				categ = "";
				page = bits.length > 1 ? bits[1] : 1;
			}
			else { //category/?/page/x
				categ = bits[0];
				page = bits.length > 3 ? bits[3] : 1;
			}
		}
		if (categ == "") categ = "accueil";

		if (url) {
			showArticle(url);
		}
		else {
			showCategory(categ, page);
		}

		var links = menu.getElementsByTagName("a");
		for(i = 0, len = links.length; i < len; i++) {
			links[i].className = ""; // remove "active";
		}
		//console.log(categ);
		document.getElementById(categ).className = "active";

		if (noscroll !== true) menu.scrollIntoView(true);

		return true;
	};
	window.addEventListener('popstate', navigate, false);

	// site navigation
	document.addEventListener("click", linkClick, true);
	function linkClick(e){
		link = e.target;
		if(link.nodeType != 1 || link.tagName.toLowerCase() !="a") return true;
		var href = link.href;

		var local = false;
		// don't try treating these links
		if (href.substr(0, 7) == "mailto:") return true;
		if (href.substr(0, 4) == "tel:") return true;

		if (href.substr(0, 7) == "http://" || href.substr(0, 8) == "https://" || href.substr(0, 2) == "//") {
			var server = location.href.split('/')[2];
			if (href.indexOf(server) >= 0) local = true;
		}
		if (local) {
			if (href.split("?")[0].substr(-4).toLowerCase() == ".pdf") {
				if (!link.hasAttribute("target")) {
					link.setAttribute("target", "_blank");

					// Cancel action and regenerate a click - otherwise the target attribute isn't used
					if (document.createEvent) { // Firefox
						var event = document.createEvent("MouseEvents");
						event.initEvent("click", true, true);
						link.dispatchEvent(event);
					}	else if (link.click) { // IE
						link.click();
					} else {
						console.log("no click method");
						return true;
					}
					e.preventDefault();
					return false;
				}
			} else {
				e.preventDefault();
				//$.scrollTo('#content', 800);
				history.pushState(null, null, href);
				navigate();
				return false;
			}
		} else {
			if (!link.hasAttribute("target")) {
				link.setAttribute("target", "_blank");

				// Cancel action and regenerate a click - otherwise the target attribute isn't used
				if (document.createEvent) { // Firefox
					var event = document.createEvent("MouseEvents");
					event.initEvent("click", true, true);
					link.dispatchEvent(event);
				}	else if (link.click) { // IE
					link.click();
				} else {
					console.log("no click method");
					return true;
				}
				e.preventDefault();
				return false;
			}
		}
	};

	// give searches the full list
	document.getElementById("do-search").addEventListener("click", searchFullList, false);
	document.getElementById("search-input").addEventListener("keyup", searchFullList, false);
	document.getElementById("search-input").addEventListener("input", searchFullList, false);

	function searchFullList(e) {
		if (e.type !== 'keyup' || e.which === 13) {
			history.pushState(null, null, "/");
			navigate();
		};
	};

})();

// Audio
(function(){
	var player = document.getElementById("audio-player");
	var progress = document.getElementById("audio-progress");
	var button = document.getElementById("playpause");
	var duration = 0;

	// control button
	button.addEventListener("click", playpause, false);
	function playpause() {
		if (player.paused) {
			player.play();
			button.style.backgroundPosition = "0% 100%";
		} else {
			player.pause();
			button.style.backgroundPosition = "0% 0%";
		}
	}

	// audio progress display
	player.addEventListener("canplaythrough", function () {
		duration = player.duration;
	}, false);

	player.addEventListener("timeupdate", updateProgress, false);
	function updateProgress() {
		if (duration == 0) duration = player.duration;
		var playPercent = 100 * (player.currentTime / duration);
		progress.style.backgroundPosition = (100 - playPercent) + "% 0%";
	};

	// navigation
	function play(which) {
		var list = document.getElementById("audio-list").children;
		var len = list.length;
		var current = undefined;
		for (i = 0; i < len; i++) {
			if (list[i].className == "playing") current = i;
		}
		if (current == undefined) return;
		if (which == "prev") {
			next = current - 1;
			if (next < 0) next = len - 1;
		} else {
			next = current + 1;
			if (next > len - 1) next = 0;
		}
		playpause();
		list[current].className = ""; // remove "playing"
		list[next].className = "playing";
		player.src = list[next].getElementsByClassName("audio-link")[0].href;
		playpause();
	}

	player.addEventListener("ended", function() {
		play("next");
	}, false);

	document.getElementById("audio-next").addEventListener("click", function(e) {
		play("next");
		return false;
	}, false);

	document.getElementById("audio-prev").addEventListener("click", function(e) {
		play("prev");
		return false;
	}, false);

	// seeking
	progress.addEventListener("click", function (e) {
		if(e.offsetX == undefined) { // this works for Firefox
			var xpos = e.pageX-progress.offsetLeft;
			if (obj = progress.offsetParent) {
				do {
					xpos -= obj.offsetLeft;
				} while (obj = obj.offsetParent);
			}
		} else {										 // works in Google Chrome
			var xpos = e.offsetX;
		}
		var percent = xpos / e.target.clientWidth;
		player.pause();
		player.currentTime = player.duration * percent;
		player.play();
		updateProgress();
	}, false);

	// visibility detection
	function getHiddenProp(){
    if ('hidden' in document) return 'hidden';

    var prefixes = ['webkit','moz','ms','o'];
    for (var i = 0; i < prefixes.length; i++){
			if ((prefixes[i] + 'Hidden') in document)
				return prefixes[i] + 'Hidden';
    }

    return null;
	}
	function isHidden() {
    var prop = getHiddenProp();
    if (!prop) return false;

    return document[prop];
	}
	var visProp = getHiddenProp();
	if (visProp) var visEvent = visProp.replace(/[H|h]idden/,'') + 'visibilitychange';
	function visChange() {
		if (!isHidden()) {
			// play and remove visEvent
			playpause();
			document.removeEventListener(visEvent, visChange);
		}
	}

	if (!isHidden()) {
		playpause();
	} else { // use the property name to generate the prefixed event name
		document.addEventListener(visEvent, visChange);
	}
})();<commit_msg>Corriger navigation des catégories<commit_after>(function(){
	var perPage = 10;
	var menu = document.getElementById("menu");

	// initialise article list
	var articles = new List("content", {
		valueNames: ["title_link", "title_text", "date", "href", "content", "readmore", "readmore-link", "category"],
		listClass: "list",
		searchClass: "search",
		sortFunction: function(a, b, options) {
			m = (options.order == "desc") ? 1 : -1;
			if (a._values.date == "") return -m;
			if (b._values.date == "") return m;
			return m * b._values.date.localeCompare(a._values.date);
		}
	});
	// limit display to 11 articles and hope the pagination will work
	articles.show(1, 11);

	// fill up the article list
	var getjson = new XMLHttpRequest();
	getjson.onreadystatechange = function() {
		if (getjson.readyState == 4 && getjson.status == 200) {
			var articles = JSON.parse(getjson.responseText);
			addArticles(articles);
		}
	}
	getjson.open("GET", '/articles.json', true);
	getjson.send();

	function addArticles(data) {
		// Add the articles to listjs and redo pagination
		articles.show(1, articles.size());
		for(i=0, len=data.length; i<len; i++) {
			if (articles.get('href', data[i].href).length == 0) {
				articles.add(data[i]);
			}
		}
		navigate(true);
	}

	function showArticle(href) {
		matches = articles.get("href", href);
		if (matches.length == 0) return false;
		var article = matches[0].values();
		document.getElementById("list").style.display = "none";
		document.getElementById("pagination").style.display = "none";
		var full_article = document.getElementById("full-article");
		full_article.innerHTML = "
" + article.title_text + "

" + article.content + article.readmore + "
";
		full_article.style.display = "block";
	}

	function showCategory(category, page) {
		if (page === undefined) page = 1;
		articles.sort("date", {order: "desc"});
		articles.filter(function(item) {
			if (category == "accueil" || item.values().category == category) {
				return true;
			}
			return false;
		});
		articles.show(10 * (page - 1) + 1 + (page==1?0:1), (page==1?perPage+1:perPage));
		document.getElementById("list").style.display = "block";
		document.getElementById("pagination").style.display = "block";
		document.getElementById("full-article").style.display = "none";
		makePagination(category, page);
	}

	function makePagination(category, page) {
		var pagination = document.getElementById("pagination");
		if (pagination !== null) {
			pagination.innerHTML = "";
		} else {
			document.getElementById("content-column").innerHTML += '

';
			pagination = document.getElementById("pagination");
		}

		if (category == "accueil") {
			var total = articles.size();
		} else {
			var total = articles.get("category", category).length;
		}
		//console.log(total);

		href = location.href;
		pos = href.indexOf("/page/");
		if (pos >= 0) {
			href = href.substr(0, pos);
		} else if (category != "accueil") {
			href += "?";
			total = total - 1; // the extra article on the front page
		}
		if (href.substr(-1) != "/") href += "/";
		href += "page/";
		//console.log(href);
		//console.log(total);

		var links = "";
		if (page > 1) {
			// make prev link
			links += '< Articles précédents';
		}
		if (page < total/perPage) {
			// make next link
			links += ' Articles suivants >';
		}

		pagination.innerHTML = links;
	}

	navigate = function(noscroll) {
		var bits = location.href.split("/");
		var categ = "";
		url = "";
		bits.splice(0, 3);
		//console.log(bits);
		if (bits.length > 1 && bits[1].length > 0) { // article asked for
			//console.log("post");
			categ = bits[0];
			if (categ.match(/^[0-9]{4}$/)) categ = "";
			url = "/" + bits.join("/");
		}
		else { // category list asked for
			//console.log("cat");
			if (bits[0] == "page") { //accueil
				categ = "";
				page = bits.length > 1 ? bits[1] : 1;
			}
			else { //category/?/page/x
				categ = bits[0];
				page = bits.length > 3 ? bits[3] : 1;
			}
		}
		//console.log(categ);
		if (categ == "") categ = "accueil";

		if (url) {
			showArticle(url);
		}
		else {
			showCategory(categ, page);
		}

		var links = menu.getElementsByTagName("a");
		for(i = 0, len = links.length; i < len; i++) {
			links[i].className = ""; // remove "active";
		}
		//console.log(categ);
		document.getElementById(categ).className = "active";

		if (noscroll !== true) menu.scrollIntoView(true);

		return true;
	};
	window.addEventListener('popstate', navigate, false);

	// site navigation
	document.addEventListener("click", linkClick, true);
	function linkClick(e){
		link = e.target;
		if(link.nodeType != 1 || link.tagName.toLowerCase() !="a") return true;
		var href = link.href;

		var local = false;
		// don't try treating these links
		if (href.substr(0, 7) == "mailto:") return true;
		if (href.substr(0, 4) == "tel:") return true;

		if (href.substr(0, 7) == "http://" || href.substr(0, 8) == "https://" || href.substr(0, 2) == "//") {
			var server = location.href.split('/')[2];
			if (href.indexOf(server) >= 0) local = true;
		}
		if (local) {
			if (href.split("?")[0].substr(-4).toLowerCase() == ".pdf") {
				if (!link.hasAttribute("target")) {
					link.setAttribute("target", "_blank");

					// Cancel action and regenerate a click - otherwise the target attribute isn't used
					if (document.createEvent) { // Firefox
						var event = document.createEvent("MouseEvents");
						event.initEvent("click", true, true);
						link.dispatchEvent(event);
					}	else if (link.click) { // IE
						link.click();
					} else {
						//console.log("no click method");
						return true;
					}
					e.preventDefault();
					return false;
				}
			} else {
				e.preventDefault();
				//$.scrollTo('#content', 800);
				history.pushState(null, null, href);
				navigate();
				return false;
			}
		} else {
			if (!link.hasAttribute("target")) {
				link.setAttribute("target", "_blank");

				// Cancel action and regenerate a click - otherwise the target attribute isn't used
				if (document.createEvent) { // Firefox
					var event = document.createEvent("MouseEvents");
					event.initEvent("click", true, true);
					link.dispatchEvent(event);
				}	else if (link.click) { // IE
					link.click();
				} else {
					//console.log("no click method");
					return true;
				}
				e.preventDefault();
				return false;
			}
		}
	};

	// give searches the full list
	document.getElementById("do-search").addEventListener("click", searchFullList, false);
	document.getElementById("search-input").addEventListener("keyup", searchFullList, false);
	document.getElementById("search-input").addEventListener("input", searchFullList, false);

	function searchFullList(e) {
		if (e.type !== 'keyup' || e.which === 13) {
			history.pushState(null, null, "/");
			navigate();
		};
	};

})();

// Audio
(function(){
	var player = document.getElementById("audio-player");
	var progress = document.getElementById("audio-progress");
	var button = document.getElementById("playpause");
	var duration = 0;

	// control button
	button.addEventListener("click", playpause, false);
	function playpause() {
		if (player.paused) {
			player.play();
			button.style.backgroundPosition = "0% 100%";
		} else {
			player.pause();
			button.style.backgroundPosition = "0% 0%";
		}
	}

	// audio progress display
	player.addEventListener("canplaythrough", function () {
		duration = player.duration;
	}, false);

	player.addEventListener("timeupdate", updateProgress, false);
	function updateProgress() {
		if (duration == 0) duration = player.duration;
		var playPercent = 100 * (player.currentTime / duration);
		progress.style.backgroundPosition = (100 - playPercent) + "% 0%";
	};

	// navigation
	function play(which) {
		var list = document.getElementById("audio-list").children;
		var len = list.length;
		var current = undefined;
		for (i = 0; i < len; i++) {
			if (list[i].className == "playing") current = i;
		}
		if (current == undefined) return;
		if (which == "prev") {
			next = current - 1;
			if (next < 0) next = len - 1;
		} else {
			next = current + 1;
			if (next > len - 1) next = 0;
		}
		playpause();
		list[current].className = ""; // remove "playing"
		list[next].className = "playing";
		player.src = list[next].getElementsByClassName("audio-link")[0].href;
		playpause();
	}

	player.addEventListener("ended", function() {
		play("next");
	}, false);

	document.getElementById("audio-next").addEventListener("click", function(e) {
		play("next");
		return false;
	}, false);

	document.getElementById("audio-prev").addEventListener("click", function(e) {
		play("prev");
		return false;
	}, false);

	// seeking
	progress.addEventListener("click", function (e) {
		if(e.offsetX == undefined) { // this works for Firefox
			var xpos = e.pageX-progress.offsetLeft;
			if (obj = progress.offsetParent) {
				do {
					xpos -= obj.offsetLeft;
				} while (obj = obj.offsetParent);
			}
		} else {										 // works in Google Chrome
			var xpos = e.offsetX;
		}
		var percent = xpos / e.target.clientWidth;
		player.pause();
		player.currentTime = player.duration * percent;
		player.play();
		updateProgress();
	}, false);

	// visibility detection
	function getHiddenProp(){
    if ('hidden' in document) return 'hidden';

    var prefixes = ['webkit','moz','ms','o'];
    for (var i = 0; i < prefixes.length; i++){
			if ((prefixes[i] + 'Hidden') in document)
				return prefixes[i] + 'Hidden';
    }

    return null;
	}
	function isHidden() {
    var prop = getHiddenProp();
    if (!prop) return false;

    return document[prop];
	}
	var visProp = getHiddenProp();
	if (visProp) var visEvent = visProp.replace(/[H|h]idden/,'') + 'visibilitychange';
	function visChange() {
		if (!isHidden()) {
			// play and remove visEvent
			playpause();
			document.removeEventListener(visEvent, visChange);
		}
	}

	if (!isHidden()) {
		playpause();
	} else { // use the property name to generate the prefixed event name
		document.addEventListener(visEvent, visChange);
	}
})();<|endoftext|>


<commit_before>define(function () {
    return {
        spiralSort: function(array) {
            var len = array.length,
                bottomBound = len,
                col = 0,
                leftBound = 0,
                rightBound = len,
                row = 0,
                sorted = [],
                topBound = 0;

            for (var i = 0; i < len-i; i++) {
                while (col < rightBound) {
                    if (array[row][col]) {
                        sorted.push(array[row][col]);
                    }
                    col++;
                }
                col--;
                row++;
                while (row < bottomBound) {
                    sorted.push(array[row][col]);
                    row++;
                }
                col--;
                row--;
                bottomBound--;
                while (col >= leftBound) {
                    sorted.push(array[row][col]);
                    col--;
                }
                row--;
                col++;
                leftBound++;
                topBound++;
                while (row >= topBound) {
                    sorted.push(array[row][col]);
                    row--;
                }
                row++;
                col++;
                rightBound--;
            }
            return sorted;
        }
    };
});
<commit_msg>spiral sort refactor<commit_after>define(function () {
    return {
        spiralSort: function(array) {
            var len = array.length,
                bounds = {
                    xMin: 0,
                    yMin: 0,
                    xMax: len -1,
                    yMax: len -1
                },
                col = 0,
                row = 0,
                direction = 'right',
                sorted = [];

            for (var i = 0; i < len*len; i++) {
                if (array[row][col]) {
                    sorted.push(array[row][col]);
                }

                // Directional cases
                switch(direction) {
                    case 'right':
                        if (col == bounds.xMax) {
                            direction = 'down';
                            row++;
                            bounds.xMax--;
                            bounds.yMin++;
                        } else {
                            col++;
                        }
                        break;
                    case 'down':
                        if (row == bounds.yMax) {
                            direction = 'left';
                            col--;
                            bounds.yMax--;
                        } else {
                            row++;
                        }
                        break;
                    case 'left':
                        if (col == bounds.xMin) {
                            direction = 'up';
                            row--;
                            bounds.xMin++;
                        } else {
                            col--;
                        }
                        break;
                    case 'up':
                        if (row == bounds.yMin) {
                            direction = 'right';
                            col++;
                            bounds.yMin++;
                        } else {
                            row--;
                        }
                        break;
                }
            }
            return sorted;
        }
    };
});
<|endoftext|>


<commit_before>/* Base component class. */
import { getElement, append, getOuterHTMLText } from '../modules/ui';
import { doRedBorderAnimation } from '../modules/action-class-names';

export default class Component {
	constructor(id = '', parent = null, nodeType = 'div', content = '') {
		// this id when binding might already be specified
		this.id = id;
		this.parent = parent;
		this.nodeType = nodeType;
		this.$node = $(`<${nodeType} id='${id}'>${content}</${nodeType}>`);

		if (parent) {
			append($(parent), this.$node);
		}
	}

	addClasses(classes = '') {
		this.html().addClass(classes);
	}

	addCSS(cssProps = {}) {
		this.html().css(cssProps);
	}

	bind(container = '') {
		let myTarget = this.id;

		this.parent = container;
		if (typeof container !== 'string') {
			myTarget = this.$node;
		}

		append($(container), $(myTarget));
	}

	html() {
		return this.$node;
	}

	rawHtml() {
		return getOuterHTMLText(this.html());
	}

	appendChild(component) {
		if (component instanceof Component) {
			append(this.html(), component.html());
			component.parent = this.id;
		}
	}

	appendHtml(html) {
		append(this.html(), html);
	}

	init() {
		this._buildTemplate();
	}

	update(props) {
		const { id, parent, $node, nodeType } = props;

		this.id = id ? id : this.id;
		this.parent = parent ? parent : this.parent;
		this.nodeType = nodeType ? nodeType : this.nodeType;
		this.$node = $node ? $node : this.$node;
	}

	hideFromDom() {
		this.html().css('display', 'none');
	}

	showInDom() {
		this.html().css('display', 'block');
	}

	doToggleAnimation(childElementSelector = null, animation = doRedBorderAnimation) {
		const myNode = this.$node;
		return childElementSelector ? myNode.children(childElementSelector).toggleClass(animation) : this.$node.toggleClass(doRedBorderAnimation);
	}
}
<commit_msg>Use myNode variable for animation<commit_after>/* Base component class. */
import { getElement, append, getOuterHTMLText } from '../modules/ui';
import { doRedBorderAnimation } from '../modules/action-class-names';

export default class Component {
	constructor(id = '', parent = null, nodeType = 'div', content = '') {
		// this id when binding might already be specified
		this.id = id;
		this.parent = parent;
		this.nodeType = nodeType;
		this.$node = $(`<${nodeType} id='${id}'>${content}</${nodeType}>`);

		if (parent) {
			append($(parent), this.$node);
		}
	}

	addClasses(classes = '') {
		this.html().addClass(classes);
	}

	addCSS(cssProps = {}) {
		this.html().css(cssProps);
	}

	bind(container = '') {
		let myTarget = this.id;

		this.parent = container;
		if (typeof container !== 'string') {
			myTarget = this.$node;
		}

		append($(container), $(myTarget));
	}

	html() {
		return this.$node;
	}

	rawHtml() {
		return getOuterHTMLText(this.html());
	}

	appendChild(component) {
		if (component instanceof Component) {
			append(this.html(), component.html());
			component.parent = this.id;
		}
	}

	appendHtml(html) {
		append(this.html(), html);
	}

	init() {
		this._buildTemplate();
	}

	update(props) {
		const { id, parent, $node, nodeType } = props;

		this.id = id ? id : this.id;
		this.parent = parent ? parent : this.parent;
		this.nodeType = nodeType ? nodeType : this.nodeType;
		this.$node = $node ? $node : this.$node;
	}

	hideFromDom() {
		this.html().css('display', 'none');
	}

	showInDom() {
		this.html().css('display', 'block');
	}

	doToggleAnimation(childElementSelector = null, animation = doRedBorderAnimation) {
		const myNode = this.$node;
		return childElementSelector
			? myNode.children(childElementSelector).toggleClass(animation)
			: myNode.toggleClass(doRedBorderAnimation);
	}
}
<|endoftext|>