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

/*
* Name : lineChartFlow.js
* Module : Lib::BusinessTier::LineChartFlow
* Location : /lib/businessTier/flow
*
* History :
*
* Version   Date         Programmer         Description
* =========================================================
* 0.0.1     2015-05-25   Filippo Rampado    Initial code
* =========================================================
*/

var BarChartFlowModel=require('../../dataTier/flow/barChartFlowModel.js');
var Flow=require('./flow.js');

function BarChartFlow(params, graphSocket, records) {
	if (graphSocket===undefined || !(graphSocket.hasOwnProperty('_namespace'))){
		console.log('Error: 201');
		return;
	}
	var bc=new BarChartFlowModel(params, records);
	if (!bc.hasOwnProperty('_ID')){
		return;
	}
	this.parent.constructor.call(this, graphSocket);
	this._dataBarChartFlow=bc;
}

BarChartFlow.prototype = Object.create(Flow.prototype);
BarChartFlow.prototype.constructor = Flow;
BarChartFlow.prototype.parent = Flow.prototype;

BarChartFlow.prototype.updateRecord = function(index, record){
	if ((index===undefined)||(typeof index !== 'number')||(index >= this._dataBarChartFlow._records.length || index < 0)){
		return 112;
	}
	var oldValid=this._dataBarChartFlow.getRecordByIndex(index).norrisRecordIsValid;
	var res=this._dataBarChartFlow.updateRecord(index, record);
	var newValid=this._dataBarChartFlow.getRecordByIndex(index).norrisRecordIsValid;
	if (res===true ){
		if (oldValid && !newValid){
            /*console.dir('Printing record ID');
            console.dir(this._dataBarChartFlow.getRecordByIndex(index).norrisRecordID);*/
			var data={
				action: 'deleteRecord',
				ID: this._dataBarChartFlow._ID,
				norrisRecordID: this._dataBarChartFlow.getRecordByIndex(index).norrisRecordID
			};
			this._graphSocket.sendMessage('updateFlowData', data);
		}
		if (newValid){
			var indexKey=this._dataBarChartFlow._indexKey;
			var valueKey=this._dataBarChartFlow._valueKey;
			var newValue=[null, null];
			if (record[indexKey]!==undefined && typeof record[indexKey]==='number' && record[valueKey]!==undefined && typeof record[valueKey]==='number'){
				newValue=[record[indexKey], record[valueKey]];
			}
			if (!oldValid){
				var data2={
					action: 'insertRecords',
					ID: this._dataBarChartFlow._ID,
					records: [{
						norrisRecordID: this._dataBarChartFlow.getRecordByIndex(index).norrisRecordID,
						value: newValue
					}]
				};
				this._graphSocket.sendMessage('updateFlowData', data2);

			}
			if (oldValid){
				var data3={
					action: 'updateRecord',
					ID: this._dataBarChartFlow._ID,
					norrisRecordID: this._dataBarChartFlow.getRecordByIndex(index).norrisRecordID,
					value: newValue
				};
				this._graphSocket.sendMessage('updateFlowData', data3);
			}
		}
	}
	return res;
};

BarChartFlow.prototype.getReplaceDataJSON = function(){
	var records=[];
	/*for(var key in this._dataBarChartFlow._records){
		records.push({
			norrisRecordID : this._dataBarChartFlow._records[key].norrisRecordID,
			markerID: this._dataBarChartFlow._records[key][this._dataBarChartFlow._objectKey],
			value: [ //lat,long
				this._dataBarChartFlow._records[key][this._dataBarChartFlow._xKey],
				this._dataBarChartFlow._records[key][this._dataBarChartFlow._yKey]
			]
		});
	}*/
	var dataRecords=this._dataBarChartFlow._records;
	for (var i=0; i<dataRecords.length; i++){
		if (dataRecords[i].norrisRecordIsValid){
			records.push({
				norrisRecordID : dataRecords[i].norrisRecordID,
				value: [ //lat,long
					dataRecords[i][this._dataBarChartFlow._indexKey],
					dataRecords[i][this._dataBarChartFlow._valueKey]
				]
			});
		}
	}

	return {
		action: 'replaceData',
		ID: this._dataBarChartFlow._ID,
		records: records
	};
};

BarChartFlow.prototype.updateProperties = function(params){
	if (params!==undefined){
		var prop=this._dataBarChartFlow.updateProperties(params);
		prop.ID=this._dataBarChartFlow._ID;
		if (prop.filters !== undefined){//filters changed
			var indexKey=this._dataBarChartFlow._indexKey;
			var records=[];
			var recordsModel=this._dataBarChartFlow._records;
			var nRecords=this._dataBarChartFlow._records.length;
			for (var i=0; i<nRecords; i++){
				if (recordsModel[i][indexKey]!==undefined &&
				typeof recordsModel[i][indexKey]==='number'){
					if (recordsModel[i].norrisIsValid){
						records.push({
							norrisRecordID: recordsModel[i].norrisRecordID,
							markerID: params[this._dataBarChartFlow._objectKey],
							value: [recordsModel[i][indexKey]]
						});
					}
				}
			}
			this._graphSocket.sendMessage('updateFlowData', this.getReplaceDataJSON());
		}
		this._graphSocket.sendMessage('updateFlowProp', prop);
	}
};

module.exports = BarChartFlow;
<commit_msg>complete barchartflow test coverage<commit_after>/*jshint node: true, -W106 */
'use strict';

/*
* Name : lineChartFlow.js
* Module : Lib::BusinessTier::LineChartFlow
* Location : /lib/businessTier/flow
*
* History :
*
* Version   Date         Programmer         Description
* =========================================================
* 0.0.1     2015-05-25   Filippo Rampado    Initial code
* =========================================================
*/

var BarChartFlowModel=require('../../dataTier/flow/barChartFlowModel.js');
var Flow=require('./flow.js');

function BarChartFlow(params, graphSocket, records) {
	if (graphSocket===undefined || !(graphSocket.hasOwnProperty('_namespace'))){
		console.log('Error: 201');
		return;
	}
	var bc=new BarChartFlowModel(params, records);
	if (!bc.hasOwnProperty('_ID')){
		return;
	}
	this.parent.constructor.call(this, graphSocket);
	this._dataBarChartFlow=bc;
}

BarChartFlow.prototype = Object.create(Flow.prototype);
BarChartFlow.prototype.constructor = Flow;
BarChartFlow.prototype.parent = Flow.prototype;

BarChartFlow.prototype.updateRecord = function(index, record){
	if ((index===undefined)||(typeof index !== 'number')||(index >= this._dataBarChartFlow._records.length || index < 0)){
		return 112;
	}
	var oldValid=this._dataBarChartFlow.getRecordByIndex(index).norrisRecordIsValid;
	var res=this._dataBarChartFlow.updateRecord(index, record);
	var newValid=this._dataBarChartFlow.getRecordByIndex(index).norrisRecordIsValid;
	if (res===true ){
		if (oldValid && !newValid){
            /*console.dir('Printing record ID');
            console.dir(this._dataBarChartFlow.getRecordByIndex(index).norrisRecordID);*/
			var data={
				action: 'deleteRecord',
				ID: this._dataBarChartFlow._ID,
				norrisRecordID: this._dataBarChartFlow.getRecordByIndex(index).norrisRecordID
			};
			this._graphSocket.sendMessage('updateFlowData', data);
		}
		if (newValid){
			var indexKey=this._dataBarChartFlow._indexKey;
			var valueKey=this._dataBarChartFlow._valueKey;
			var newValue=[null, null];
			if (record[indexKey]!==undefined && typeof record[indexKey]==='number' && record[valueKey]!==undefined && typeof record[valueKey]==='number'){
				newValue=[record[indexKey], record[valueKey]];
			}
			if (!oldValid){
				var data2={
					action: 'insertRecords',
					ID: this._dataBarChartFlow._ID,
					records: [{
						norrisRecordID: this._dataBarChartFlow.getRecordByIndex(index).norrisRecordID,
						value: newValue
					}]
				};
				this._graphSocket.sendMessage('updateFlowData', data2);

			}
			if (oldValid){
				var data3={
					action: 'updateRecord',
					ID: this._dataBarChartFlow._ID,
					norrisRecordID: this._dataBarChartFlow.getRecordByIndex(index).norrisRecordID,
					value: newValue
				};
				this._graphSocket.sendMessage('updateFlowData', data3);
			}
		}
	}
	return res;
};

BarChartFlow.prototype.getReplaceDataJSON = function(){
	var records=[];
	/*for(var key in this._dataBarChartFlow._records){
		records.push({
			norrisRecordID : this._dataBarChartFlow._records[key].norrisRecordID,
			markerID: this._dataBarChartFlow._records[key][this._dataBarChartFlow._objectKey],
			value: [ //lat,long
				this._dataBarChartFlow._records[key][this._dataBarChartFlow._xKey],
				this._dataBarChartFlow._records[key][this._dataBarChartFlow._yKey]
			]
		});
	}*/
	var dataRecords=this._dataBarChartFlow._records;
	for (var i=0; i<dataRecords.length; i++){
		if (dataRecords[i].norrisRecordIsValid){
			records.push({
				norrisRecordID : dataRecords[i].norrisRecordID,
				value: [ //lat,long
					dataRecords[i][this._dataBarChartFlow._indexKey],
					dataRecords[i][this._dataBarChartFlow._valueKey]
				]
			});
		}
	}

	return {
		action: 'replaceData',
		ID: this._dataBarChartFlow._ID,
		records: records
	};
};

BarChartFlow.prototype.updateProperties = function(params){
	if (params!==undefined){
		var prop=this._dataBarChartFlow.updateProperties(params);
		prop.ID=this._dataBarChartFlow._ID;
		if (prop.filters !== undefined){//filters changed
			var indexKey=this._dataBarChartFlow._indexKey;
			var records=[];
			var recordsModel=this._dataBarChartFlow._records;
			var nRecords=this._dataBarChartFlow._records.length;
			for (var i=0; i<nRecords; i++){
				if (recordsModel[i][indexKey]!==undefined &&
				typeof recordsModel[i][indexKey]==='number'){
					if (recordsModel[i].norrisRecordIsValid){
						records.push({
							norrisRecordID: recordsModel[i].norrisRecordID,
							markerID: params[this._dataBarChartFlow._objectKey],
							value: [recordsModel[i][indexKey]]
						});
					}
				}
			}
			this._graphSocket.sendMessage('updateFlowData', this.getReplaceDataJSON());
		}
		this._graphSocket.sendMessage('updateFlowProp', prop);
	}
};

module.exports = BarChartFlow;
<|endoftext|>


<commit_before>var _ = require('lodash');
var ss = require('simple-statistics');
var evalculist = require('evalculist');
var isItem = require('./item/isItem');
var keyToVarName = require('./keyToVarName');

var itemMethods = ['$item', '$$item', '$siblings'];

var fnToString = _.constant('[Function]');

function ContextObject (item) {
  if (item) {
    var _this = this;
    _.each(itemMethods, function(method) {
      _this[method] = function () {
        return item[method].apply(item, arguments);
      };
      _this[method].toString = fnToString;
    });

    this.$parent = item.parent;
    this.$index = item.parent ? item.parent.items.indexOf(item) : 0;
    this.$items = item.items;
    this.$name = item.key;
  }
}

var proto = ContextObject.prototype;

var mathKeys = ['E','LN2','LN10','LOG2E','LOG10E','PI','SQRT1_2','SQRT2','abs','acos','acosh','asin','asinh','atan','atan2','atanh','cbrt','ceil','clz32','cos','cosh','exp','expm1','floor','fround','hypot','imul','log','log1p','log2','log10','max','min','pow','random','round','sign','sin','sinh','sqrt','tan','tanh','trunc'];

_.each(mathKeys, function(key) { proto[key] = Math[key]; });

var ssKeys = ['median','mode','product','variance','sampleVariance','standardDeviation','sampleStandardDeviation','medianAbsoluteDeviation','interquartileRange','harmonicMean','geometricMean','rootMeanSquare','sampleSkewness','factorial'];

_.each(ssKeys, function(key) { proto[key] = ss[key]; });

var lodashKeys = ['difference','intersection','reverse','union','uniq','xor',
                  'filter','find','findLast','map','reduce','zip','unzip',
                  'ceil','floor','max','min','round','clamp','inRange','range',
                  'camelCase','capitalize','kebabCase','lowerCase','join','split',
                  'parseInt','repeat','replace','snakeCase','split','startCase','toLower',
                  'toUpper','truncate','upperCase','words','times','identity'];
_.each(lodashKeys, function (key) { proto[key] = _[key]; });

var valIfItem = function (item) { return isItem(item) ? item.valueOf() : item; };
var itemsIfItem = function (item) { return isItem(item) ? item.items : item; };

var conditionals = ['isArray','isNumber','isFunction','isString'];

_.each(conditionals, function (methodName) {
  proto[methodName] = _.flow(valIfItem, _[methodName]);
});

proto.THIS_YEAR = (new Date()).getFullYear();

proto.average = proto.mean = function (items, defaultValue) {
  return proto.sum(items, defaultValue) / items.length;
};
proto.sum = function(items, defaultValue) {
  if (defaultValue != null) {
    return items.reduce(function(sum, item) {
      var val = item && item.valueOf();
      if (!_.isNumber(val) || _.isNaN(val)) val = defaultValue;
      return sum + val;
    }, 0);
  }
  return items.reduce(function(sum, item) {
    var val = item.valueOf();
    return sum + (_.isNumber(val) ? val : NaN);
  }, 0);
};

proto.quantile = function (sample, p) {
  if (_.isNumber(p)) return ss.quantile(sample, p);
};

proto.interquartileRange = function (items) {
  var values = _.map(items, valIfItem);
  return ss.interquartileRange(values);
};
// var multiOps =

proto.products = function (arr) {
  return _.map(arr, function (pair) {
    return pair.length && _.reduce(pair, function (a, b) { return +a * +b; }, 1);
  });
};

// TODO sums, squares, cubes, sqrts,

proto.binomialCoefficient = function binomial(n, k) {
  // if ((typeof n !== 'number') || (typeof k !== 'number')) return false;
  var coeff = 1;
  for (var x = n-k+1; x <= n; x++) coeff *= x;
  for (x = 1; x <= k; x++) coeff /= x;
  return coeff;
};
proto.isInteger = function (n) { return _.isNumber(n) && n % 1 === 0; }
proto.gcd = function (a, b) {
  var _gcd = function (a, b) { return b !== 0 ? _gcd(b, a % b) : a; };
  if (proto.isInteger(a) && proto.isInteger(b)) return _gcd(a, b);
  return NaN;
}
proto.lcm = function (a, b) { return Math.abs(a) * (Math.abs(b) / proto.gcd(a, b)); }
proto.fraction = function (numerator,denominator) {
  var gcd = proto.gcd(numerator,denominator);
  return '' + (numerator / gcd) + '/' +  (denominator / gcd);
};
proto.polarToCartesian = function (r, theta) {
  var x = r * Math.cos(theta),
      y = r * Math.sin(theta);
  return [x, y];
};
proto.cartesianToPolar = function (x, y) {
  var r = Math.sqrt(x * x + y * y),
      theta = Math.atan(y / x);
  return [r, theta];
};
proto.degreesToRadians = function (degrees) {
  return (degrees / 360) * (2 * Math.PI);
};

proto.radiansToDegrees = function (radians) {
  return 360 * radians / (2 * Math.PI);
};

proto.length = proto.count = _.property('length');
proto.name = proto.key = _.property('key');
proto.valueOf = _.method('valueOf');
proto.toString = _.method('toString');
proto.recursiveCount = function (items) {
  return items.length + _.reduce(items, function (m, item) {
    return m + proto.recursiveCount(item.items);
  }, 0);
};

proto.true = true;
proto.false = false;
proto.null = null;

proto.itemOf = function (item, name) {
  return item.$item(name);
};
proto.itemsOf = _.property('items');
proto.nameOf = _.property('key');
proto.parentOf = _.property('parent');
proto.indexOf = function (array, item) {
  array = itemsIfItem(array);
  return array.indexOf(item);
};
proto.pluckItems = function (items, key) {
  var condition;
  if (_.isFunction(key)) {
    condition = key;
  } else {
    condition = { key: key };
  }
  items = itemsIfItem(items);
  return items.reduce(function (pluckedItems, item) {
    var pluckedItem = _.find(item.items, condition);
    if (pluckedItem) pluckedItems.push(pluckedItem);
    return pluckedItems;
  }, []);
};

proto.flowMap = function () {
  var fns = _.flatten(arguments);
  var fmap = _.rest(function (args) {
    return _.map(fns, function (fn) {
      return fn.valueOf().apply(null, args);
    });
  });
  fmap.toString = fnToString;
  return fmap;
};

proto.flow = function () {
  var fns = _.flatten(arguments);
  var flow = function () {
    return _.reduce(fns, function (r, fn) {
      return [fn.valueOf().apply(null, r)];
    }, arguments)[0];
  };
  flow.toString = fnToString;
  return flow;
};

proto.compose = _.flip(proto.flow);

var curry2 = function (fn) {
  var fn0, fn1;
  fn0 = function () {
    if (arguments.length === 0) return fn0;
    var arg0 = arguments[0];
    fn1 = function (arg1) { return fn(arg0, arg1); };
    if (arguments.length > 1) return fn1(arguments[1]);
    fn1.toString = fnToString;
    return fn1;
  };
  fn0.toString = fnToString;
  return fn0;
};

proto.isEqualTo = proto.eq = curry2(function (b, a) { return a == b; });
proto.isGreaterThan = proto.gt = curry2(function (b, a) { return a > b; });
proto.isGreaterThanOrEqualTo = proto.gte = curry2(function (b, a) { return a >= b; });
proto.isLessThan = proto.lt = curry2(function (b, a) { return a < b; });
proto.isLessThanOrEqualTo = proto.lte = curry2(function (b, a) { return a <= b; });

// TODO should these logic functions check and adapt to non-function arguments?
proto.and = function () {
  var fns = _.flatten(arguments),
      and;
  and = function () {
    var args = arguments;
    return _.every(fns, function (fn) {
      return fn.valueOf().apply(null, args);
    });
  };
  and.toString = fnToString;
  return and;
};

proto.or = function () {
  var fns = _.flatten(arguments),
      or;
  or = function () {
    var args = arguments;
    return _.some(fns, function (fn) {
      return fn.valueOf().apply(null, args);
    });
  };
  or.toString = fnToString;
  return or;
};

proto.not = function (fn) {
  return function () {
    return !fn.valueOf().apply(null, arguments);
  };
};

proto.item = curry2(function (key, list) {
  if (isItem(list)) return list.$item(key);
  if (_.isNumber(key)) return list[key];
  var condition;
  if (_.isFunction(key)) {
    condition = key;
  } else {
    condition = { key: key };
  }
  return _.find(list, condition);
});

proto.global_item = function (key) {
  return window.topItem.$item(key);
};

// evalculist adds a special "accessor" function for things like a['b']
// so it becomes accessor(a, 'b')
proto.accessor = function (obj, key) {
  if (_.isNumber(key) && !isItem(obj[key])) return obj[key];
  return proto.pluckItems(obj, key);
};

proto.dotAccessor = function (items, key) {
  items = itemsIfItem(items);
  var item = _.findLast(items, function (item) {
    if (!item.key) item.valueOf();
    return keyToVarName(item.key) === key;
  });
  if (item && item.hasVal) return item.valueOf();
  return item;
};

var iterators = ['sum','count','average','mean','median','mode','standardDeviation','products',
                'reverse','unzip',
                'filter','find','findLast','map','reduce'];

_.each(iterators, function (methodName) {
  var baseFn = proto[methodName];
  proto[methodName] = function () {
    if (isItem(arguments[0])) arguments[0] = arguments[0].items;
    return baseFn.apply(this, arguments);
  };
});

proto.flatten = function (items) {
  items = itemsIfItem(items);
  if (isItem(items[0])) {
    return _.reduce(items, function (flatItems, item) {
      flatItems.push(item);
      if (item.items.length) return flatItems.concat(proto.flatten(item));
      return flatItems;
    }, []);
  } else {
    return _.flatten(items);
  }
}

proto.uniq = proto.unique = function (items) {
  items = itemsIfItem(items);
  items = _.map(items, proto.valueOf);
  return _.uniq(items);
};

proto.slice = function (items, start, end) {
  items = itemsIfItem(items);
  var result = _.slice(items, start, end);
  if (_.isString(items)) return result.join('');
  return result;
};

var doubleIterators = ['difference','intersection','union','xor','zip'];

_.each(doubleIterators, function (methodName) {
  var baseFn = proto[methodName];
  proto[methodName] = function () {
    var args = arguments;
    _.each(args, function (arg, i) {
      if (isItem(arg)) arg = arg.items;
      if (_.isArray(arg)) arg = _.map(arg, proto.valueOf);
      args[i] = arg;
    });
    return baseFn.apply(this, args);
  };
});

_.each(proto, function (fn) {
  if (_.isFunction(fn)) fn.toString = fnToString;
});

module.exports = function (item) {
  return new ContextObject(item);
};
<commit_msg>Add partial function<commit_after>var _ = require('lodash');
var ss = require('simple-statistics');
var evalculist = require('evalculist');
var isItem = require('./item/isItem');
var keyToVarName = require('./keyToVarName');

var itemMethods = ['$item', '$$item', '$siblings'];

var fnToString = _.constant('[Function]');

function ContextObject (item) {
  if (item) {
    var _this = this;
    _.each(itemMethods, function(method) {
      _this[method] = function () {
        return item[method].apply(item, arguments);
      };
      _this[method].toString = fnToString;
    });

    this.$parent = item.parent;
    this.$index = item.parent ? item.parent.items.indexOf(item) : 0;
    this.$items = item.items;
    this.$name = item.key;
  }
}

var proto = ContextObject.prototype;

var mathKeys = ['E','LN2','LN10','LOG2E','LOG10E','PI','SQRT1_2','SQRT2','abs','acos','acosh','asin','asinh','atan','atan2','atanh','cbrt','ceil','clz32','cos','cosh','exp','expm1','floor','fround','hypot','imul','log','log1p','log2','log10','max','min','pow','random','round','sign','sin','sinh','sqrt','tan','tanh','trunc'];

_.each(mathKeys, function(key) { proto[key] = Math[key]; });

var ssKeys = ['median','mode','product','variance','sampleVariance','standardDeviation','sampleStandardDeviation','medianAbsoluteDeviation','interquartileRange','harmonicMean','geometricMean','rootMeanSquare','sampleSkewness','factorial'];

_.each(ssKeys, function(key) { proto[key] = ss[key]; });

var lodashKeys = ['difference','intersection','reverse','union','uniq','xor',
                  'filter','find','findLast','map','reduce','zip','unzip',
                  'ceil','floor','max','min','round','clamp','inRange','range',
                  'camelCase','capitalize','kebabCase','lowerCase','join','split',
                  'parseInt','repeat','replace','snakeCase','split','startCase','toLower',
                  'toUpper','truncate','upperCase','words','times','identity'];
_.each(lodashKeys, function (key) { proto[key] = _[key]; });

var valIfItem = function (item) { return isItem(item) ? item.valueOf() : item; };
var itemsIfItem = function (item) { return isItem(item) ? item.items : item; };

var conditionals = ['isArray','isNumber','isFunction','isString'];

_.each(conditionals, function (methodName) {
  proto[methodName] = _.flow(valIfItem, _[methodName]);
});

proto.PLACEHOLDER = { toString: _.constant('[PLACEHOLDER]') };

proto.partial = _.rest(function (fn, partialArgs) {
  var partialFn = _.rest(function (args) {
    var finalArgs = partialArgs.map(function (pArg) {
      if (pArg === proto.PLACEHOLDER) return args.shift();
      return pArg;
    }).concat(args);
    return fn.apply(null, finalArgs);
  });
  partialFn.toString = fnToString;
  return partialFn;
});

proto.average = proto.mean = function (items, defaultValue) {
  return proto.sum(items, defaultValue) / items.length;
};
proto.sum = function(items, defaultValue) {
  if (defaultValue != null) {
    return items.reduce(function(sum, item) {
      var val = item && item.valueOf();
      if (!_.isNumber(val) || _.isNaN(val)) val = defaultValue;
      return sum + val;
    }, 0);
  }
  return items.reduce(function(sum, item) {
    var val = item.valueOf();
    return sum + (_.isNumber(val) ? val : NaN);
  }, 0);
};

proto.quantile = function (sample, p) {
  if (_.isNumber(p)) return ss.quantile(sample, p);
};

proto.interquartileRange = function (items) {
  var values = _.map(items, valIfItem);
  return ss.interquartileRange(values);
};
// var multiOps =

proto.products = function (arr) {
  return _.map(arr, function (pair) {
    return pair.length && _.reduce(pair, function (a, b) { return +a * +b; }, 1);
  });
};

// TODO sums, squares, cubes, sqrts,

proto.binomialCoefficient = function binomial(n, k) {
  // if ((typeof n !== 'number') || (typeof k !== 'number')) return false;
  var coeff = 1;
  for (var x = n-k+1; x <= n; x++) coeff *= x;
  for (x = 1; x <= k; x++) coeff /= x;
  return coeff;
};
proto.isInteger = function (n) { return _.isNumber(n) && n % 1 === 0; }
proto.gcd = function (a, b) {
  var _gcd = function (a, b) { return b !== 0 ? _gcd(b, a % b) : a; };
  if (proto.isInteger(a) && proto.isInteger(b)) return _gcd(a, b);
  return NaN;
}
proto.lcm = function (a, b) { return Math.abs(a) * (Math.abs(b) / proto.gcd(a, b)); }
proto.fraction = function (numerator,denominator) {
  var gcd = proto.gcd(numerator,denominator);
  return '' + (numerator / gcd) + '/' +  (denominator / gcd);
};
proto.polarToCartesian = function (r, theta) {
  var x = r * Math.cos(theta),
      y = r * Math.sin(theta);
  return [x, y];
};
proto.cartesianToPolar = function (x, y) {
  var r = Math.sqrt(x * x + y * y),
      theta = Math.atan(y / x);
  return [r, theta];
};
proto.degreesToRadians = function (degrees) {
  return (degrees / 360) * (2 * Math.PI);
};

proto.radiansToDegrees = function (radians) {
  return 360 * radians / (2 * Math.PI);
};

proto.length = proto.count = _.property('length');
proto.name = proto.key = _.property('key');
proto.valueOf = _.method('valueOf');
proto.toString = _.method('toString');
proto.recursiveCount = function (items) {
  return items.length + _.reduce(items, function (m, item) {
    return m + proto.recursiveCount(item.items);
  }, 0);
};

proto.true = true;
proto.false = false;
proto.null = null;

proto.itemOf = function (item, name) {
  return item.$item(name);
};
proto.itemsOf = _.property('items');
proto.nameOf = _.property('key');
proto.parentOf = _.property('parent');
proto.indexOf = function (array, item) {
  array = itemsIfItem(array);
  return array.indexOf(item);
};
proto.pluckItems = function (items, key) {
  var condition;
  if (_.isFunction(key)) {
    condition = key;
  } else {
    condition = { key: key };
  }
  items = itemsIfItem(items);
  return items.reduce(function (pluckedItems, item) {
    var pluckedItem = _.find(item.items, condition);
    if (pluckedItem) pluckedItems.push(pluckedItem);
    return pluckedItems;
  }, []);
};

proto.flowMap = function () {
  var fns = _.flatten(arguments);
  var fmap = _.rest(function (args) {
    return _.map(fns, function (fn) {
      return fn.valueOf().apply(null, args);
    });
  });
  fmap.toString = fnToString;
  return fmap;
};

proto.flow = function () {
  var fns = _.flatten(arguments);
  var flow = function () {
    return _.reduce(fns, function (r, fn) {
      return [fn.valueOf().apply(null, r)];
    }, arguments)[0];
  };
  flow.toString = fnToString;
  return flow;
};

proto.compose = _.flip(proto.flow);

var curry2 = function (fn) {
  var fn0, fn1;
  fn0 = function () {
    if (arguments.length === 0) return fn0;
    var arg0 = arguments[0];
    fn1 = function (arg1) { return fn(arg0, arg1); };
    if (arguments.length > 1) return fn1(arguments[1]);
    fn1.toString = fnToString;
    return fn1;
  };
  fn0.toString = fnToString;
  return fn0;
};

proto.isEqualTo = proto.eq = curry2(function (b, a) { return a == b; });
proto.isGreaterThan = proto.gt = curry2(function (b, a) { return a > b; });
proto.isGreaterThanOrEqualTo = proto.gte = curry2(function (b, a) { return a >= b; });
proto.isLessThan = proto.lt = curry2(function (b, a) { return a < b; });
proto.isLessThanOrEqualTo = proto.lte = curry2(function (b, a) { return a <= b; });

// TODO should these logic functions check and adapt to non-function arguments?
proto.and = function () {
  var fns = _.flatten(arguments),
      and;
  and = function () {
    var args = arguments;
    return _.every(fns, function (fn) {
      return fn.valueOf().apply(null, args);
    });
  };
  and.toString = fnToString;
  return and;
};

proto.or = function () {
  var fns = _.flatten(arguments),
      or;
  or = function () {
    var args = arguments;
    return _.some(fns, function (fn) {
      return fn.valueOf().apply(null, args);
    });
  };
  or.toString = fnToString;
  return or;
};

proto.not = function (fn) {
  return function () {
    return !fn.valueOf().apply(null, arguments);
  };
};

proto.item = curry2(function (key, list) {
  if (isItem(list)) return list.$item(key);
  if (_.isNumber(key)) return list[key];
  var condition;
  if (_.isFunction(key)) {
    condition = key;
  } else {
    condition = { key: key };
  }
  return _.find(list, condition);
});

proto.global_item = function (key) {
  return window.topItem.$item(key);
};

// evalculist adds a special "accessor" function for things like a['b']
// so it becomes accessor(a, 'b')
proto.accessor = function (obj, key) {
  if (_.isNumber(key) && !isItem(obj[key])) return obj[key];
  return proto.pluckItems(obj, key);
};

proto.dotAccessor = function (items, key) {
  items = itemsIfItem(items);
  var item = _.findLast(items, function (item) {
    if (!item.key) item.valueOf();
    return keyToVarName(item.key) === key;
  });
  if (item && item.hasVal) return item.valueOf();
  return item;
};

var iterators = ['sum','count','average','mean','median','mode','standardDeviation','products',
                'reverse','unzip',
                'filter','find','findLast','map','reduce'];

_.each(iterators, function (methodName) {
  var baseFn = proto[methodName];
  proto[methodName] = function () {
    if (isItem(arguments[0])) arguments[0] = arguments[0].items;
    return baseFn.apply(this, arguments);
  };
});

proto.flatten = function (items) {
  items = itemsIfItem(items);
  if (isItem(items[0])) {
    return _.reduce(items, function (flatItems, item) {
      flatItems.push(item);
      if (item.items.length) return flatItems.concat(proto.flatten(item));
      return flatItems;
    }, []);
  } else {
    return _.flatten(items);
  }
}

proto.uniq = proto.unique = function (items) {
  items = itemsIfItem(items);
  items = _.map(items, proto.valueOf);
  return _.uniq(items);
};

proto.slice = function (items, start, end) {
  items = itemsIfItem(items);
  var result = _.slice(items, start, end);
  if (_.isString(items)) return result.join('');
  return result;
};

var doubleIterators = ['difference','intersection','union','xor','zip'];

_.each(doubleIterators, function (methodName) {
  var baseFn = proto[methodName];
  proto[methodName] = function () {
    var args = arguments;
    _.each(args, function (arg, i) {
      if (isItem(arg)) arg = arg.items;
      if (_.isArray(arg)) arg = _.map(arg, proto.valueOf);
      args[i] = arg;
    });
    return baseFn.apply(this, args);
  };
});

_.each(proto, function (fn) {
  if (_.isFunction(fn)) fn.toString = fnToString;
});

module.exports = function (item) {
  return new ContextObject(item);
};
<|endoftext|>


<commit_before>import { before, beforeEach, afterEach } from 'mocha';

export default function(Constructor) {
  return function setupTest(moduleName, options) {
    var module;

    before(function() {
      module = new Constructor(moduleName, options);
    });

    beforeEach(function() {
      module.setContext(this);

      return module.setup();
    });

    afterEach(function() {
      return module.teardown();
    });
  };
}
<commit_msg>Revert "Share Mocha's test context in setup-test-factory."<commit_after>import { before, beforeEach, afterEach } from 'mocha';
import { getContext } from 'ember-test-helpers';

export default function(Constructor) {
  return function setupTest(moduleName, options) {
    var module;

    before(function() {
      module = new Constructor(moduleName, options);
    });

    beforeEach(function() {
      return module.setup().then(() => {
        var context = getContext();
        Object.keys(context).forEach(key => {
          this[key] = context[key];
        });
      });
    });

    afterEach(function() {
      return module.teardown();
    });
  };
}
<|endoftext|>


<commit_before>import Ember from 'ember';
import { getContext, setContext, unsetContext } from './test-context';
import { Klass } from 'klassy';
import { getResolver } from './test-resolver';
import buildRegistry from './build-registry';

export default Klass.extend({
  init: function(subjectName, description, callbacks) {
    // Allow `description` to be omitted, in which case it should
    // default to `subjectName`
    if (!callbacks && typeof description === 'object') {
      callbacks = description;
      description = subjectName;
    }

    this.subjectName = subjectName;
    this.description = description || subjectName;
    this.name = description || subjectName;
    this.callbacks = callbacks || {};

    if (this.callbacks.integration && this.callbacks.needs) {
      throw new Error("cannot declare 'inegration: true' and 'needs' in the same module");
    }

    if (this.callbacks.integration) {
      this.isIntegration = callbacks.integration;
      delete callbacks.integration;
    }

    this.initSubject();
    this.initNeeds();
    this.initSetupSteps();
    this.initTeardownSteps();
  },

  initSubject: function() {
    this.callbacks.subject = this.callbacks.subject || this.defaultSubject;
  },

  initNeeds: function() {
    this.needs = [this.subjectName];
    if (this.callbacks.needs) {
      this.needs = this.needs.concat(this.callbacks.needs);
      delete this.callbacks.needs;
    }
  },

  initSetupSteps: function() {
    this.setupSteps = [];
    this.contextualizedSetupSteps = [];

    if (this.callbacks.beforeSetup) {
      this.setupSteps.push( this.callbacks.beforeSetup );
      delete this.callbacks.beforeSetup;
    }

    this.setupSteps.push(this.setupContainer);
    this.setupSteps.push(this.setupContext);
    this.setupSteps.push(this.setupTestElements);

    if (this.callbacks.setup) {
      this.contextualizedSetupSteps.push( this.callbacks.setup );
      delete this.callbacks.setup;
    }
  },

  initTeardownSteps: function() {
    this.teardownSteps = [];
    this.contextualizedTeardownSteps = [];

    if (this.callbacks.teardown) {
      this.contextualizedTeardownSteps.push( this.callbacks.teardown );
      delete this.callbacks.teardown;
    }

    this.teardownSteps.push(this.teardownSubject);
    this.teardownSteps.push(this.teardownContainer);
    this.teardownSteps.push(this.teardownContext);
    this.teardownSteps.push(this.teardownTestElements);

    if (this.callbacks.afterTeardown) {
      this.teardownSteps.push( this.callbacks.afterTeardown );
      delete this.callbacks.afterTeardown;
    }
  },

  setup: function() {
    var self = this;
    return self.invokeSteps(self.setupSteps).then(function() {
      self.contextualizeCallbacks();
      return self.invokeSteps(self.contextualizedSetupSteps, self.context);
    });
  },

  teardown: function() {
    var self = this;
    return self.invokeSteps(self.contextualizedTeardownSteps, self.context).then(function() {
      return self.invokeSteps(self.teardownSteps);
    }).then(function() {
      self.cache = null;
      self.cachedCalls = null;
    });
  },

  invokeSteps: function(steps, _context) {
    var context = _context;
    if (!context) {
      context = this;
    }
    steps = steps.slice();
    function nextStep() {
      var step = steps.shift();
      if (step) {
        // guard against exceptions, for example missing components referenced from needs.
        return new Ember.RSVP.Promise(function(ok) {
          ok(step.call(context));
        }).then(nextStep);
      } else {
        return Ember.RSVP.resolve();
      }
    }
    return nextStep();
  },

  setupContainer: function() {
    if (this.isIntegration) {
      this._setupIntegratedContainer();
    } else {
      this._setupIsolatedContainer();
    }
  },

  setupContext: function() {
    var subjectName = this.subjectName;
    var container = this.container;

    var factory = function() {
      return container.lookupFactory(subjectName);
    };

    setContext({
      container:  this.container,
      registry: this.registry,
      factory:    factory,
      dispatcher: null
    });

    this.context = getContext();
  },

  setupTestElements: function() {
    if (Ember.$('#ember-testing').length === 0) {
      Ember.$('
').appendTo(document.body);
    }
  },

  teardownSubject: function() {
    var subject = this.cache.subject;

    if (subject) {
      Ember.run(function() {
        Ember.tryInvoke(subject, 'destroy');
      });
    }
  },

  teardownContainer: function() {
    var container = this.container;
    Ember.run(function() {
      container.destroy();
    });
  },

  teardownContext: function() {
    var context = this.context;
    this.context = undefined;
    unsetContext();

    if (context.dispatcher && !context.dispatcher.isDestroyed) {
      Ember.run(function() {
        context.dispatcher.destroy();
      });
    }
  },

  teardownTestElements: function() {
    Ember.$('#ember-testing').empty();

    // Ember 2.0.0 removed Ember.View as public API, so only do this when
    // Ember.View is present
    if (Ember.View && Ember.View.views) {
      Ember.View.views = {};
    }
  },

  defaultSubject: function(options, factory) {
    return factory.create(options);
  },

  // allow arbitrary named factories, like rspec let
  contextualizeCallbacks: function() {
    var _this     = this;
    var callbacks = this.callbacks;
    var context   = this.context;
    var factory   = context.factory;

    this.cache = this.cache || {};
    this.cachedCalls = this.cachedCalls || {};

    var keys = (Object.keys || Ember.keys)(callbacks);

    for (var i = 0, l = keys.length; i < l; i++) {
      (function(key) {

        context[key] = function(options) {
          if (_this.cachedCalls[key]) { return _this.cache[key]; }

          var result = callbacks[key].call(_this, options, factory());

          _this.cache[key] = result;
          _this.cachedCalls[key] = true;

          return result;
        };

      })(keys[i]);
    }
  },

  _setupContainer: function() {
    var resolver = getResolver();
    var items = buildRegistry(resolver);

    this.container = items.container;
    this.registry = items.registry;

    var thingToRegisterWith = this.registry || this.container;
    var router = resolver.resolve('router:main');
    router = router || Ember.Router.extend();
    thingToRegisterWith.register('router:main', router);
  },

  _setupIsolatedContainer: function() {
    var resolver = getResolver();
    this._setupContainer();

    var thingToRegisterWith = this.registry || this.container;

    for (var i = this.needs.length; i > 0; i--) {
      var fullName = this.needs[i - 1];
      var normalizedFullName = resolver.normalize(fullName);
      thingToRegisterWith.register(fullName, resolver.resolve(normalizedFullName));
    }

    if (this.registry) {
      this.registry.fallback.resolver = function() {};
    } else {
      this.container.resolver = function() {};
    }
  },

  _setupIntegratedContainer: function() {
    this._setupContainer();
  }

});
<commit_msg>Fix typo in thrown error<commit_after>import Ember from 'ember';
import { getContext, setContext, unsetContext } from './test-context';
import { Klass } from 'klassy';
import { getResolver } from './test-resolver';
import buildRegistry from './build-registry';

export default Klass.extend({
  init: function(subjectName, description, callbacks) {
    // Allow `description` to be omitted, in which case it should
    // default to `subjectName`
    if (!callbacks && typeof description === 'object') {
      callbacks = description;
      description = subjectName;
    }

    this.subjectName = subjectName;
    this.description = description || subjectName;
    this.name = description || subjectName;
    this.callbacks = callbacks || {};

    if (this.callbacks.integration && this.callbacks.needs) {
      throw new Error("cannot declare 'integration: true' and 'needs' in the same module");
    }

    if (this.callbacks.integration) {
      this.isIntegration = callbacks.integration;
      delete callbacks.integration;
    }

    this.initSubject();
    this.initNeeds();
    this.initSetupSteps();
    this.initTeardownSteps();
  },

  initSubject: function() {
    this.callbacks.subject = this.callbacks.subject || this.defaultSubject;
  },

  initNeeds: function() {
    this.needs = [this.subjectName];
    if (this.callbacks.needs) {
      this.needs = this.needs.concat(this.callbacks.needs);
      delete this.callbacks.needs;
    }
  },

  initSetupSteps: function() {
    this.setupSteps = [];
    this.contextualizedSetupSteps = [];

    if (this.callbacks.beforeSetup) {
      this.setupSteps.push( this.callbacks.beforeSetup );
      delete this.callbacks.beforeSetup;
    }

    this.setupSteps.push(this.setupContainer);
    this.setupSteps.push(this.setupContext);
    this.setupSteps.push(this.setupTestElements);

    if (this.callbacks.setup) {
      this.contextualizedSetupSteps.push( this.callbacks.setup );
      delete this.callbacks.setup;
    }
  },

  initTeardownSteps: function() {
    this.teardownSteps = [];
    this.contextualizedTeardownSteps = [];

    if (this.callbacks.teardown) {
      this.contextualizedTeardownSteps.push( this.callbacks.teardown );
      delete this.callbacks.teardown;
    }

    this.teardownSteps.push(this.teardownSubject);
    this.teardownSteps.push(this.teardownContainer);
    this.teardownSteps.push(this.teardownContext);
    this.teardownSteps.push(this.teardownTestElements);

    if (this.callbacks.afterTeardown) {
      this.teardownSteps.push( this.callbacks.afterTeardown );
      delete this.callbacks.afterTeardown;
    }
  },

  setup: function() {
    var self = this;
    return self.invokeSteps(self.setupSteps).then(function() {
      self.contextualizeCallbacks();
      return self.invokeSteps(self.contextualizedSetupSteps, self.context);
    });
  },

  teardown: function() {
    var self = this;
    return self.invokeSteps(self.contextualizedTeardownSteps, self.context).then(function() {
      return self.invokeSteps(self.teardownSteps);
    }).then(function() {
      self.cache = null;
      self.cachedCalls = null;
    });
  },

  invokeSteps: function(steps, _context) {
    var context = _context;
    if (!context) {
      context = this;
    }
    steps = steps.slice();
    function nextStep() {
      var step = steps.shift();
      if (step) {
        // guard against exceptions, for example missing components referenced from needs.
        return new Ember.RSVP.Promise(function(ok) {
          ok(step.call(context));
        }).then(nextStep);
      } else {
        return Ember.RSVP.resolve();
      }
    }
    return nextStep();
  },

  setupContainer: function() {
    if (this.isIntegration) {
      this._setupIntegratedContainer();
    } else {
      this._setupIsolatedContainer();
    }
  },

  setupContext: function() {
    var subjectName = this.subjectName;
    var container = this.container;

    var factory = function() {
      return container.lookupFactory(subjectName);
    };

    setContext({
      container:  this.container,
      registry: this.registry,
      factory:    factory,
      dispatcher: null
    });

    this.context = getContext();
  },

  setupTestElements: function() {
    if (Ember.$('#ember-testing').length === 0) {
      Ember.$('
').appendTo(document.body);
    }
  },

  teardownSubject: function() {
    var subject = this.cache.subject;

    if (subject) {
      Ember.run(function() {
        Ember.tryInvoke(subject, 'destroy');
      });
    }
  },

  teardownContainer: function() {
    var container = this.container;
    Ember.run(function() {
      container.destroy();
    });
  },

  teardownContext: function() {
    var context = this.context;
    this.context = undefined;
    unsetContext();

    if (context.dispatcher && !context.dispatcher.isDestroyed) {
      Ember.run(function() {
        context.dispatcher.destroy();
      });
    }
  },

  teardownTestElements: function() {
    Ember.$('#ember-testing').empty();

    // Ember 2.0.0 removed Ember.View as public API, so only do this when
    // Ember.View is present
    if (Ember.View && Ember.View.views) {
      Ember.View.views = {};
    }
  },

  defaultSubject: function(options, factory) {
    return factory.create(options);
  },

  // allow arbitrary named factories, like rspec let
  contextualizeCallbacks: function() {
    var _this     = this;
    var callbacks = this.callbacks;
    var context   = this.context;
    var factory   = context.factory;

    this.cache = this.cache || {};
    this.cachedCalls = this.cachedCalls || {};

    var keys = (Object.keys || Ember.keys)(callbacks);

    for (var i = 0, l = keys.length; i < l; i++) {
      (function(key) {

        context[key] = function(options) {
          if (_this.cachedCalls[key]) { return _this.cache[key]; }

          var result = callbacks[key].call(_this, options, factory());

          _this.cache[key] = result;
          _this.cachedCalls[key] = true;

          return result;
        };

      })(keys[i]);
    }
  },

  _setupContainer: function() {
    var resolver = getResolver();
    var items = buildRegistry(resolver);

    this.container = items.container;
    this.registry = items.registry;

    var thingToRegisterWith = this.registry || this.container;
    var router = resolver.resolve('router:main');
    router = router || Ember.Router.extend();
    thingToRegisterWith.register('router:main', router);
  },

  _setupIsolatedContainer: function() {
    var resolver = getResolver();
    this._setupContainer();

    var thingToRegisterWith = this.registry || this.container;

    for (var i = this.needs.length; i > 0; i--) {
      var fullName = this.needs[i - 1];
      var normalizedFullName = resolver.normalize(fullName);
      thingToRegisterWith.register(fullName, resolver.resolve(normalizedFullName));
    }

    if (this.registry) {
      this.registry.fallback.resolver = function() {};
    } else {
      this.container.resolver = function() {};
    }
  },

  _setupIntegratedContainer: function() {
    this._setupContainer();
  }

});
<|endoftext|>


<commit_before>import Ember from 'ember';
import AbstractTestModule from './abstract-test-module';
import { getResolver } from './test-resolver';
import buildRegistry from './build-registry';
import hasEmberVersion from './has-ember-version';

export default AbstractTestModule.extend({
  init(subjectName, description, callbacks) {
    // Allow `description` to be omitted, in which case it should
    // default to `subjectName`
    if (!callbacks && typeof description === 'object') {
      callbacks = description;
      description = subjectName;
    }

    this.subjectName = subjectName;
    this.description = description || subjectName;
    this.name = description || subjectName;
    this.callbacks = callbacks || {};
    this.resolver = this.callbacks.resolver || getResolver();

    if (this.callbacks.integration && this.callbacks.needs) {
      throw new Error("cannot declare 'integration: true' and 'needs' in the same module");
    }

    if (this.callbacks.integration) {
      if (this.isComponentTestModule) {
        this.isLegacy = (callbacks.integration === 'legacy');
        this.isIntegration = (callbacks.integration !== 'legacy');
      } else {
        if (callbacks.integration === 'legacy') {
          throw new Error('`integration: \'legacy\'` is only valid for component tests.');
        }
        this.isIntegration = true;
      }

      delete callbacks.integration;
    }

    this.initSubject();
    this.initNeeds();
    this.initSetupSteps();
    this.initTeardownSteps();
  },

  initSubject() {
    this.callbacks.subject = this.callbacks.subject || this.defaultSubject;
  },

  initNeeds() {
    this.needs = [this.subjectName];
    if (this.callbacks.needs) {
      this.needs = this.needs.concat(this.callbacks.needs);
      delete this.callbacks.needs;
    }
  },

  initSetupSteps() {
    this.setupSteps = [];
    this.contextualizedSetupSteps = [];

    if (this.callbacks.beforeSetup) {
      this.setupSteps.push( this.callbacks.beforeSetup );
      delete this.callbacks.beforeSetup;
    }

    this.setupSteps.push(this.setupContainer);
    this.setupSteps.push(this.setupContext);
    this.setupSteps.push(this.setupTestElements);
    this.setupSteps.push(this.setupAJAXListeners);

    if (this.callbacks.setup) {
      this.contextualizedSetupSteps.push( this.callbacks.setup );
      delete this.callbacks.setup;
    }
  },

  initTeardownSteps() {
    this.teardownSteps = [];
    this.contextualizedTeardownSteps = [];

    if (this.callbacks.teardown) {
      this.contextualizedTeardownSteps.push( this.callbacks.teardown );
      delete this.callbacks.teardown;
    }

    this.teardownSteps.push(this.teardownSubject);
    this.teardownSteps.push(this.teardownContainer);
    this.teardownSteps.push(this.teardownContext);
    this.teardownSteps.push(this.teardownTestElements);
    this.teardownSteps.push(this.teardownAJAXListeners);

    if (this.callbacks.afterTeardown) {
      this.teardownSteps.push( this.callbacks.afterTeardown );
      delete this.callbacks.afterTeardown;
    }
  },

  setupContainer() {
    if (this.isIntegration || this.isLegacy) {
      this._setupIntegratedContainer();
    } else {
      this._setupIsolatedContainer();
    }
  },

  setupContext() {
    var subjectName = this.subjectName;
    var container = this.container;

    var factory = function() {
      return container.lookupFactory(subjectName);
    };

    this._super({
      container:  this.container,
      registry: this.registry,
      factory:    factory,
      register() {
        var target = this.registry || this.container;
        return target.register.apply(target, arguments);
      }
    });

    if (Ember.setOwner) {
      Ember.setOwner(this.context, this.container.owner);
    }

    this.setupInject();
  },

  setupInject() {
    var module = this;
    var context = this.context;

    if (Ember.inject) {
      var keys = (Object.keys || Ember.keys)(Ember.inject);

      keys.forEach(function(typeName) {
        context.inject[typeName] = function(name, opts) {
          var alias = (opts && opts.as) || name;
          Ember.run(function() {
            Ember.set(context, alias, module.container.lookup(typeName + ':' + name));
          });
        };
      });
    }
  },

  teardownSubject() {
    var subject = this.cache.subject;

    if (subject) {
      Ember.run(function() {
        Ember.tryInvoke(subject, 'destroy');
      });
    }
  },

  teardownContainer() {
    var container = this.container;
    Ember.run(function() {
      container.destroy();
    });
  },

  defaultSubject(options, factory) {
    return factory.create(options);
  },

  // allow arbitrary named factories, like rspec let
  contextualizeCallbacks() {
    var callbacks = this.callbacks;
    var context   = this.context;

    this.cache = this.cache || {};
    this.cachedCalls = this.cachedCalls || {};

    var keys = (Object.keys || Ember.keys)(callbacks);
    var keysLength = keys.length;

    if (keysLength) {
      var deprecatedContext = this._buildDeprecatedContext(this, context);
      for (var i = 0; i < keysLength; i++) {
        this._contextualizeCallback(context, keys[i], deprecatedContext);
      }
    }
  },

  _contextualizeCallback(context, key, callbackContext) {
    var _this     = this;
    var callbacks = this.callbacks;
    var factory   = context.factory;

    context[key] = function(options) {
      if (_this.cachedCalls[key]) { return _this.cache[key]; }

      var result = callbacks[key].call(callbackContext, options, factory());

      _this.cache[key] = result;
      _this.cachedCalls[key] = true;

      return result;
    };
  },

  /*
    Builds a version of the passed in context that contains deprecation warnings
    for accessing properties that exist on the module.
  */
  _buildDeprecatedContext(module, context) {
    var deprecatedContext = Object.create(context);

    var keysForDeprecation = Object.keys(module);

    for (var i = 0, l = keysForDeprecation.length; i < l; i++) {
      this._proxyDeprecation(module, deprecatedContext, keysForDeprecation[i]);
    }

    return deprecatedContext;
  },

  /*
    Defines a key on an object to act as a proxy for deprecating the original.
  */
  _proxyDeprecation(obj, proxy, key) {
    if (typeof proxy[key] === 'undefined') {
      Object.defineProperty(proxy, key, {
        get() {
          Ember.deprecate('Accessing the test module property "' + key + '" from a callback is deprecated.', false, { id: 'ember-test-helpers.test-module.callback-context', until: '0.6.0' });
          return obj[key];
        }
      });
    }
  },

  _setupContainer(isolated) {
    var resolver = this.resolver;

    var items = buildRegistry(!isolated ? resolver : Object.create(resolver, {
      resolve: {
        value() {}
      }
    }));

    this.container = items.container;
    this.registry = items.registry;

    if (hasEmberVersion(1, 13)) {
      var thingToRegisterWith = this.registry || this.container;
      var router = resolver.resolve('router:main');
      router = router || Ember.Router.extend();
      thingToRegisterWith.register('router:main', router);
    }
  },

  _setupIsolatedContainer() {
    var resolver = this.resolver;
    this._setupContainer(true);

    var thingToRegisterWith = this.registry || this.container;

    for (var i = this.needs.length; i > 0; i--) {
      var fullName = this.needs[i - 1];
      var normalizedFullName = resolver.normalize(fullName);
      thingToRegisterWith.register(fullName, resolver.resolve(normalizedFullName));
    }

    if (!this.registry) {
      this.container.resolver = function() {};
    }
  },

  _setupIntegratedContainer() {
    this._setupContainer();
  }

});
<commit_msg>test-module: Replace assignments with this._super() call<commit_after>import Ember from 'ember';
import AbstractTestModule from './abstract-test-module';
import { getResolver } from './test-resolver';
import buildRegistry from './build-registry';
import hasEmberVersion from './has-ember-version';

export default AbstractTestModule.extend({
  init(subjectName, description, callbacks) {
    // Allow `description` to be omitted, in which case it should
    // default to `subjectName`
    if (!callbacks && typeof description === 'object') {
      callbacks = description;
      description = subjectName;
    }

    this._super(description || subjectName, callbacks);

    this.subjectName = subjectName;
    this.description = description || subjectName;
    this.resolver = this.callbacks.resolver || getResolver();

    if (this.callbacks.integration && this.callbacks.needs) {
      throw new Error("cannot declare 'integration: true' and 'needs' in the same module");
    }

    if (this.callbacks.integration) {
      if (this.isComponentTestModule) {
        this.isLegacy = (callbacks.integration === 'legacy');
        this.isIntegration = (callbacks.integration !== 'legacy');
      } else {
        if (callbacks.integration === 'legacy') {
          throw new Error('`integration: \'legacy\'` is only valid for component tests.');
        }
        this.isIntegration = true;
      }

      delete callbacks.integration;
    }

    this.initSubject();
    this.initNeeds();
  },

  initSubject() {
    this.callbacks.subject = this.callbacks.subject || this.defaultSubject;
  },

  initNeeds() {
    this.needs = [this.subjectName];
    if (this.callbacks.needs) {
      this.needs = this.needs.concat(this.callbacks.needs);
      delete this.callbacks.needs;
    }
  },

  initSetupSteps() {
    this.setupSteps = [];
    this.contextualizedSetupSteps = [];

    if (this.callbacks.beforeSetup) {
      this.setupSteps.push( this.callbacks.beforeSetup );
      delete this.callbacks.beforeSetup;
    }

    this.setupSteps.push(this.setupContainer);
    this.setupSteps.push(this.setupContext);
    this.setupSteps.push(this.setupTestElements);
    this.setupSteps.push(this.setupAJAXListeners);

    if (this.callbacks.setup) {
      this.contextualizedSetupSteps.push( this.callbacks.setup );
      delete this.callbacks.setup;
    }
  },

  initTeardownSteps() {
    this.teardownSteps = [];
    this.contextualizedTeardownSteps = [];

    if (this.callbacks.teardown) {
      this.contextualizedTeardownSteps.push( this.callbacks.teardown );
      delete this.callbacks.teardown;
    }

    this.teardownSteps.push(this.teardownSubject);
    this.teardownSteps.push(this.teardownContainer);
    this.teardownSteps.push(this.teardownContext);
    this.teardownSteps.push(this.teardownTestElements);
    this.teardownSteps.push(this.teardownAJAXListeners);

    if (this.callbacks.afterTeardown) {
      this.teardownSteps.push( this.callbacks.afterTeardown );
      delete this.callbacks.afterTeardown;
    }
  },

  setupContainer() {
    if (this.isIntegration || this.isLegacy) {
      this._setupIntegratedContainer();
    } else {
      this._setupIsolatedContainer();
    }
  },

  setupContext() {
    var subjectName = this.subjectName;
    var container = this.container;

    var factory = function() {
      return container.lookupFactory(subjectName);
    };

    this._super({
      container:  this.container,
      registry: this.registry,
      factory:    factory,
      register() {
        var target = this.registry || this.container;
        return target.register.apply(target, arguments);
      }
    });

    if (Ember.setOwner) {
      Ember.setOwner(this.context, this.container.owner);
    }

    this.setupInject();
  },

  setupInject() {
    var module = this;
    var context = this.context;

    if (Ember.inject) {
      var keys = (Object.keys || Ember.keys)(Ember.inject);

      keys.forEach(function(typeName) {
        context.inject[typeName] = function(name, opts) {
          var alias = (opts && opts.as) || name;
          Ember.run(function() {
            Ember.set(context, alias, module.container.lookup(typeName + ':' + name));
          });
        };
      });
    }
  },

  teardownSubject() {
    var subject = this.cache.subject;

    if (subject) {
      Ember.run(function() {
        Ember.tryInvoke(subject, 'destroy');
      });
    }
  },

  teardownContainer() {
    var container = this.container;
    Ember.run(function() {
      container.destroy();
    });
  },

  defaultSubject(options, factory) {
    return factory.create(options);
  },

  // allow arbitrary named factories, like rspec let
  contextualizeCallbacks() {
    var callbacks = this.callbacks;
    var context   = this.context;

    this.cache = this.cache || {};
    this.cachedCalls = this.cachedCalls || {};

    var keys = (Object.keys || Ember.keys)(callbacks);
    var keysLength = keys.length;

    if (keysLength) {
      var deprecatedContext = this._buildDeprecatedContext(this, context);
      for (var i = 0; i < keysLength; i++) {
        this._contextualizeCallback(context, keys[i], deprecatedContext);
      }
    }
  },

  _contextualizeCallback(context, key, callbackContext) {
    var _this     = this;
    var callbacks = this.callbacks;
    var factory   = context.factory;

    context[key] = function(options) {
      if (_this.cachedCalls[key]) { return _this.cache[key]; }

      var result = callbacks[key].call(callbackContext, options, factory());

      _this.cache[key] = result;
      _this.cachedCalls[key] = true;

      return result;
    };
  },

  /*
    Builds a version of the passed in context that contains deprecation warnings
    for accessing properties that exist on the module.
  */
  _buildDeprecatedContext(module, context) {
    var deprecatedContext = Object.create(context);

    var keysForDeprecation = Object.keys(module);

    for (var i = 0, l = keysForDeprecation.length; i < l; i++) {
      this._proxyDeprecation(module, deprecatedContext, keysForDeprecation[i]);
    }

    return deprecatedContext;
  },

  /*
    Defines a key on an object to act as a proxy for deprecating the original.
  */
  _proxyDeprecation(obj, proxy, key) {
    if (typeof proxy[key] === 'undefined') {
      Object.defineProperty(proxy, key, {
        get() {
          Ember.deprecate('Accessing the test module property "' + key + '" from a callback is deprecated.', false, { id: 'ember-test-helpers.test-module.callback-context', until: '0.6.0' });
          return obj[key];
        }
      });
    }
  },

  _setupContainer(isolated) {
    var resolver = this.resolver;

    var items = buildRegistry(!isolated ? resolver : Object.create(resolver, {
      resolve: {
        value() {}
      }
    }));

    this.container = items.container;
    this.registry = items.registry;

    if (hasEmberVersion(1, 13)) {
      var thingToRegisterWith = this.registry || this.container;
      var router = resolver.resolve('router:main');
      router = router || Ember.Router.extend();
      thingToRegisterWith.register('router:main', router);
    }
  },

  _setupIsolatedContainer() {
    var resolver = this.resolver;
    this._setupContainer(true);

    var thingToRegisterWith = this.registry || this.container;

    for (var i = this.needs.length; i > 0; i--) {
      var fullName = this.needs[i - 1];
      var normalizedFullName = resolver.normalize(fullName);
      thingToRegisterWith.register(fullName, resolver.resolve(normalizedFullName));
    }

    if (!this.registry) {
      this.container.resolver = function() {};
    }
  },

  _setupIntegratedContainer() {
    this._setupContainer();
  }

});
<|endoftext|>


<commit_before>'use strict'

module.exports = function (sequelize, DataTypes) {
  let User = sequelize.define('User', {
    id: {
      type: DataTypes.UUID,
      primaryKey: true,
      defaultValue: DataTypes.UUIDV4
    },
    email: {
      type: DataTypes.STRING,
      allowNull: false
    },
    password: {
      type: DataTypes.STRING(1024),
      allowNull: false
    },
    salt: {
      type: DataTypes.STRING,
      allowNull: true
    },
    nicknames: {
      type: 'citext[]',
      allowNull: true,
      defaultValue: 'ARRAY[]::citext[]'
    },
    drilled: {
      type: DataTypes.BOOLEAN,
      allowNull: false,
      defaultValue: false
    },
    drilledDispatch: {
      type: DataTypes.BOOLEAN,
      allowNull: false,
      defaultValue: false
    },
    group: {
      type: DataTypes.ENUM('normal', 'overseer', 'moderator', 'admin'),
      allowNull: false,
      defaultValue: 'normal'
    },
    dispatch: {
      type: DataTypes.BOOLEAN,
      allowNull: true,
      defaultValue: null,
      unique: true
    }
  }, {
    paranoid: true,
    classMethods: {
      associate: function (models) {
        User.hasMany(models.Rat, { as: 'rats' })
      }
    }
  })

  return User
}
<commit_msg>Use literal function for citext array default value, not string<commit_after>'use strict'

module.exports = function (sequelize, DataTypes) {
  let User = sequelize.define('User', {
    id: {
      type: DataTypes.UUID,
      primaryKey: true,
      defaultValue: DataTypes.UUIDV4
    },
    email: {
      type: DataTypes.STRING,
      allowNull: false
    },
    password: {
      type: DataTypes.STRING(1024),
      allowNull: false
    },
    salt: {
      type: DataTypes.STRING,
      allowNull: true
    },
    nicknames: {
      type: 'citext[]',
      allowNull: true,
      defaultValue: sequelize.literal('ARRAY[]::citext[]')
    },
    drilled: {
      type: DataTypes.BOOLEAN,
      allowNull: false,
      defaultValue: false
    },
    drilledDispatch: {
      type: DataTypes.BOOLEAN,
      allowNull: false,
      defaultValue: false
    },
    group: {
      type: DataTypes.ENUM('normal', 'overseer', 'moderator', 'admin'),
      allowNull: false,
      defaultValue: 'normal'
    },
    dispatch: {
      type: DataTypes.BOOLEAN,
      allowNull: true,
      defaultValue: null,
      unique: true
    }
  }, {
    paranoid: true,
    classMethods: {
      associate: function (models) {
        User.hasMany(models.Rat, { as: 'rats' })
      }
    }
  })

  return User
}
<|endoftext|>


<commit_before>import { expect } from 'chai';
import { hasChildren } from '../src';

describe('tree.hasChildren', function () {
  it('returns false if empty rows are passed', function () {
    expect(hasChildren({ rows: [] })).to.deep.equal(false);
  });

  it('returns false if there are no children', function () {
    const given = [
      {
        foo: 'bar'
      }
    ];
    const expected = false;

    expect(hasChildren({ rows: given, index: 0 })).to.deep.equal(expected);
  });

  it('returns true if there is one child', function () {
    const given = [
      {
        id: 0,
        foo: 'bar'
      },
      {
        parent: 0,
        foo: 'foo'
      }
    ];
    const expected = true;

    expect(hasChildren({ rows: given, index: 0 })).to.deep.equal(expected);
  });

  it('works with sibling children', function () {
    const given = [
      {
        id: 0,
        foo: 'bar'
      },
      {
        id: 1,
        parent: 0,
        foo: 'foo'
      },
      {
        id: 2
        parent: 0,
        foo: 'barbar'
      }
    ];
    const expected = true;

    expect(hasChildren({ rows: given, index: 0 })).to.deep.equal(expected);
  });

  it('works with nested children', function () {
    const given = [
      {
        id: 0,
        foo: 'bar'
      },
      {
        id: 1,
        parent: 0,
        foo: 'foo'
      },
      {
        id: 2,
        parent: 1,
        foo: 'barbar'
      }
    ];
    const expected = true;

    expect(hasChildren({ rows: given, index: 1 })).to.deep.equal(expected);
  });

  it('allows parent field to be customized', function () {
    const property = 'demo';
    const given = [
      {
        id: 0,
        foo: 'bar'
      },
      {
        id: 1,
        [property]: 0,
        foo: 'foo'
      },
      {
        id: 2,
        [property]: 1,
        foo: 'barbar'
      }
    ];
    const expected = true;

    expect(hasChildren({
      rows: given, index: 1, parent: property
    })).to.deep.equal(expected);
  });

  it('allows id field to be customized', function () {
    const property = 'demo';
    const given = [
      {
        [property]: 0,
        foo: 'bar'
      },
      {
        [property]: 1,
        parent: 0,
        foo: 'foo'
      },
      {
        [property]: 2,
        parent: 1,
        foo: 'barbar'
      }
    ];
    const expected = true;

    expect(hasChildren({
      rows: given, index: 1, id: property
    })).to.deep.equal(expected);
  });
});
<commit_msg>tree - Add a missing comma<commit_after>import { expect } from 'chai';
import { hasChildren } from '../src';

describe('tree.hasChildren', function () {
  it('returns false if empty rows are passed', function () {
    expect(hasChildren({ rows: [] })).to.deep.equal(false);
  });

  it('returns false if there are no children', function () {
    const given = [
      {
        foo: 'bar'
      }
    ];
    const expected = false;

    expect(hasChildren({ rows: given, index: 0 })).to.deep.equal(expected);
  });

  it('returns true if there is one child', function () {
    const given = [
      {
        id: 0,
        foo: 'bar'
      },
      {
        parent: 0,
        foo: 'foo'
      }
    ];
    const expected = true;

    expect(hasChildren({ rows: given, index: 0 })).to.deep.equal(expected);
  });

  it('works with sibling children', function () {
    const given = [
      {
        id: 0,
        foo: 'bar'
      },
      {
        id: 1,
        parent: 0,
        foo: 'foo'
      },
      {
        id: 2,
        parent: 0,
        foo: 'barbar'
      }
    ];
    const expected = true;

    expect(hasChildren({ rows: given, index: 0 })).to.deep.equal(expected);
  });

  it('works with nested children', function () {
    const given = [
      {
        id: 0,
        foo: 'bar'
      },
      {
        id: 1,
        parent: 0,
        foo: 'foo'
      },
      {
        id: 2,
        parent: 1,
        foo: 'barbar'
      }
    ];
    const expected = true;

    expect(hasChildren({ rows: given, index: 1 })).to.deep.equal(expected);
  });

  it('allows parent field to be customized', function () {
    const property = 'demo';
    const given = [
      {
        id: 0,
        foo: 'bar'
      },
      {
        id: 1,
        [property]: 0,
        foo: 'foo'
      },
      {
        id: 2,
        [property]: 1,
        foo: 'barbar'
      }
    ];
    const expected = true;

    expect(hasChildren({
      rows: given, index: 1, parent: property
    })).to.deep.equal(expected);
  });

  it('allows id field to be customized', function () {
    const property = 'demo';
    const given = [
      {
        [property]: 0,
        foo: 'bar'
      },
      {
        [property]: 1,
        parent: 0,
        foo: 'foo'
      },
      {
        [property]: 2,
        parent: 1,
        foo: 'barbar'
      }
    ];
    const expected = true;

    expect(hasChildren({
      rows: given, index: 1, id: property
    })).to.deep.equal(expected);
  });
});
<|endoftext|>


<commit_before>/**
 * RightJS UI Internationalization: French module
 *
 * Copyright (C) Nikolay V. Nemshilov aka St.
 */
if (self.Calendar) {
  $ext(Calendar.i18n, {
    Done:            "Fait",
    Now:             "Maintenant",
    Next:            "Mois prochain",
    Prev:            "Mois précédent",
    NextYear:        "L'année prochain",
    PrevYear:        "L'année précédent",

    dayNames:        $w('Dimanche Lundi Mardi Mercredi Jeudi Vendredi Samedi'),
    dayNamesShort:   $w('Dim Lun Mar Mer Jeu Ven Sam'),
    dayNamesMin:     $w('Di Lu Ma Me Je Ve Sa'),
    monthNames:      $w('Janvier Février Mars Avril Mai Juin Juillet Août Septembre Octobre Novembre Décembre'),
    monthNamesShort: $w('Jan Fév Mar Avr Mai Juin Juil Août Sept Oct Nov Déc')
  });
}

if (self.Lightbox) {
  $ext(Lightbox.i18n, {
    CloseTitle: 'Fin',
    PrevTitle:  'Image précédente',
    NextTitle:  'Prochaine image'
  });
}
<commit_msg>Shortified the 'Now' button translation so was fitting the button<commit_after>/**
 * RightJS UI Internationalization: French module
 *
 * Copyright (C) Nikolay V. Nemshilov aka St.
 */
if (self.Calendar) {
  $ext(Calendar.i18n, {
    Done:            "Fait",
    Now:             "Maint.",
    Next:            "Mois prochain",
    Prev:            "Mois précédent",
    NextYear:        "L'année prochain",
    PrevYear:        "L'année précédent",

    dayNames:        $w('Dimanche Lundi Mardi Mercredi Jeudi Vendredi Samedi'),
    dayNamesShort:   $w('Dim Lun Mar Mer Jeu Ven Sam'),
    dayNamesMin:     $w('Di Lu Ma Me Je Ve Sa'),
    monthNames:      $w('Janvier Février Mars Avril Mai Juin Juillet Août Septembre Octobre Novembre Décembre'),
    monthNamesShort: $w('Jan Fév Mar Avr Mai Juin Juil Août Sept Oct Nov Déc')
  });
}

if (self.Lightbox) {
  $ext(Lightbox.i18n, {
    CloseTitle: 'Fin',
    PrevTitle:  'Image précédente',
    NextTitle:  'Prochaine image'
  });
}
<|endoftext|>


<commit_before>/* globals menu */

Template.sidebarItem.helpers({
	canLeave() {
		const roomData = Session.get(`roomData${ this.rid }`);

		if (!roomData) { return false; }

		if (((roomData.cl != null) && !roomData.cl) || (roomData.t === 'd')) {
			return false;
		} else {
			return true;
		}
	}
});

Template.sidebarItem.events({
	'click [data-id], click .sidebar-item__link'() {
		return menu.close();
	}
});

Template.sidebarItem.onCreated(function() {
	// console.log('sidebarItem', this.data);
});
<commit_msg>Add leave and hide buttons again<commit_after>/* globals menu popover */

Template.sidebarItem.helpers({
	canLeave() {
		const roomData = Session.get(`roomData${ this.rid }`);

		if (!roomData) { return false; }

		if (((roomData.cl != null) && !roomData.cl) || (roomData.t === 'd')) {
			return false;
		} else {
			return true;
		}
	}
});

Template.sidebarItem.events({
	'click [data-id], click .sidebar-item__link'() {
		return menu.close();
	},
	'click .sidebar-item__menu'(e) {
		const config = {
			popoverClass: 'sidebar-item',
			columns: [
				{
					groups: [
						{
							items: [
								{
									icon: 'eye-off',
									name: t('Hide_room'),
									type: 'sidebar-item',
									id: 'hide'
								},
								{
									icon: 'sign-out',
									name: t('Leave_room'),
									type: 'sidebar-item',
									id: 'leave'
								}
							]
						}
					]
				}
			],
			mousePosition: {
				x: e.clientX,
				y: e.clientY
			},
			data: {
				template: this.t,
				rid: this.rid,
				name: this.name
			}
		};

		popover.open(config);
	}
});

Template.sidebarItem.onCreated(function() {
	// console.log('sidebarItem', this.data);
});
<|endoftext|>


<commit_before>var fs = require('fs')
var dae2json = require('../../../')

module.exports = LoadModel

// TODO: clean up
function LoadModel (gl, callback) {
  // TODO: Read using xhr request
  dae2json(fs.readFileSync('./demo/assets/two-skinned-cubes.dae'), function (err, parsedDae) {
    if (err) { callback(err) }

    var vertexPositionBuffer = gl.createBuffer()
    gl.bindBuffer(gl.ARRAY_BUFFER, vertexPositionBuffer)
    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(parsedDae.vertexPositions), gl.STATIC_DRAW)

    var vertexPositionIndexBuffer = gl.createBuffer()
    gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, vertexPositionIndexBuffer)
    gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(parsedDae.vertexPositionIndices), gl.STATIC_DRAW)

    // TODO: naming
    var vertexJointAffectors = []
    var vertexJointWeights = []
    // Handle weights (this model has only one joint/weight per vertex)
    // TODO: Should the consumer be expected to know the max # joints/weights per vertex?
    parsedDae.vertexJointWeights.forEach(function (jointsAndWeights) {
      var jointIndex = Object.keys(jointsAndWeights)[0]
      vertexJointAffectors.push(Number(jointIndex))
      vertexJointWeights.push(jointsAndWeights[jointIndex])
    })

    // Joints the affect each vertex
    // TODO: naming
    var affectingJointIndexBuffer = gl.createBuffer()
    gl.bindBuffer(gl.ARRAY_BUFFER, affectingJointIndexBuffer)
    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertexJointAffectors), gl.STATIC_DRAW)

    // Weights of affecting joints
    // TODO: naming
    var weightBuffer = gl.createBuffer()
    gl.bindBuffer(gl.ARRAY_BUFFER, weightBuffer)
    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertexJointWeights), gl.STATIC_DRAW)

    var stuff = {
      vertexPositionBuffer: vertexPositionBuffer,
      vertexPositionIndexBuffer: vertexPositionIndexBuffer,
      affectingJointIndexBuffer: affectingJointIndexBuffer,
      weightBuffer: weightBuffer,
      keyframes: parsedDae.keyframes
    }
    callback(null, stuff)
  })
}
<commit_msg>Add vertex normals to demo<commit_after>var fs = require('fs')
var dae2json = require('../../../')

module.exports = LoadModel

// TODO: clean up
function LoadModel (gl, callback) {
  // TODO: Read using xhr request
  dae2json(fs.readFileSync('./demo/assets/two-skinned-cubes.dae'), function (err, parsedDae) {
    if (err) { callback(err) }

    var vertexPositionBuffer = gl.createBuffer()
    gl.bindBuffer(gl.ARRAY_BUFFER, vertexPositionBuffer)
    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(parsedDae.vertexPositions), gl.STATIC_DRAW)

    var vertexPositionIndexBuffer = gl.createBuffer()
    gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, vertexPositionIndexBuffer)
    gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(parsedDae.vertexPositionIndices), gl.STATIC_DRAW)

    // TODO: naming
    var vertexJointAffectors = []
    var vertexJointWeights = []
    // Handle weights (this model has only one joint/weight per vertex)
    // TODO: Should the consumer be expected to know the max # joints/weights per vertex?
    parsedDae.vertexJointWeights.forEach(function (jointsAndWeights) {
      var jointIndex = Object.keys(jointsAndWeights)[0]
      vertexJointAffectors.push(Number(jointIndex))
      vertexJointWeights.push(jointsAndWeights[jointIndex])
    })

    // Joints the affect each vertex
    // TODO: naming
    var affectingJointIndexBuffer = gl.createBuffer()
    gl.bindBuffer(gl.ARRAY_BUFFER, affectingJointIndexBuffer)
    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertexJointAffectors), gl.STATIC_DRAW)

    // Weights of affecting joints
    // TODO: naming
    var weightBuffer = gl.createBuffer()
    gl.bindBuffer(gl.ARRAY_BUFFER, weightBuffer)
    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertexJointWeights), gl.STATIC_DRAW)

    // Vertex normals
    // TODO: Comment this
    var vertexNormals = []
    parsedDae.vertexNormalIndices.forEach(function (index) {
      for (var i = 0; i < 3; i++) {
        vertexNormals.push(parsedDae.vertexNormals[index * 3 + i])
      }
    })
    var vertexNormalBuffer = gl.createBuffer()
    gl.bindBuffer(gl.ARRAY_BUFFER, vertexNormalBuffer)
    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertexNormals), gl.STATIC_DRAW)

    var stuff = {
      vertexNormalBuffer: vertexNormalBuffer,
      vertexPositionBuffer: vertexPositionBuffer,
      vertexPositionIndexBuffer: vertexPositionIndexBuffer,
      affectingJointIndexBuffer: affectingJointIndexBuffer,
      weightBuffer: weightBuffer,
      keyframes: parsedDae.keyframes
    }
    callback(null, stuff)
  })
}
<|endoftext|>


<commit_before>import { updateMediumParams } from '../../client/actions'
import BasicCheckbox from '../basic_checkbox'
import React from 'react';
import { connect } from 'react-redux'
import _, { contains, find } from 'underscore'

function MediumFilter(props) {
  const {
    aggregatedMediums,
    filterParams,
    initialMediumMap,
    updateMediumParamsAction
  } = props
  const mediumIds = filterParams.gene_ids
  const allMediums = { id: 'mediums-all', name: 'All' }
  const allMediumsSelected = mediumIds.length == 0
  const aggregatedMediumIds = aggregatedMediums.map((agg) => agg.id)

  return (

Medium

      <BasicCheckbox
        key={allMediums.id}
        item={allMediums}
        onClick={updateMediumParamsAction}
        checked={allMediumsSelected}
      />
      {
        _.map(initialMediumMap, (initialAgg) => {
          const mediumSelected = contains(mediumIds, initialAgg.id)
          const includedMedium = aggregatedMediums.find((agg) => agg.id === initialAgg.id)
          return (
            <BasicCheckbox
              key={initialAgg.id}
              item={{id: initialAgg.id, name: initialAgg.name, count: includedMedium && includedMedium.count}}
              onClick={updateMediumParamsAction}
              checked={mediumSelected}
              disabled={includedMedium === undefined}
            />
          )
        })
      }

  )
}

const mapStateToProps = (state) => {
  return {
    aggregatedMediums: state.auctionArtworks.aggregatedMediums,
    filterParams: state.auctionArtworks.filterParams,
    initialMediumMap: state.auctionArtworks.initialMediumMap
  }
}

const mapDispatchToProps = {
  updateMediumParamsAction: updateMediumParams
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(MediumFilter)
<commit_msg>fix auction2 page for ie support<commit_after>import { updateMediumParams } from '../../client/actions'
import BasicCheckbox from '../basic_checkbox'
import React from 'react';
import { connect } from 'react-redux'
import _, { contains } from 'underscore'

function MediumFilter(props) {
  const {
    aggregatedMediums,
    filterParams,
    initialMediumMap,
    updateMediumParamsAction
  } = props
  const mediumIds = filterParams.gene_ids
  const allMediums = { id: 'mediums-all', name: 'All' }
  const allMediumsSelected = mediumIds.length == 0
  const aggregatedMediumIds = aggregatedMediums.map((agg) => agg.id)

  return (

Medium

      <BasicCheckbox
        key={allMediums.id}
        item={allMediums}
        onClick={updateMediumParamsAction}
        checked={allMediumsSelected}
      />
      {
        _.map(initialMediumMap, (initialAgg) => {
          const mediumSelected = contains(mediumIds, initialAgg.id)
          const includedMedium = _.find(aggregatedMediums, (agg) => agg.id === initialAgg.id)
          return (
            <BasicCheckbox
              key={initialAgg.id}
              item={{id: initialAgg.id, name: initialAgg.name, count: includedMedium && includedMedium.count}}
              onClick={updateMediumParamsAction}
              checked={mediumSelected}
              disabled={includedMedium === undefined}
            />
          )
        })
      }

  )
}

const mapStateToProps = (state) => {
  return {
    aggregatedMediums: state.auctionArtworks.aggregatedMediums,
    filterParams: state.auctionArtworks.filterParams,
    initialMediumMap: state.auctionArtworks.initialMediumMap
  }
}

const mapDispatchToProps = {
  updateMediumParamsAction: updateMediumParams
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(MediumFilter)
<|endoftext|>


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

// Array polyfills for older browsers
if (!('clean' in Array.prototype)) {
  Array.prototype.clean = function (deleteValue) {
    for (var i = 0; i < this.length; i++) {
      if (this[i] == deleteValue) {
        this.splice(i, 1);
        i--;
      }
    }
    return this;
  };
}

if (!('move' in Array.prototype)) {
  Array.prototype.move = function (old_index, new_index) {
    if (new_index >= this.length) {
      var k = new_index - this.length;
      while ((k--) + 1) {
        this.push(undefined);
      }
    }
    this.splice(new_index, 0, this.splice(old_index, 1)[0]);
    return this;
  };
}

if (!('indexOf' in Array.prototype)) {
  Array.prototype.indexOf = function (needle) {
    for (var i = 0; i < this.length; i++) {
      if (this[i] === needle) {
        return i;
      }
    }
    return -1;
  };
}

// adding missing .filter for IE8
if (!('filter' in Array.prototype)) {
  Array.prototype.filter = function (filter, that /*opt*/) {
    var other = [], v;
    for (var i = 0, n = this.length; i < n; i++)
      if (i in this && filter.call(that, v = this[i], i, this))
        other.push(v);
    return other;
  };
}

Array.prototype.diff = function (a) {
  return this.filter(function (i) {
    return a.indexOf(i) < 0;
  });
};

/*
 * Add utility methods to the HUE object
*/
(function (hue) {
  'use strict';

  /*
   * Convert text to URLs
   * Selector arg can be jQuery or document.querySelectorAll()
  */
  hue.text2Url = function (selectors) {
    var i = 0,
      len = selectors.length;

    for (i; i < len; i++) {
      var arr = [],
        selector = selectors[i],
        val = selector.innerHTML.replace(/ /g, ' ').split(' ');

      val.forEach(function(word) {
        var matched = null,
          re = /(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?/gi;

        if (re.test(word)) {
          matched = word.match(re);
          word = word.replace(matched, '' + matched + '')
          arr.push(word);
        } else {
          arr.push(word);
        }
      });

      selector.innerHTML = arr.join(' ');
    }
    return this;
  };

  /*
   * Create a in-memory div, set it's inner text(which jQuery automatically encodes)
   * then grab the encoded contents back out.
  */

  hue.htmlEncode = function (value){
    return $('
').text(value).html();
  };

}(hue = window.hue || {}));

if (!Object.keys) {
  Object.keys = (function () {
    'use strict';
    var hasOwnProperty = Object.prototype.hasOwnProperty,
        hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
        dontEnums = [
          'toString',
          'toLocaleString',
          'valueOf',
          'hasOwnProperty',
          'isPrototypeOf',
          'propertyIsEnumerable',
          'constructor'
        ],
        dontEnumsLength = dontEnums.length;

    return function (obj) {
      if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) {
        throw new TypeError('Object.keys called on non-object');
      }

      var result = [], prop, i;

      for (prop in obj) {
        if (hasOwnProperty.call(obj, prop)) {
          result.push(prop);
        }
      }

      if (hasDontEnumBug) {
        for (i = 0; i < dontEnumsLength; i++) {
          if (hasOwnProperty.call(obj, dontEnums[i])) {
            result.push(dontEnums[i]);
          }
        }
      }
      return result;
    };
  }());
}

function s4() {
  return Math.floor((1 + Math.random()) * 0x10000)
      .toString(16)
      .substring(1);
}

function UUID() {
  return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
}

// Based on original pub/sub implementation from http://davidwalsh.name/pubsub-javascript
var huePubSub = (function () {
  var topics = {};
  var hOP = topics.hasOwnProperty;

  return {
    subscribe: function (topic, listener) {
      if(! hOP.call(topics, topic)) {
        topics[topic] = [];
      }

      var index = topics[topic].push(listener) - 1;

      return {
        remove: function () {
          delete topics[topic][index];
        }
      };
    },
    subscribeOnce: function (topic, listener) {
      var ephemeral = this.subscribe(topic, function(){
        listener.apply(arguments);
        ephemeral.remove();
      });

    },
    publish: function (topic, info) {
      if (! hOP.call(topics, topic)) {
        return;
      }

      topics[topic].forEach(function (item) {
        item(info != undefined ? info : {});
      });
    }
  };
})();

Number.prototype.toHHMMSS = function () {
  var _s = this;
  var _ms = _s % 1000;
  _s = (_s - _ms) / 1000;
  var _secs = _s % 60;
  _s = (_s - _secs) / 60;
  var _mins = _s % 60;
  var _hrs = (_s - _mins) / 60;

  return (_hrs > 0 ? _hrs + "h, " : "") + (_mins > 0 ? _mins + "m, " : "") + _secs + "." + _ms + "s";
}
<commit_msg>[core] Allow undefined to be published with huePubSub<commit_after>// Licensed to Cloudera, Inc. under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  Cloudera, Inc. licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Array polyfills for older browsers
if (!('clean' in Array.prototype)) {
  Array.prototype.clean = function (deleteValue) {
    for (var i = 0; i < this.length; i++) {
      if (this[i] == deleteValue) {
        this.splice(i, 1);
        i--;
      }
    }
    return this;
  };
}

if (!('move' in Array.prototype)) {
  Array.prototype.move = function (old_index, new_index) {
    if (new_index >= this.length) {
      var k = new_index - this.length;
      while ((k--) + 1) {
        this.push(undefined);
      }
    }
    this.splice(new_index, 0, this.splice(old_index, 1)[0]);
    return this;
  };
}

if (!('indexOf' in Array.prototype)) {
  Array.prototype.indexOf = function (needle) {
    for (var i = 0; i < this.length; i++) {
      if (this[i] === needle) {
        return i;
      }
    }
    return -1;
  };
}

// adding missing .filter for IE8
if (!('filter' in Array.prototype)) {
  Array.prototype.filter = function (filter, that /*opt*/) {
    var other = [], v;
    for (var i = 0, n = this.length; i < n; i++)
      if (i in this && filter.call(that, v = this[i], i, this))
        other.push(v);
    return other;
  };
}

Array.prototype.diff = function (a) {
  return this.filter(function (i) {
    return a.indexOf(i) < 0;
  });
};

/*
 * Add utility methods to the HUE object
*/
(function (hue) {
  'use strict';

  /*
   * Convert text to URLs
   * Selector arg can be jQuery or document.querySelectorAll()
  */
  hue.text2Url = function (selectors) {
    var i = 0,
      len = selectors.length;

    for (i; i < len; i++) {
      var arr = [],
        selector = selectors[i],
        val = selector.innerHTML.replace(/ /g, ' ').split(' ');

      val.forEach(function(word) {
        var matched = null,
          re = /(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?/gi;

        if (re.test(word)) {
          matched = word.match(re);
          word = word.replace(matched, '' + matched + '')
          arr.push(word);
        } else {
          arr.push(word);
        }
      });

      selector.innerHTML = arr.join(' ');
    }
    return this;
  };

  /*
   * Create a in-memory div, set it's inner text(which jQuery automatically encodes)
   * then grab the encoded contents back out.
  */

  hue.htmlEncode = function (value){
    return $('
').text(value).html();
  };

}(hue = window.hue || {}));

if (!Object.keys) {
  Object.keys = (function () {
    'use strict';
    var hasOwnProperty = Object.prototype.hasOwnProperty,
        hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
        dontEnums = [
          'toString',
          'toLocaleString',
          'valueOf',
          'hasOwnProperty',
          'isPrototypeOf',
          'propertyIsEnumerable',
          'constructor'
        ],
        dontEnumsLength = dontEnums.length;

    return function (obj) {
      if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) {
        throw new TypeError('Object.keys called on non-object');
      }

      var result = [], prop, i;

      for (prop in obj) {
        if (hasOwnProperty.call(obj, prop)) {
          result.push(prop);
        }
      }

      if (hasDontEnumBug) {
        for (i = 0; i < dontEnumsLength; i++) {
          if (hasOwnProperty.call(obj, dontEnums[i])) {
            result.push(dontEnums[i]);
          }
        }
      }
      return result;
    };
  }());
}

function s4() {
  return Math.floor((1 + Math.random()) * 0x10000)
      .toString(16)
      .substring(1);
}

function UUID() {
  return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
}

// Based on original pub/sub implementation from http://davidwalsh.name/pubsub-javascript
var huePubSub = (function () {
  var topics = {};
  var hOP = topics.hasOwnProperty;

  return {
    subscribe: function (topic, listener) {
      if(! hOP.call(topics, topic)) {
        topics[topic] = [];
      }

      var index = topics[topic].push(listener) - 1;

      return {
        remove: function () {
          delete topics[topic][index];
        }
      };
    },
    subscribeOnce: function (topic, listener) {
      var ephemeral = this.subscribe(topic, function(){
        listener.apply(arguments);
        ephemeral.remove();
      });

    },
    publish: function (topic, info) {
      if (! hOP.call(topics, topic)) {
        return;
      }

      topics[topic].forEach(function (item) {
        item(info);
      });
    }
  };
})();

Number.prototype.toHHMMSS = function () {
  var _s = this;
  var _ms = _s % 1000;
  _s = (_s - _ms) / 1000;
  var _secs = _s % 60;
  _s = (_s - _secs) / 60;
  var _mins = _s % 60;
  var _hrs = (_s - _mins) / 60;

  return (_hrs > 0 ? _hrs + "h, " : "") + (_mins > 0 ? _mins + "m, " : "") + _secs + "." + _ms + "s";
}
<|endoftext|>