<commit_before>var BIP39 = require('bip39')
var ccWallet = require('cc-wallet-core')
var _ = require('lodash')

var AssetModels = require('./AssetModels')

/**
 * @class WalletEngine
 *
 * @param {Object} opts
 * @param {boolean} opts.testnet
 */
function WalletEngine(opts) {
  this.setCallback(function() {})
  this.assetModels = null

  opts = _.extend({ testnet: false }, opts)
  this.ccWallet = new ccWallet(opts)

  if (this.isInitialized())
    this._initializeWalletEngine()
}

/**
 * @param {function} callback
 */
WalletEngine.prototype.setCallback = function(callback) {
  this.updateCallback = callback
}

/**
 * @return {string}
 */
WalletEngine.prototype.generateMnemonic = BIP39.generateMnemonic

/**
 * @return {boolean}
 */
WalletEngine.prototype.isCurrentMnemonic = function(mnemonic, password) {
  var seed = BIP39.mnemonicToSeedHex(mnemonic, password)
  return this.ccWallet.isCurrentSeed(seed)
}

/**
 * @return {boolean}
 */
WalletEngine.prototype.isInitialized = function() {
  return this.ccWallet.isInitialized()
}

/**
 * @param {string} mnemonic
 * @param {string} [password]
 * @throws {Error} If already initialized
 */
WalletEngine.prototype.initialize = function(mnemonic, password) {
  var seed = BIP39.mnemonicToSeedHex(mnemonic, password)
  this.ccWallet.initialize(seed)

  this._initializeWalletEngine()
}

/**
 */
WalletEngine.prototype._initializeWalletEngine = function() {
  this.assetModels = new AssetModels(this.ccWallet)
  this.assetModels.on('update', function() { this.updateCallback() }.bind(this))
}

/**
 * @return {AssetModel[]}
 * @throws {Error} If wallet not initialized
 */
WalletEngine.prototype.getAssetModels = function() {
  this.ccWallet.isInitializedCheck()
  return this.assetModels.getAssetModels()
}

/**
 * @throws {Error} If wallet not initialized
 */
WalletEngine.prototype.update = function() {
  this.ccWallet.isInitializedCheck()
  this.assetModels.update()
}

module.exports = WalletEngine
<commit_msg>no throwing in WalletEngine functions<commit_after>var BIP39 = require('bip39')
var ccWallet = require('cc-wallet-core')
var _ = require('lodash')

var AssetModels = require('./AssetModels')

/**
 * @class WalletEngine
 *
 * @param {Object} opts
 * @param {boolean} opts.testnet
 */
function WalletEngine(opts) {
  this.setCallback(function() {})
  this.assetModels = null

  opts = _.extend({ testnet: false }, opts)
  this.ccWallet = new ccWallet(opts)

  if (this.isInitialized())
    this._initializeWalletEngine()
}

/**
 * @param {function} callback
 */
WalletEngine.prototype.setCallback = function(callback) {
  this.updateCallback = callback
}

/**
 * @return {string}
 */
WalletEngine.prototype.generateMnemonic = BIP39.generateMnemonic

/**
 * @return {boolean}
 */
WalletEngine.prototype.isCurrentMnemonic = function(mnemonic, password) {
  var seed = BIP39.mnemonicToSeedHex(mnemonic, password)
  return this.ccWallet.isCurrentSeed(seed)
}

/**
 * @return {boolean}
 */
WalletEngine.prototype.isInitialized = function() {
  return this.ccWallet.isInitialized()
}

/**
 * @param {string} mnemonic
 * @param {string} [password]
 * @throws {Error} If already initialized
 */
WalletEngine.prototype.initialize = function(mnemonic, password) {
  var seed = BIP39.mnemonicToSeedHex(mnemonic, password)
  this.ccWallet.initialize(seed)

  this._initializeWalletEngine()
}

/**
 */
WalletEngine.prototype._initializeWalletEngine = function() {
  this.assetModels = new AssetModels(this.ccWallet)
  this.assetModels.on('update', function() { this.updateCallback() }.bind(this))
}

/**
 * @return {AssetModel[]}
 */
WalletEngine.prototype.getAssetModels = function() {
  if (this.isInitialized()) {
      return this.assetModels.getAssetModels();
  } else {
      return [];
  }
}

WalletEngine.prototype.update = function() {
  if (this.isInitialized()) {
      this.assetModels.update();
  }
}

module.exports = WalletEngine
<|endoftext|>


<commit_before>/*
 * @project {{=it.name}}
 * @author Larry Battle
 * @license {{=it.license.overview}}
 * @date 07/02/2012
 */
(function(root){
	var Input = function () {
		this.z = null;
		this.type = null;
		this.terms = null;
		this.constraints = null;
		this.isStandardMode = false;
	};
	// Holds constants
	Input.parse = function (type, z, constraints) {
		Input.checkForInputError(type, z, constraints);
		var obj = new Input();
		obj.type = type;
		obj.z = YASMIJ.Expression.parse(z);
		obj.constraints = YASMIJ.Input.getArrOfConstraints(constraints);
		obj.setTermNames();
		obj.checkConstraints();
		return obj;
	};
	Input.getArrOfConstraints = function (arr) {
		arr = (YASMIJ.Matrix.isArray(arr)) ? arr : [arr];
		var constraints = [],
		i = arr.length;
		while (i--) {
			constraints[i] = YASMIJ.Constraint.parse(arr[i]);
		}
		return constraints;
	};
	Input.getErrors = function (type, z, constraints) {
		var errMsgs = [];
		if (typeof z !== "string") {
			errMsgs.push("z must be a string.");
		}
		if (type !== "maximize" && type !== "minimize") {
			errMsgs.push("`maximize` and `minimize` are the only types that is currently supported.");
		}
		if (!YASMIJ.Matrix.isArray(constraints) || !constraints.length) {
			errMsgs.push("Constraints must be an array with at least one element.");
		}
		return errMsgs;
	};
	/**
	* Returns the problem type.
	* @note this function assume all the constraints have
	* variables on the left and constants on the right.
	* @return {String}
	*/
	Input.prototype.computeType = function(){
		var hasLessThan = this.doAnyConstrainsHaveRelation( /<=?/ );
		var hasGreaterThan = this.doAnyConstrainsHaveRelation( />=?/ );

		if( /max/.test( this.type ) ){
			return hasGreaterThan ? YASMIJ.CONST.NONSTANDARD_MAX : YASMIJ.CONST.STANDARD_MAX;
		}
		if( /min/.test( this.type ) ){
			return hasLessThan ? YASMIJ.CONST.NONSTANDARD_MIN : YASMIJ.CONST.STANDARD_MIN;
		}
	};
	/**
	* Checks if any constraints the same comparison.
	* @param {String|RegExp} comparison
	* @return {Boolean}
	*/
	Input.prototype.doAnyConstrainsHaveRelation = function(comparison){
		comparison = new RegExp(comparison);
		return this.anyConstraints(function(i, constraint){
			return comparison.test(constraint.comparison);
		});
	};
	/**
	* Checks if all constraints the same comparison.
	* @param {String|RegExp} comparison
	* @return {Boolean}
	*/
	Input.prototype.doAllConstrainsHaveRelation = function(comparison){
		comparison = new RegExp(comparison);
		return this.allConstraints(function(i, constraint){
			return comparison.test(constraint.comparison);
		});
	};
	/**
	* Checks if the callback returns a truthy value for any constraints.
	* @param {Function} fn - callback
	* @return {Boolean}
	*/
	Input.prototype.anyConstraints = function (fn) {
		for (var i = 0, len = this.constraints.length; i < len; i++) {
			if( fn(i, this.constraints[i], this.constraints) ){
				return true;
			}
		}
		return false;
	};
	/**
	* Checks if the callback returns a truthy value for all constraints.
	* @param {Function} fn - callback
	* @return {Boolean}
	*/
	Input.prototype.allConstraints = function (fn) {
		var result = true;
		for (var i = 0, len = this.constraints.length; i < len; i++) {
			result = result && !!fn(i, this.constraints[i], this.constraints);
		}
		return result;
	};
	/**
	* Iterates over a the constraints, executing the callback for each element.
	* @param {Function} fn - callback
	* @return {Boolean}
	*/
	Input.prototype.forEachConstraint = function (fn) {
		for (var i = 0, len = this.constraints.length; i < len; i++) {
			fn(i, this.constraints[i], this.constraints);
		}
	};
	Input.prototype.addNumbersToSlacks = function () {
		var c = this.constraints,
		slackI = 1;
		for (var i = 0, len = c.length; i < len; i++) {
			if (c[i].slack) {
				c[i].updateSlack("slack" + slackI);
				slackI++;
			}
		}
	};
	Input.prototype.getTermNames = function (onlyVariables) {
		var vars = [],
		i = this.constraints.length;
		while (i--) {
			vars = vars.concat(this.constraints[i].getTermNames(onlyVariables));
		}
		return YASMIJ.getUniqueArray(vars).sort();
	};
	Input.prototype.setTermNames = function () {
		this.terms = this.getTermNames();
	};
	Input.prototype.getZTermNotInAnyOfTheConstraints = function () {
		var varMissing = "",
		terms = this.z.getTermNames(),
		term,
		i = 0,
		iLen = terms.length;

		for (; !varMissing && i < iLen; i++) {
			term = terms[i];
			for (var j = 0, jLen = this.constraints.length; j < jLen; j++) {
				if (this.constraints[j].leftSide.terms[term]) {
					break;
				}
			}
			if (j === jLen) {
				varMissing = term;
			}
		}
		return varMissing;
	};
	Input.prototype.checkConstraints = function () {
		var errMsg = [],
		missingZVar = this.getZTermNotInAnyOfTheConstraints();
		if (missingZVar) {
			errMsg.push("`" + missingZVar + "`, from the objective function, should appear least once in a constraint.");
		}
		return errMsg;
	};
	Input.checkForInputError = function (type, z, constraints) {
		var arr = Input.getErrors(type, z, constraints);
		if (arr && arr.length) {
			throw new Error("Input Error: " + arr.join('\n'));
		}
	};
	Input.prototype.toString = function () {
		return [this.type + " z = " + this.z, "where " + this.constraints.join(", ")].join(", ");
	};
	Input.prototype.convertConstraintsToMaxForm = function () {
		var c = this.constraints;
		for (var i = 0, len = c.length; i < len; i++) {
			c[i] = c[i].convertToStandardMaxForm();
		}
	};
	Input.prototype.convertToStandardForm = function () {
		if (this.isStandardMode) {
			return this;
		}
		if (/min/.test(this.type)) {
			this.z = this.z.inverse();
		}
		this.convertConstraintsToMaxForm();
		this.addNumbersToSlacks();
		this.setTermNames();
		this.isStandardMode = true;
		return this;
	};
	root.Input = Input;
}(YASMIJ));
<commit_msg>Update YASMIJ.Input.js<commit_after>/*
* @project {{=it.name}}
* @author Larry Battle
* @license {{=it.license.overview}}
*/

tests.runInputTests = function(){
	module( "YASMIJ.Input Class" );
	test( "test YASMIJ.Input.prototype.addNumbersToSlacks", function(){
		var func = function(str, eqs){
			return YASMIJ.Input.parse( "maximize", str, eqs).convertToStandardForm();
		};
		var x = func( "x1 + 2x2 - x3", [
			"a < 14",
			"a + b <=28"
		]);
		var c = x.constraints.join( ", " );
		equal( /slack1/.test(c), true );
		equal( /slack2/.test(c), true );
	});
	test( "test YASMIJ.Input.prototype.getZTermNotInAnyOfTheConstraints", function(){
		var func = function(str, eqs){
			return YASMIJ.Input.parse( "maximize", str, eqs).getZTermNotInAnyOfTheConstraints();
		};
		equal( func( "a", [ "a < 1", "b < 3"] ), "");
		equal( func( "c + d", [ "c < 1", "d < 1"] ), "");

		equal( func( "a", [ "b < 3"] ), "a");
		equal( func( "c + d", [ "c < 1" ] ), "d");
	});
	test( "test YASMIJ.Input.prototype.checkConstraints", function(){
		var func = function(str, eqs){
			return YASMIJ.Input.parse( "maximize", str, eqs).checkConstraints();
		};
		ok( func( "a", [ "a < 1", "b < 3"] ) );
		ok( func( "c + d", [ "d < 1"] ));

	});
	test( "test YASMIJ.Input.prototype.convertConstraintsToMaxForm", function(){

		var func = function(str){
			var obj = {
				constraints: [ YASMIJ.Constraint.parse(str) ]
			};
			YASMIJ.Input.prototype.convertConstraintsToMaxForm.call(obj);
			return obj.constraints[0].toString();
		};
		var testThis = function(str){
			var x = YASMIJ.Constraint.parse(str).convertToStandardMaxForm().toString();
			equal( func( str ), x );
		};
		testThis( "a + b < 4" );
	});
	test( "test YASMIJ.Input.prototype.convertToStandardForm", function(){
		var func = function(str, eqs){
			return YASMIJ.Input.parse( "maximize", str, eqs);
		};
		var testThis = function(str, eqs){
			var x = func( str, eqs );
			equal( x.isStandardMode, false );
			x.convertToStandardForm();
			equal( x.isStandardMode, true );
		};
		testThis( "a + b", ["a + b < 1"] );
	});
	test( "test YASMIJ.Input.prototype.toString()", function(){
		var x = YASMIJ.Input.parse( "maximize", "x1 + 2x2 - x3", [
			"2x1+x2+x3 <= 14",
			"4x1+2x2+3x3<=28",
			"2x1+5x2+5x3<=30"
		]);
		var expected = [
			"maximize z = x1 + 2x2 - x3",
			"where 2x1 + x2 + x3 <= 14, 4x1 + 2x2 + 3x3 <= 28, 2x1 + 5x2 + 5x3 <= 30"
		].join( ", " );
		equal( x.toString(), expected );
	});
	test( "test YASMIJ.Input.prototype.getTermNames()", function(){
		var func = function(str, eqs, onlyVariables){
			return YASMIJ.Input.parse( "maximize", str, eqs).getTermNames(onlyVariables).join(", ");
		};
		equal( func( "x1 + 2x2 - x3", [
			"2x1+x2+x3 <= 14",
			"4x1+2x2+3x3<=28",
			"2x1+5x2+5x3<=30"
		]), ["x1", "x2", "x3", "14", "28", "30" ].sort().join( ", " ) );

		equal( func( "x1 + 2x2 - x3", [
			"2x1+x2+x3 <= 14",
			"4x1+2x2+3x3<=28",
			"2x1+5x2+5x3<=30"
		], true), ["x1", "x2", "x3" ].sort().join( ", " ) );
	});
	test( "test YASMIJ.Input.parse", function(){
		var x = YASMIJ.Input.parse( "maximize", "x1 + 2x2 - x3", [
			"2x1+x2+x3 <= 14",
			"4x1+2x2+3x3<=28",
			"2x1+5x2+5x3<=30"
		]);
		equal( x.type, "maximize" );
		equal( x.z.toString(), "x1 + 2x2 - x3" );
		equal( x.constraints.length, 3 );
		deepEqual( x.terms.join(", "), "14, 28, 30, x1, x2, x3" );
	});
	test( "test YASMIJ.Input.prototype.doAnyConstrainsHaveRelation()", function(){
		var fn = function(arr, comparison){
			var x = YASMIJ.Input.parse("maximize", "x1 + 2x2 - x3", arr);
			return x.doAnyConstrainsHaveRelation( comparison );
		};
		equal( fn([
			"a < 14",
			"a + b < 28"
		], /^<$/ ), true );
		equal( fn([
			"a > 14",
			"a + b > 28"
		], /^>$/ ), true );
		equal( fn([
			"a > 14",
			"a + b >= 28"
		], /^>=$/ ), true );

		equal( fn([
			"a < 14",
			"a + b <= 28"
		], /^>$/ ), false );
		equal( fn([
			"a > 14",
			"a + b >= 28"
		], /^<=$/ ), false );
	});
	test( "test YASMIJ.Input.prototype.doAllConstrainsHaveRelation()", function(){
		var fn = function(arr, comparison){
			var x = YASMIJ.Input.parse("maximize", "x1 + 2x2 - x3", arr);
			return x.doAllConstrainsHaveRelation( comparison );
		};
		equal( fn([
			"a < 14",
			"a + b < 28"
		], /^<$/ ), true );
		equal( fn([
			"a < 14",
			"a + b <= 28"
		], /^<$/ ), false );

		equal( fn([
			"a > 14",
			"a + b > 28"
		], /^>$/ ), true );
		equal( fn([
			"a > 14",
			"a + b >= 28"
		], /^>$/ ), false );
	});
	test( "test YASMIJ.Input.prototype.computeType() with (non)standard max", function(){
		var t = YASMIJ.CONST;
		var fn = function(type, arr){
			var x = YASMIJ.Input.parse(type, "x1 + 2x2 - x3", arr);
			return x.computeType();
		};
		equal( fn("maximize",[
			"a <= 14",
			"a + b <= 28"
		]), t.STANDARD_MAX );
		equal( fn("maximize",[
			"a <= 14",
			"a + b < 28"
		]), t.STANDARD_MAX );
		equal( fn("maximize",[
			"a < 14",
			"a + b < 28"
		]), t.STANDARD_MAX );

		equal( fn("maximize",[
			"a > 14",
			"a + b < 28"
		]), t.NONSTANDARD_MAX );
		equal( fn("maximize",[
			"a <= 14",
			"a + b > 28"
		]), t.NONSTANDARD_MAX );
	});
	test( "test YASMIJ.Input.prototype.computeType() with (non)standard min", function(){
		var t = YASMIJ.CONST;
		var fn = function(type, arr){
			var x = YASMIJ.Input.parse(type, "x1 + 2x2 - x3", arr);
			return x.computeType();
		};
		equal( fn("minimize",[
			"a >= 14",
			"a + b >= 28"
		]), t.STANDARD_MIN );
		equal( fn("minimize",[
			"a >= 14",
			"a + b > 28"
		]), t.STANDARD_MIN );
		equal( fn("minimize",[
			"a > 14",
			"a + b > 28"
		]), t.STANDARD_MIN );

		equal( fn("minimize",[
			"a > 14",
			"a + b < 28"
		]), t.NONSTANDARD_MIN );
		equal( fn("minimize",[
			"a <= 14",
			"a + b > 28"
		]), t.NONSTANDARD_MIN );
	});
};
<|endoftext|>


<commit_before>/**
 * @file Dom vendor
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

function getOffset(el) {

    if (!el) {
        return null;
    }

    if (el.getBoundingClientRect) {

        const result = el.getBoundingClientRect();

        return {
            top: result.top + getScrollTop(),
            left: result.left + getScrollLeft()
        };

    }

    let offset = {
        top: el.offsetTop,
        left: el.offsetLeft
    };
    while (el.offsetParent) {
        el = el.offsetParent;
        offset.top += el.offsetTop;
        offset.left += el.offsetLeft;
    }

    return offset;

}

function getScrollHeight() {
    return document.body.scrollHeight || document.documentElement.scrollHeight;
}

function getScrollLeft() {

    if (window.SCROLL_EL && window.SCROLL_EL.scrollLeft) {
        return SCROLL_EL.scrollLeft;
    }

    return document.body.scrollLeft || document.documentElement.scrollLeft;

}

function getScrollTop() {

    if (window.SCROLL_EL && window.SCROLL_EL.scrollTop) {
        return SCROLL_EL.scrollTop;
    }

    return document.body.scrollTop || document.documentElement.scrollTop;

}

function hasClass(el, className) {

    if (!el || !className) {
        return false;
    }

    const elClassName = el.className;

    if (!elClassName) {
        return false;
    }

    const elClass = elClassName.split(/\s+/);

    return elClass && elClass.findIndex(item => item === className) !== -1;

}

function addClass(el, className) {

    if (!el || !className) {
        return;
    }

    const elClassName = el.className;

    if (!elClassName) {
        el.className = className;
        return;
    }

    const elClass = elClassName.split(/\s+/),
        index = elClass ? elClass.findIndex(item => item === className) : -1;

    if (index !== -1) { // already has this className
        return;
    }

    elClass.push(className);
    el.className = elClass.join(' ');

}

function removeClass(el, className) {

    if (!el || !className) {
        return;
    }

    const elClassName = el.className;

    if (!elClassName) {
        return;
    }

    const elClass = elClassName.split(/\s+/),
        index = elClass ? elClass.findIndex(item => item === className) : -1;

    if (index === -1) { // no this className
        return;
    }

    elClass.splice(index, 1);
    el.className = elClass.join(' ');

}

function toggleClass(el, className, bool) {
    bool ?
        addClass(el, className)
        :
        removeClass(el, className);
}

function findParentByClassName(el, className) {

    if (!el || !className) {
        return;
    }

    while (el) {
        if (hasClass(el, className)) {
            return el;
        }
        el = el.parentNode;
    }

    return;

}

function isParent(el, parentEl) {

    if (!el || !parentEl) {
        return false;
    }

    do {

        el = el.parentNode;

        if (el == parentEl) {
            return true;
        }

    } while (el);

    return false;

}

export default {
    getOffset,
    getScrollHeight,
    getScrollLeft,
    getScrollTop,
    hasClass,
    addClass,
    removeClass,
    toggleClass,
    findParentByClassName,
    isParent
};<commit_msg>update Dom<commit_after>/**
 * @file Dom vendor
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

function getOffset(el) {

    if (!el) {
        return null;
    }

    if (el.getBoundingClientRect) {

        const result = el.getBoundingClientRect();

        return {
            top: result.top + getScrollTop(),
            left: result.left + getScrollLeft()
        };

    }

    let offset = {
        top: el.offsetTop,
        left: el.offsetLeft
    };
    while (el.offsetParent) {
        el = el.offsetParent;
        offset.top += el.offsetTop;
        offset.left += el.offsetLeft;
    }

    return offset;

}

function getScrollHeight() {
    return document.body.scrollHeight || document.documentElement.scrollHeight;
}

function getScrollLeft() {

    if (window.SCROLL_EL && window.SCROLL_EL.scrollLeft) {
        return SCROLL_EL.scrollLeft;
    }

    return document.body.scrollLeft || document.documentElement.scrollLeft;

}

function getScrollTop() {

    if (window.SCROLL_EL && window.SCROLL_EL.scrollTop) {
        return SCROLL_EL.scrollTop;
    }

    return document.body.scrollTop || document.documentElement.scrollTop;

}

function hasClass(el, className) {

    if (!el || !className) {
        return false;
    }

    const elClassName = el.className;

    if (!elClassName) {
        return false;
    }

    const elClass = elClassName.split(/\s+/);

    return elClass && elClass.findIndex(item => item === className) !== -1;

}

function addClass(el, className) {

    if (!el || !className) {
        return;
    }

    const elClassName = el.className;

    if (!elClassName) {
        el.className = className;
        return;
    }

    const elClass = elClassName.split(/\s+/),
        index = elClass ? elClass.findIndex(item => item === className) : -1;

    if (index !== -1) { // already has this className
        return;
    }

    elClass.push(className);
    el.className = elClass.join(' ');

}

function removeClass(el, className) {

    if (!el || !className) {
        return;
    }

    const elClassName = el.className;

    if (!elClassName) {
        return;
    }

    const elClass = elClassName.split(/\s+/),
        index = elClass ? elClass.findIndex(item => item === className) : -1;

    if (index === -1) { // no this className
        return;
    }

    elClass.splice(index, 1);
    el.className = elClass.join(' ');

}

function toggleClass(el, className, bool) {
    bool ?
        addClass(el, className)
        :
        removeClass(el, className);
}

function findParentByClassName(el, className) {

    if (!el || !className) {
        return;
    }

    while (el) {
        if (hasClass(el, className)) {
            return el;
        }
        el = el.parentNode;
    }

    return;

}

function isParent(el, parentEl) {

    if (!el || !parentEl) {
        return false;
    }

    do {

        el = el.parentNode;

        if (el == parentEl) {
            return true;
        }

    } while (el);

    return false;

}

function isScrollable(...values) {
    return values.some(value => value === 'auto' || value === 'scroll');
}

function isElementScrollable(el) {
    const style = window.getComputedStyle(el);
    return isScrollable(style.overflow, style.overflowY, style.overflowX);
};

function getClosestScrollable(el) {

    if (el == null) {
        return null;
    }

    if (!isElementScrollable(el)) {
        return getClosestScrollable(el.parentElement);
    }

    return el;

}

export default {
    getOffset,
    getScrollHeight,
    getScrollLeft,
    getScrollTop,
    hasClass,
    addClass,
    removeClass,
    toggleClass,
    findParentByClassName,
    isParent,
    getClosestScrollable
};
<|endoftext|>


<commit_before>/**
 * @file Dom vendor
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

function getOffset(el) {

    if (!el) {
        return null;
    }

    if (el.getBoundingClientRect) {

        const result = el.getBoundingClientRect();

        return {
            top: result.top + getScrollTop(),
            left: result.left + getScrollLeft()
        };

    }

    let offset = {
        top: el.offsetTop,
        left: el.offsetLeft
    };
    while (el.offsetParent) {
        el = el.offsetParent;
        offset.top += el.offsetTop;
        offset.left += el.offsetLeft;
    }

    return offset;

}

function getScrollHeight() {
    return document.body.scrollHeight || document.documentElement.scrollHeight;
}

function getScrollLeft() {

    if (window.SCROLL_EL && window.SCROLL_EL.scrollLeft) {
        return SCROLL_EL.scrollLeft;
    }

    return document.body.scrollLeft || document.documentElement.scrollLeft;

}

function getScrollTop() {

    if (window.SCROLL_EL && window.SCROLL_EL.scrollTop) {
        return SCROLL_EL.scrollTop;
    }

    return document.body.scrollTop || document.documentElement.scrollTop;

}

function hasClass(el, className) {

    if (!el || !className) {
        return false;
    }

    const elClassName = el.className;

    if (!elClassName) {
        return false;
    }

    const elClass = elClassName.split(/\s+/);

    return elClass.findIndex(item => item === className) !== -1;

}

function addClass(el, className) {

    if (!el || !className) {
        return;
    }

    const elClassName = el.className;

    if (!elClassName) {
        el.className = className;
        return;
    }

    const elClass = elClassName.split(/\s+/),
        index = elClass.findIndex(item => item === className);

    if (index !== -1) { // already has this className
        return;
    }

    elClass.push(className);
    el.className = elClass.join(' ');

}

function removeClass(el, className) {

    if (!el || !className) {
        return;
    }

    const elClassName = el.className;

    if (!elClassName) {
        return;
    }

    const elClass = elClassName.split(/\s+/),
        index = elClass.findIndex(item => item === className);

    if (index === -1) { // no this className
        return;
    }

    elClass.splice(index, 1);
    el.className = elClass.join(' ');

}

function toggleClass(el, className, bool) {
    bool ?
        addClass(el, className)
        :
        removeClass(el, className);
}

function findParentByClassName(el, className) {

    if (!el || !className) {
        return;
    }

    while (el) {
        if (hasClass(el, className)) {
            return el;
        }
        el = el.parentNode;
    }

    return;

}

function hasParent(el, parentEl) {

    if (!el || !parentEl) {
        return false;
    }

    do {

        el = el.parentNode;

        if (el == parentEl) {
            return true;
        }

    } while (el);

    return false;

}

export default {
    getOffset,
    getScrollHeight,
    getScrollLeft,
    getScrollTop,
    hasClass,
    addClass,
    removeClass,
    toggleClass,
    findParentByClassName,
    hasParent
};<commit_msg>update Dom<commit_after>/**
 * @file Dom vendor
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

function getOffset(el) {

    if (!el) {
        return null;
    }

    if (el.getBoundingClientRect) {

        const result = el.getBoundingClientRect();

        return {
            top: result.top + getScrollTop(),
            left: result.left + getScrollLeft()
        };

    }

    let offset = {
        top: el.offsetTop,
        left: el.offsetLeft
    };
    while (el.offsetParent) {
        el = el.offsetParent;
        offset.top += el.offsetTop;
        offset.left += el.offsetLeft;
    }

    return offset;

}

function getScrollHeight() {
    return document.body.scrollHeight || document.documentElement.scrollHeight;
}

function getScrollLeft() {

    if (window.SCROLL_EL && window.SCROLL_EL.scrollLeft) {
        return SCROLL_EL.scrollLeft;
    }

    return document.body.scrollLeft || document.documentElement.scrollLeft;

}

function getScrollTop() {

    if (window.SCROLL_EL && window.SCROLL_EL.scrollTop) {
        return SCROLL_EL.scrollTop;
    }

    return document.body.scrollTop || document.documentElement.scrollTop;

}

function hasClass(el, className) {

    if (!el || !className) {
        return false;
    }

    const elClassName = el.className;

    if (!elClassName) {
        return false;
    }

    const elClass = elClassName.split(/\s+/);

    return elClass.findIndex(item => item === className) !== -1;

}

function addClass(el, className) {

    if (!el || !className) {
        return;
    }

    const elClassName = el.className;

    if (!elClassName) {
        el.className = className;
        return;
    }

    const elClass = elClassName.split(/\s+/),
        index = elClass.findIndex(item => item === className);

    if (index !== -1) { // already has this className
        return;
    }

    elClass.push(className);
    el.className = elClass.join(' ');

}

function removeClass(el, className) {

    if (!el || !className) {
        return;
    }

    const elClassName = el.className;

    if (!elClassName) {
        return;
    }

    const elClass = elClassName.split(/\s+/),
        index = elClass.findIndex(item => item === className);

    if (index === -1) { // no this className
        return;
    }

    elClass.splice(index, 1);
    el.className = elClass.join(' ');

}

function toggleClass(el, className, bool) {
    bool ?
        addClass(el, className)
        :
        removeClass(el, className);
}

function findParentByClassName(el, className) {

    if (!el || !className) {
        return;
    }

    while (el) {
        if (hasClass(el, className)) {
            return el;
        }
        el = el.parentNode;
    }

    return;

}

function isParent(el, parentEl) {

    if (!el || !parentEl) {
        return false;
    }

    do {

        el = el.parentNode;

        if (el == parentEl) {
            return true;
        }

    } while (el);

    return false;

}

export default {
    getOffset,
    getScrollHeight,
    getScrollLeft,
    getScrollTop,
    hasClass,
    addClass,
    removeClass,
    toggleClass,
    findParentByClassName,
    isParent
};<|endoftext|>


<commit_before>import types from 'constants'
import { push } from 'react-router-redux'

const { EDIT_PAGE } = types

const doEdit = (content) => {
    return {
        type: EDIT_PAGE,
        payload: {
            content: content
        }
    }
}

export const editPage = (content, name) => {
    return (dispatch) => {
        dispatch(doEdit(content))
        dispatch(push(`/page/${name}/edit`))
    }
}
<commit_msg>action to edit info pages<commit_after>import types from 'constants'
import { push } from 'react-router-redux'

const { EDIT_PAGE } = types

const doEdit = (content) => {
    return {
        type: EDIT_PAGE,
        payload: {
            content: content
        }
    }
}

export const editPage = (content, name) => {
    return (dispatch) => {
        dispatch(doEdit(content))
        dispatch(push(`/page/${name}/edit`))
    }
}

export const editInfoPage = (content, name) => {
    return (dispatch) => {
        dispatch(doEdit(content))
        dispatch(push(`${name}/information/edit`))
    }
}
<|endoftext|>


<commit_before>import moment from 'moment'

import manager from '../manager'
import AlarmAct from '../acts/Alarm'

import Alarm from './Alarm'

const init = async () => {
  await Alarm.clearAll()

  const {hours: hour, minutes: minute, seconds: second} = moment().add(5, 's').toObject()
  // const [hour, minute, second] = [7, 30, 0]

  const testAlarm = new Alarm({
    name: 'Test 1',
    scheduleDescriptor: {hour, minute, second}
  })
  await testAlarm.save()

  const alarms = await Alarm.fromDB()
  const scheduledAlarms = alarms.map(alarm => alarm.schedule(() => manager.connect(new AlarmAct(alarm))))

  console.log('Alarms will trigger at', scheduledAlarms.map(alarm => alarm.scheduleDescriptor))
}

export default init
export {Alarm}
<commit_msg>👷 Quicker Testing<commit_after>import moment from 'moment'

import manager from '../manager'
import AlarmAct from '../acts/Alarm'

import Alarm from './Alarm'

const init = async () => {
  await Alarm.clearAll()

  const {hours: hour, minutes: minute, seconds: second} = moment().add(2, 's').toObject()
  // const [hour, minute, second] = [7, 30, 0]

  const testAlarm = new Alarm({
    name: 'Test 1',
    scheduleDescriptor: {hour, minute, second}
  })
  await testAlarm.save()

  const alarms = await Alarm.fromDB()
  const scheduledAlarms = alarms.map(alarm => alarm.schedule(() => manager.connect(new AlarmAct(alarm))))

  console.log('Alarms will trigger at', scheduledAlarms.map(alarm => alarm.scheduleDescriptor))
}

export default init
export {Alarm}
<|endoftext|>


<commit_before>(function() {
	$(document).ready(function() {

		var publicationsJSON = []
		authorsJSON = [];

		// create a new pubDB json object
		var converter = new pubDB.json();

		// initialize -> get a jQuery object of html contents in callback function
		converter.init(function(dbObject) {
		// pass dbObject to buildJSON method -> get a json object back (<- created on client side)
			converter.buildPublicationJSON(dbObject, function(pubData) {
			publicationsJSON = pubData;

			converter.buildAuthorJSON(pubData, function(authorData) {
			authorsJSON = authorData;

		  var w = 960;    //width
		  var h = 500     //height

		  var color = d3.scale.category20();    //different colours

		  var force = d3.layout.force()     //force-directed layout
			.charge(-120)           //charge-strength
			.linkDistance(30)         //target distance between linked nodes
			.size([w, h]);            //layout size

		  var svg = d3.select("body").append("svg")
			.attr("width", w)
			.attr("height", h);

		  d3.json("./DATA/authorsTest.json", function (error, graph) { //get data from "authorsTest.json"
			force                       //callback?
			  .nodes(graph.nodes)
			  .links(graph.links)
			  .start();           //start or restart the simulation when the nodes change

			var link = svg.selectAll(".link")
			  .data(graph.links)
			  .enter().append("line")
			  .attr("class", "link")
			  .style("stroke-width", function (d){return Math.sqrt(d.value); });

			var node = svg.selectAll(".node")
			  .data(graph.nodes)
			  .enter().append("circle")
			  .attr("class", "nodes")
			  .attr("r", 5)
			  .on("mouseup", authorClicked)
			  .style("fill", function(d) {
				return color(d.group);
				})
			  .call(force.drag);

			node.append("title")
			  .text(function (d) {return d.name;});

			force.on("tick", function() {   //listen to updates in the computed layout positions
			  link.attr("x1", function (d) { return d.source.x; })
			  .attr("y1", function (d) { return d.source.y; })
			  .attr("x2", function (d) { return d.target.x; })
			  .attr("y2", function (d) {return d.target.y });

			node.attr("cx", function (d) {return d.x;})
			  .attr("cy", function (d) {return d.y});
			  });

			 //fisheye

			var fisheye = d3.fisheye.circular()
			  .radius(120)
			  .distortion(2);

			svg.on("mousemove", function(){
				fisheye.focus(d3.mouse(this));

				node.each(function(d) { d.fisheye = fisheye(d); })
				.attr("cx", function(d) { return d.fisheye.x; })
				.attr("cy", function(d) { return d.fisheye.y; })
				.attr("r", function(d) { return d.fisheye.z * 4.5; });

				link.attr("x1", function(d) { return d.source.fisheye.x; })
				.attr("y1", function(d) { return d.source.fisheye.y; })
				.attr("x2", function(d) { return d.target.fisheye.x; })
				.attr("y2", function(d) { return d.target.fisheye.y; });
			});

		  });

		  function authorClicked () {
				// FEHLT: Übertragung welcher Autor geladen wird!
				location.replace("HTML/author.html");
			  };

	        });
      });
    });
	});
})();<commit_msg>author-network changed<commit_after>(function() {
	$(document).ready(function() {

		var publicationsJSON = []
		authorsJSON = [];
		var nodes = "{'nodes':[";
		var links;

		// create a new pubDB json object
		var converter = new pubDB.json();

		// initialize -> get a jQuery object of html contents in callback function
		converter.init(function(dbObject) {
		// pass dbObject to buildJSON method -> get a json object back (<- created on client side)
			converter.buildPublicationJSON(dbObject, function(pubData) {
			publicationsJSON = pubData;

			converter.buildAuthorJSON(pubData, function(authorData) {
			authorsJSON = authorData;

			//console.log(publicationsJSON);

		  var w = 960;    //width
		  var h = 500     //height

		  var color = d3.scale.category20();    //different colours

		  for (var i = 0, l = publicationsJSON.length; i < l; i += 1) {
            for (var j = 0, m = publicationsJSON[i].authors.length; j < m; j += 1) {

			  nodes = nodes + "{'name':'" + publicationsJSON[i].authors[j].name + "','group':" + i + "},";

            }
          }

		  //nodes = nodes + "]}";
		  console.log(nodes);

		  var force = d3.layout.force()     //force-directed layout
			.charge(-120)           //charge-strength
			.linkDistance(30)         //target distance between linked nodes
			.size([w, h]);            //layout size

		  var svg = d3.select("body").append("svg")
			.attr("width", w)
			.attr("height", h);

		  d3.json("./DATA/authorsTest.json", function (error, graph) { //get data from "authorsTest.json"
			force                       //callback?
			  .nodes(graph.nodes)
			  .links(graph.links)
			  .start();           //start or restart the simulation when the nodes change

			var link = svg.selectAll(".link")
			  .data(graph.links)
			  .enter().append("line")
			  .attr("class", "link")
			  .style("stroke-width", function (d){return Math.sqrt(d.value); });

			var node = svg.selectAll(".node")
			  .data(graph.nodes)
			  .enter().append("circle")
			  .attr("class", "nodes")
			  .attr("r", 5)
			  .on("mouseup", authorClicked)
			  .style("fill", function(d) {
				return color(d.group);
				})
			  .call(force.drag);

			node.append("title")
			  .text(function (d) {return d.name;});

			force.on("tick", function() {   //listen to updates in the computed layout positions
			  link.attr("x1", function (d) { return d.source.x; })
			  .attr("y1", function (d) { return d.source.y; })
			  .attr("x2", function (d) { return d.target.x; })
			  .attr("y2", function (d) {return d.target.y });

			node.attr("cx", function (d) {return d.x;})
			  .attr("cy", function (d) {return d.y});
			  });

			 //fisheye

			var fisheye = d3.fisheye.circular()
			  .radius(120)
			  .distortion(2);

			svg.on("mousemove", function(){
				fisheye.focus(d3.mouse(this));

				node.each(function(d) { d.fisheye = fisheye(d); })
				.attr("cx", function(d) { return d.fisheye.x; })
				.attr("cy", function(d) { return d.fisheye.y; })
				.attr("r", function(d) { return d.fisheye.z * 4.5; });

				link.attr("x1", function(d) { return d.source.fisheye.x; })
				.attr("y1", function(d) { return d.source.fisheye.y; })
				.attr("x2", function(d) { return d.target.fisheye.x; })
				.attr("y2", function(d) { return d.target.fisheye.y; });
			});

		  });

		  function authorClicked () {
				// FEHLT: Übertragung welcher Autor geladen wird!
				location.replace("HTML/author.html");
			  };

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


<commit_before>import React from 'react';
import NotificationsContainer from './containers/notifications_container';
import PropTypes from 'prop-types';
import LoadingBarContainer from './containers/loading_bar_container';
import TabsBar from './components/tabs_bar';
import ModalContainer from './containers/modal_container';
import { connect } from 'react-redux';
import { isMobile } from '../../is_mobile';
import { debounce } from 'lodash';
import { uploadCompose } from '../../actions/compose';
import { refreshHomeTimeline } from '../../actions/timelines';
import { refreshNotifications } from '../../actions/notifications';
import UploadArea from './components/upload_area';
import ColumnsAreaContainer from './containers/columns_area_container';

const noOp = () => false;

class UI extends React.PureComponent {

  static defaultProps = {
    intent: false,
  };

  static propTypes = {
    dispatch: PropTypes.func.isRequired,
    children: PropTypes.node,
    intent: PropTypes.bool,
  };

  state = {
    width: window.innerWidth,
    draggingOver: false,
  };

  handleResize = () => {
    this.setState({ width: window.innerWidth });
  }

  handleDragEnter = (e) => {
    e.preventDefault();

    if (!this.dragTargets) {
      this.dragTargets = [];
    }

    if (this.dragTargets.indexOf(e.target) === -1) {
      this.dragTargets.push(e.target);
    }

    if (e.dataTransfer && e.dataTransfer.types.includes('Files')) {
      this.setState({ draggingOver: true });
    }
  }

  handleDragOver = (e) => {
    e.preventDefault();
    e.stopPropagation();

    try {
      e.dataTransfer.dropEffect = 'copy';
    } catch (err) {

    }

    return false;
  }

  handleDrop = (e) => {
    e.preventDefault();

    this.setState({ draggingOver: false });

    if (e.dataTransfer && e.dataTransfer.files.length === 1) {
      this.props.dispatch(uploadCompose(e.dataTransfer.files));
    }
  }

  handleDragLeave = (e) => {
    e.preventDefault();
    e.stopPropagation();

    this.dragTargets = this.dragTargets.filter(el => el !== e.target && this.node.contains(el));

    if (this.dragTargets.length > 0) {
      return;
    }

    this.setState({ draggingOver: false });
  }

  closeUploadModal = () => {
    this.setState({ draggingOver: false });
  }

  componentWillMount () {
    window.addEventListener('resize', this.handleResize, { passive: true });
    document.addEventListener('dragenter', this.handleDragEnter, false);
    document.addEventListener('dragover', this.handleDragOver, false);
    document.addEventListener('drop', this.handleDrop, false);
    document.addEventListener('dragleave', this.handleDragLeave, false);
    document.addEventListener('dragend', this.handleDragEnd, false);

<<<<<<>>>>>> 947887f261f74f84312327a5265553e8f16655fe
  }

  componentWillUnmount () {
    window.removeEventListener('resize', this.handleResize);
    document.removeEventListener('dragenter', this.handleDragEnter);
    document.removeEventListener('dragover', this.handleDragOver);
    document.removeEventListener('drop', this.handleDrop);
    document.removeEventListener('dragleave', this.handleDragLeave);
    document.removeEventListener('dragend', this.handleDragEnd);
  }

  setRef = (c) => {
    this.node = c;
  }

  render () {
    const { width, draggingOver } = this.state;
    const { intent, children } = this.props;

    if (intent) {
      return children;
    }

    return (

        <TabsBar />
        <ColumnsAreaContainer singleColumn={isMobile(width)}>{children}</ColumnsAreaContainer>
        <NotificationsContainer />
        <LoadingBarContainer className='loading-bar' />
        <ModalContainer />
        <UploadArea active={draggingOver} onClose={this.closeUploadModal} />

    );
  }

}

export default connect()(UI);
<commit_msg>Resolve a merged conflict - app/javascript/mastodon/features/ui/index.js<commit_after>import React from 'react';
import NotificationsContainer from './containers/notifications_container';
import PropTypes from 'prop-types';
import LoadingBarContainer from './containers/loading_bar_container';
import TabsBar from './components/tabs_bar';
import ModalContainer from './containers/modal_container';
import { connect } from 'react-redux';
import { isMobile } from '../../is_mobile';
import { debounce } from 'lodash';
import { uploadCompose } from '../../actions/compose';
import { refreshHomeTimeline } from '../../actions/timelines';
import { refreshNotifications } from '../../actions/notifications';
import UploadArea from './components/upload_area';
import ColumnsAreaContainer from './containers/columns_area_container';

const noOp = () => false;

class UI extends React.PureComponent {

  static defaultProps = {
    intent: false,
  };

  static propTypes = {
    dispatch: PropTypes.func.isRequired,
    children: PropTypes.node,
    intent: PropTypes.bool,
  };

  state = {
    width: window.innerWidth,
    draggingOver: false,
  };

  handleResize = () => {
    this.setState({ width: window.innerWidth });
  }

  handleDragEnter = (e) => {
    e.preventDefault();

    if (!this.dragTargets) {
      this.dragTargets = [];
    }

    if (this.dragTargets.indexOf(e.target) === -1) {
      this.dragTargets.push(e.target);
    }

    if (e.dataTransfer && e.dataTransfer.types.includes('Files')) {
      this.setState({ draggingOver: true });
    }
  }

  handleDragOver = (e) => {
    e.preventDefault();
    e.stopPropagation();

    try {
      e.dataTransfer.dropEffect = 'copy';
    } catch (err) {

    }

    return false;
  }

  handleDrop = (e) => {
    e.preventDefault();

    this.setState({ draggingOver: false });

    if (e.dataTransfer && e.dataTransfer.files.length === 1) {
      this.props.dispatch(uploadCompose(e.dataTransfer.files));
    }
  }

  handleDragLeave = (e) => {
    e.preventDefault();
    e.stopPropagation();

    this.dragTargets = this.dragTargets.filter(el => el !== e.target && this.node.contains(el));

    if (this.dragTargets.length > 0) {
      return;
    }

    this.setState({ draggingOver: false });
  }

  closeUploadModal = () => {
    this.setState({ draggingOver: false });
  }

  componentWillMount () {
    window.addEventListener('resize', this.handleResize, { passive: true });
    document.addEventListener('dragenter', this.handleDragEnter, false);
    document.addEventListener('dragover', this.handleDragOver, false);
    document.addEventListener('drop', this.handleDrop, false);
    document.addEventListener('dragleave', this.handleDragLeave, false);
    document.addEventListener('dragend', this.handleDragEnd, false);

    if (!this.props.intent) {
      this.props.dispatch(refreshHomeTimeline());
      this.props.dispatch(refreshNotifications());
    }
  }

  componentWillUnmount () {
    window.removeEventListener('resize', this.handleResize);
    document.removeEventListener('dragenter', this.handleDragEnter);
    document.removeEventListener('dragover', this.handleDragOver);
    document.removeEventListener('drop', this.handleDrop);
    document.removeEventListener('dragleave', this.handleDragLeave);
    document.removeEventListener('dragend', this.handleDragEnd);
  }

  setRef = (c) => {
    this.node = c;
  }

  render () {
    const { width, draggingOver } = this.state;
    const { intent, children } = this.props;

    if (intent) {
      return children;
    }

    return (

        <TabsBar />
        <ColumnsAreaContainer singleColumn={isMobile(width)}>{children}</ColumnsAreaContainer>
        <NotificationsContainer />
        <LoadingBarContainer className='loading-bar' />
        <ModalContainer />
        <UploadArea active={draggingOver} onClose={this.closeUploadModal} />

    );
  }

}

export default connect()(UI);
<|endoftext|>


<commit_before>export class About {
  actors = [
    {
      'name': 'Bryan Cranston',
      'episodes': 62,
      'description': 'Bryan Cranston played the role of Walter in Breaking Bad. He is also known for playing Hal in Malcom in the Middle.',
      'image': 'bryan-cranston.jpg'
    }, {
      'name': 'Aaron Paul',
      'episodes': 62,
      'description': 'Aaron Paul played the role of Jesse in Breaking Bad. He also featured in the "Need For Speed" Movie.',
      'image': 'aaron-paul.jpg'
    }, {
      'name': 'Bob Odenkirk',
      'episodes': 62,
      'description': 'Bob Odenkrik played the role of Saul in Breaking Bad. Due to public fondness for the character, Bob stars in his own show now, called "Better Call Saul".',
      'image': 'bob-odenkirk.jpg'
    }
  ];

  attached() {
    // let bridge = System.get(System.normalizeSync('aurelia-materialize-bridge'));
    // this.version = bridge.version;
    this.version = '0.10.1';
  }

  onSelectionChanged(e) {
    let selected = this.list.getSelected();
    let names = selected.map(i => i.name);
    this.logger.log('selection changed: ' + names.join(', '));
    // this.logger.log(`selection changed ${e.detail.item.name}`);
  }
}
<commit_msg>chore(sample): increase version<commit_after>export class About {
  actors = [
    {
      'name': 'Bryan Cranston',
      'episodes': 62,
      'description': 'Bryan Cranston played the role of Walter in Breaking Bad. He is also known for playing Hal in Malcom in the Middle.',
      'image': 'bryan-cranston.jpg'
    }, {
      'name': 'Aaron Paul',
      'episodes': 62,
      'description': 'Aaron Paul played the role of Jesse in Breaking Bad. He also featured in the "Need For Speed" Movie.',
      'image': 'aaron-paul.jpg'
    }, {
      'name': 'Bob Odenkirk',
      'episodes': 62,
      'description': 'Bob Odenkrik played the role of Saul in Breaking Bad. Due to public fondness for the character, Bob stars in his own show now, called "Better Call Saul".',
      'image': 'bob-odenkirk.jpg'
    }
  ];

  attached() {
    // let bridge = System.get(System.normalizeSync('aurelia-materialize-bridge'));
    // this.version = bridge.version;
    this.version = '0.10.2';
  }

  onSelectionChanged(e) {
    let selected = this.list.getSelected();
    let names = selected.map(i => i.name);
    this.logger.log('selection changed: ' + names.join(', '));
    // this.logger.log(`selection changed ${e.detail.item.name}`);
  }
}
<|endoftext|>


<commit_before>export { Same, Bool, Int, ActivationFunction };
export { AvgMax_Or_ChannelMultiplier, channelCount1_pointwise1Before };
export { WhetherShuffleChannel };

import * as ValueRange from "./ValueRange.js";

/**
 * Describe some properties of a non-converting parameter.
 *
 * @member {ValueRange.Same} range
 *   The range of the parameter's all possible values. It is a ValueRange.Same object.
 *
 */
class Same {

  constructor() {
    this.range = ValueRange.Same.Singleton;
  }

  /** @return {string} Return the string value. */
  getStringOf( value ) {
    return value.toString();
  }
}

/** The only one ValueDesc.Same instance. */
Same.Singleton = new Same;

/**
 * Describe some properties of a boolean parameter.
 *
 * @member {ValueRange.Bool} range
 *   The boolean range of the parameter's all possible values. It is a ValueRange.Bool object.
 *
 */
class Bool {

  constructor() {
    this.range = ValueRange.Bool.Singleton;
  }

  /** @return {string} Return the string value. */
  getStringOf( value ) {
    return value.toString();
  }
}

/** The only one ValueDesc.Bool instance. */
Bool.Singleton = new Bool;

/**
 * Describe some properties of an integer parameter.
 *
 * @member {ValueRange.Int} range
 *   The integer range of the parameter's all possible values. It is an ValueRange.Int object with ( min = valueIntegerMin )
 * and ( max = valueIntegerMax ).
 *
 * @member {string[]} valueNames
 *   The string names of the parameter's all named values. It is an array of strings. They should be all legal identifers too (i.e. A-Z,
 * a-z, 0-9 (not at first character), and "_"). They will become the properties' names of this.Ids. Note that
 * ( valueNames.length <= range.kinds ). This means that only first valueNames.length values have names. So, it is possible
 * that all values do not have names (when valueNames[] is empty).
 *
 * @member {object[]} valueObjects
 *   The extra objects of the parameter values. It is an array of objects. They will become the properties' names of this.extraObjects.
 * Note that ( valueObjects.length <= range.kinds ). This means that only first valueObjects.length values have names. So, it is possible
 * that all values do not have extra objects (when valueObjects[] is empty).
 *
 * @member {Object} Ids
 *   An object contains the parameter's all named values. It is just like a name-to-integer Map (this.nameToIntegerMap), but
 * could be accessed by dot (.) operator (not by .get() method). This could be used as a constant enumeration. The
 * this.Ids.valueName will be valueInteger. Or, the this.Ids[ valueName ] will be valueInteger. That is:
 *   - this.Ids[ valueNames[ 0 ] ] = valueIntegers[ 0 ] = ( valueIntegerMin + 0 )
 *   - this.Ids[ valueNames[ 1 ] ] = valueIntegers[ 1 ] = ( valueIntegerMin + 1 )
 *   - ...
 *   - this.Ids[ valueNames[ ( valueNames.length - 1 ) ] ] = valueIntegers[ valueNames.length - 1 ] = ( valueIntegerMin + ( valueNames.length - 1 ) )
 *
 * @member {Map} nameToIntegerMap
 *   A map object contains the parameter's all named values. Using this.nameToIntegerMap.get( name ) could get the integer value of
 * the name.
 *
 * @member {Map} integerToNameMap
 *   A map object contains the parameter's all named values. Using this.integerToNameMap.get( integerValue ) could get the name of
 * the integer value.
 *
 * @member {Map} integerToObjectMap
 *   A map object contains the parameter's all object values. Using this.integerToObjectMap.get( integerValue ) could get the extra
 * object of the integer value.
 *
 */
class Int {

  /**
   *
   * @param {number} valueIntegerMin
   *   The first (i.e. minimum) integer of the parameter's all possible values.
   *
   * @param {number} valueIntegerMax
   *   The last (i.e. maximum) integer of the parameter's all possible values. It should equal ( valueIntegerMin + ( valueNames.length - 1 ) ).
   */
  constructor( valueIntegerMin, valueIntegerMax, valueNames = [], valueObjects = [] ) {

    this.range = new ValueRange.Int( valueIntegerMin, valueIntegerMax );
    this.valueNames = valueNames;
    this.valueObjects = valueObjects;

    this.Ids = {};
    this.integerToNameMap = new Map;
    this.nameToIntegerMap = new Map;
    for ( let i = 0; i < valueNames.length; ++i ) {
      let integerId = ( valueIntegerMin + i );
      let name = valueNames[ i ];
      this.Ids[ name ] = integerId;
      this.integerToNameMap.set( integerId, name );
      this.nameToIntegerMap.set( name, integerId );
    }

    this.integerToObjectMap = new Map;
    for ( let i = 0; i < valueObjects.length; ++i ) {
      let integerId = ( valueIntegerMin + i );
      let object = valueObjects[ i ];
      this.integerToObjectMap.set( integerId, object );
    }
  }

  /**
   * @return {string}
   *   Return the name of the integerValue. If no name, return the string of the integer value (e.g. "1", "2", ..., "64").
   */
  getStringOf( integerValue ) {
    let name = this.integerToNameMap.get( integerValue ); // Look up whether has name (e.g. "AVG", "MAX", "NONE").
    if ( null == name ) {
      name = integerValue.toString();
    }
    return name;
  }

}

/**
 * Describe activation function parameter's id, range, name.
 */
class ActivationFunction extends Int {

  constructor() {
    // Note:
    //   - NONE: Beware. It easily results in infinity value because it does not have upper bound.
    //   - RELU: Beware. It easily results in infinity value because it does not have upper bound.
    //   - SOFTPLUS: Avoid. Backend WASM does not support it.
    super( 0, 6,
      [ "NONE",  "RELU6",  "SIGMOID",  "TANH",  "COS",  "SIN",  "RELU" ], //  "SOFTPLUS" ],
      [   null, tf.relu6, tf.sigmoid, tf.tanh, tf.cos, tf.sin, tf.relu ]  // tf.softplus ]
    );
  }

}

/** The only one ValueDesc.ActivationFunction instance. */
ActivationFunction.Singleton = new ActivationFunction;

/** Describe depthwise operation's id, range, name.
 *
 * Convert number value into integer between [ -2, 32 ] representing depthwise operation:
 *   - -2: average pooling. (AVG)
 *   - -1: maximum pooling. (MAX)
 *   -  0: no depthwise operation. (NONE)
 *   - [ 1, 32 ]: depthwise convolution with channel multiplier between 1 and 32 (inclusive).
 */
class AvgMax_Or_ChannelMultiplier extends Int {

  constructor() {
    super( -2, 32, [ "AVG", "MAX", "NONE" ] );
  }

}

/** The only one ValueDesc.AvgMax_Or_ChannelMultiplier instance. */
AvgMax_Or_ChannelMultiplier.Singleton = new AvgMax_Or_ChannelMultiplier;

/** Describe id, range, name of channelCount1_pointwise1Before.
 *
 * Convert number value into integer between [ -2, ( 10 * 1024 ) ] representing operation:
 *   - -3: TWO_INPUTS_CONCAT_POINTWISE21_INPUT1 (-3)
 *   - -2: ONE_INPUT_TWO_DEPTHWISE
 *   - -1: ONE_INPUT_ADD_TO_OUTPUT
 *   -  0: ONE_INPUT
 *   - [ 1, ( 10 * 1024 ) ]: TWO_INPUTS with the second input channel count between 1 and 10240 (inclusive). (without names defined.)
 */
class channelCount1_pointwise1Before extends Int {

  constructor() {
//!!! ...unfinished... (2021/10/12)
//    super( -3, ( 10 * 1024 ), [
    super( -5, ( 10 * 1024 ), [
//!!! ...unfinished... (2021/10/12)
      "ONE_INPUT_HALF_THROUGH",               // (-5) ShuffleNetV2's body/tail by MobileNet
      "ONE_INPUT_HALF_DEPTHWISE1",            // (-4) ShuffleNetV2's head by MobileNet

      "TWO_INPUTS_CONCAT_POINTWISE21_INPUT1", // (-3) ShuffleNetV2's body/tail
      "ONE_INPUT_TWO_DEPTHWISE",              // (-2) ShuffleNetV2's head
      "ONE_INPUT_ADD_TO_OUTPUT",              // (-1)
      "ONE_INPUT",                            // ( 0)

      // (2021/07/13 Remarked) Do not define these names because they will occupy too many memory.
      //
      // i.e. "TWO_INPUTS_1", "TWO_INPUTS_2", ..., "TWO_INPUTS_10240".
      //... [ ... new Array( 10 * 1024 ).keys() ].map( x => "TWO_INPUTS_" + ( x + 1 ) )
    ] );
  }

}

/** The only one ValueDesc.channelCount1_pointwise1Before instance. */
channelCount1_pointwise1Before.Singleton = new channelCount1_pointwise1Before;

/** Describe id, range, name of WhetherShuffleChannel.
 *
 * Convert number value into integer between [ 0, 2 ] representing operation:
 *   - 0: NONE (i.e. NotShuffleNet_NotMobileNet, or MobileNet)
 *   - 2: BY_CHANNEL_SHUFFLER (i.e. ShuffleNetV2)
 *   - 1: BY_POINTWISE22 (i.e. Slower ShuffleNetV2)
 */
class WhetherShuffleChannel extends Int {

  constructor() {
    super( 0, 2, [
      "NONE",                // (0)
      "BY_CHANNEL_SHUFFLER", // (1)
      "BY_POINTWISE22",      // (2)
    ] );
  }

}

/** The only one ValueDesc.WhetherShuffleChannel instance. */
WhetherShuffleChannel.Singleton = new WhetherShuffleChannel;
<commit_msg>Update ValueDesc.js<commit_after>export { Same, Bool, Int, ActivationFunction };
export { AvgMax_Or_ChannelMultiplier, channelCount1_pointwise1Before };
export { WhetherShuffleChannel };

import * as ValueRange from "./ValueRange.js";

/**
 * Describe some properties of a non-converting parameter.
 *
 * @member {ValueRange.Same} range
 *   The range of the parameter's all possible values. It is a ValueRange.Same object.
 *
 */
class Same {

  constructor() {
    this.range = ValueRange.Same.Singleton;
  }

  /** @return {string} Return the string value. */
  getStringOf( value ) {
    return value.toString();
  }
}

/** The only one ValueDesc.Same instance. */
Same.Singleton = new Same;

/**
 * Describe some properties of a boolean parameter.
 *
 * @member {ValueRange.Bool} range
 *   The boolean range of the parameter's all possible values. It is a ValueRange.Bool object.
 *
 */
class Bool {

  constructor() {
    this.range = ValueRange.Bool.Singleton;
  }

  /** @return {string} Return the string value. */
  getStringOf( value ) {
    return value.toString();
  }
}

/** The only one ValueDesc.Bool instance. */
Bool.Singleton = new Bool;

/**
 * Describe some properties of an integer parameter.
 *
 * @member {ValueRange.Int} range
 *   The integer range of the parameter's all possible values. It is an ValueRange.Int object with ( min = valueIntegerMin )
 * and ( max = valueIntegerMax ).
 *
 * @member {string[]} valueNames
 *   The string names of the parameter's all named values. It is an array of strings. They should be all legal identifers too (i.e. A-Z,
 * a-z, 0-9 (not at first character), and "_"). They will become the properties' names of this.Ids. Note that
 * ( valueNames.length <= range.kinds ). This means that only first valueNames.length values have names. So, it is possible
 * that all values do not have names (when valueNames[] is empty).
 *
 * @member {object[]} valueObjects
 *   The extra objects of the parameter values. It is an array of objects. They will become the properties' names of this.extraObjects.
 * Note that ( valueObjects.length <= range.kinds ). This means that only first valueObjects.length values have names. So, it is possible
 * that all values do not have extra objects (when valueObjects[] is empty).
 *
 * @member {Object} Ids
 *   An object contains the parameter's all named values. It is just like a name-to-integer Map (this.nameToIntegerMap), but
 * could be accessed by dot (.) operator (not by .get() method). This could be used as a constant enumeration. The
 * this.Ids.valueName will be valueInteger. Or, the this.Ids[ valueName ] will be valueInteger. That is:
 *   - this.Ids[ valueNames[ 0 ] ] = valueIntegers[ 0 ] = ( valueIntegerMin + 0 )
 *   - this.Ids[ valueNames[ 1 ] ] = valueIntegers[ 1 ] = ( valueIntegerMin + 1 )
 *   - ...
 *   - this.Ids[ valueNames[ ( valueNames.length - 1 ) ] ] = valueIntegers[ valueNames.length - 1 ] = ( valueIntegerMin + ( valueNames.length - 1 ) )
 *
 * @member {Map} nameToIntegerMap
 *   A map object contains the parameter's all named values. Using this.nameToIntegerMap.get( name ) could get the integer value of
 * the name.
 *
 * @member {Map} integerToNameMap
 *   A map object contains the parameter's all named values. Using this.integerToNameMap.get( integerValue ) could get the name of
 * the integer value.
 *
 * @member {Map} integerToObjectMap
 *   A map object contains the parameter's all object values. Using this.integerToObjectMap.get( integerValue ) could get the extra
 * object of the integer value.
 *
 */
class Int {

  /**
   *
   * @param {number} valueIntegerMin
   *   The first (i.e. minimum) integer of the parameter's all possible values.
   *
   * @param {number} valueIntegerMax
   *   The last (i.e. maximum) integer of the parameter's all possible values. It should equal ( valueIntegerMin + ( valueNames.length - 1 ) ).
   */
  constructor( valueIntegerMin, valueIntegerMax, valueNames = [], valueObjects = [] ) {

    this.range = new ValueRange.Int( valueIntegerMin, valueIntegerMax );
    this.valueNames = valueNames;
    this.valueObjects = valueObjects;

    this.Ids = {};
    this.integerToNameMap = new Map;
    this.nameToIntegerMap = new Map;
    for ( let i = 0; i < valueNames.length; ++i ) {
      let integerId = ( valueIntegerMin + i );
      let name = valueNames[ i ];
      this.Ids[ name ] = integerId;
      this.integerToNameMap.set( integerId, name );
      this.nameToIntegerMap.set( name, integerId );
    }

    this.integerToObjectMap = new Map;
    for ( let i = 0; i < valueObjects.length; ++i ) {
      let integerId = ( valueIntegerMin + i );
      let object = valueObjects[ i ];
      this.integerToObjectMap.set( integerId, object );
    }
  }

  /**
   * @return {string}
   *   Return the name of the integerValue. If no name, return the string of the integer value (e.g. "1", "2", ..., "64").
   */
  getStringOf( integerValue ) {
    let name = this.integerToNameMap.get( integerValue ); // Look up whether has name (e.g. "AVG", "MAX", "NONE").
    if ( null == name ) {
      name = integerValue.toString();
    }
    return name;
  }

}

/**
 * Describe activation function parameter's id, range, name.
 */
class ActivationFunction extends Int {

  constructor() {
    // Note:
    //   - NONE: Beware. It easily results in infinity value because it does not have upper bound.
    //   - RELU: Beware. It easily results in infinity value because it does not have upper bound.
    //   - SOFTPLUS: Avoid. Backend WASM does not support it.
    super( 0, 6,
      [ "NONE",  "RELU6",  "SIGMOID",  "TANH",  "COS",  "SIN",  "RELU" ], //  "SOFTPLUS" ],
      [   null, tf.relu6, tf.sigmoid, tf.tanh, tf.cos, tf.sin, tf.relu ]  // tf.softplus ]
    );
  }

}

/** The only one ValueDesc.ActivationFunction instance. */
ActivationFunction.Singleton = new ActivationFunction;

/** Describe depthwise operation's id, range, name.
 *
 * Convert number value into integer between [ -2, 32 ] representing depthwise operation:
 *   - -2: average pooling. (AVG)
 *   - -1: maximum pooling. (MAX)
 *   -  0: no depthwise operation. (NONE)
 *   - [ 1, 32 ]: depthwise convolution with channel multiplier between 1 and 32 (inclusive).
 */
class AvgMax_Or_ChannelMultiplier extends Int {

  constructor() {
    super( -2, 32, [ "AVG", "MAX", "NONE" ] );
  }

}

/** The only one ValueDesc.AvgMax_Or_ChannelMultiplier instance. */
AvgMax_Or_ChannelMultiplier.Singleton = new AvgMax_Or_ChannelMultiplier;

/** Describe id, range, name of channelCount1_pointwise1Before.
 *
 * Convert number value into integer between [ -5, ( 10 * 1024 ) ] representing operation:
 *   - -3: TWO_INPUTS_CONCAT_POINTWISE21_INPUT1
 *   - -2: ONE_INPUT_TWO_DEPTHWISE
 *   - -1: ONE_INPUT_ADD_TO_OUTPUT
 *   -  0: ONE_INPUT
 *   - [ 1, ( 10 * 1024 ) ]: TWO_INPUTS with the second input channel count between 1 and 10240 (inclusive). (without names defined.)
 */
class channelCount1_pointwise1Before extends Int {

  constructor() {
    super( -5, ( 10 * 1024 ), [
      "ONE_INPUT_HALF_THROUGH",               // (-5) ShuffleNetV2_ByMobileNetV1's body/tail
      "ONE_INPUT_HALF_DEPTHWISE1",            // (-4) ShuffleNetV2_ByMobileNetV1's head
      "TWO_INPUTS_CONCAT_POINTWISE21_INPUT1", // (-3) ShuffleNetV2's body/tail
      "ONE_INPUT_TWO_DEPTHWISE",              // (-2) ShuffleNetV2's head (or ShuffleNetV2_ByPointwise22's head)
      "ONE_INPUT_ADD_TO_OUTPUT",              // (-1) MobileNetV2
      "ONE_INPUT",                            // ( 0) MobileNetV1 (General Pointwise1-Depthwise1-Pointwise2)

      // "TWO_INPUTS_1", "TWO_INPUTS_2", ..., "TWO_INPUTS_10240".
      //
      // ShuffleNetV2_ByPointwise22's body/tail
      //
      // (2021/07/13 Remarked) Do not define these names because they will occupy too many memory.
      //
      //... [ ... new Array( 10 * 1024 ).keys() ].map( x => "TWO_INPUTS_" + ( x + 1 ) )
    ] );
  }

}

/** The only one ValueDesc.channelCount1_pointwise1Before instance. */
channelCount1_pointwise1Before.Singleton = new channelCount1_pointwise1Before;

/** Describe id, range, name of WhetherShuffleChannel.
 *
 * Convert number value into integer between [ 0, 3 ] representing operation:
 *   - 0: NONE (i.e. NotShuffleNet_NotMobileNet, or MobileNetV2)
 *   - 1: BY_POINTWISE22      (i.e. ShuffleNetV2_ByPointwise22)
 *   - 2: BY_CHANNEL_SHUFFLER (i.e. ShuffleNetV2)
     - 3: BY_MOBILE_NET_V1    (i.e. ShuffleNetV2_ByMobileNetV1)
 */
class WhetherShuffleChannel extends Int {

  constructor() {
    super( 0, 2, [
      "NONE",                // (0)
      "BY_CHANNEL_SHUFFLER", // (1)
      "BY_POINTWISE22",      // (2)
      "BY_MOBILE_NET_V1",    // (3)
    ] );
  }

}

/** The only one ValueDesc.WhetherShuffleChannel instance. */
WhetherShuffleChannel.Singleton = new WhetherShuffleChannel;
<|endoftext|>


<commit_before>export { Same, Bool, Int };

import * as ValueRange from "./ValueRange.js";

//!!! ...unfinished... (2021/03/14)
// Could define a class contains one parameter's key (symbol), range (and adjuster), ids (string?-number), idToNameMap (number-string), nameToIdMap (string-number)?
// But all parameters' keys should be browsable by iterator.
//
// ids is already a kinds of string-number. Perhaps, nameToIdMap should be derived from ids automatically.
//
// Where is Functions?

/**
 * Describe some properties of an integer parameter.
 *
 * @member {ParamRange.Int} range
 *   The integer range of the parameter's all possible values. It is an IntegerRange object with ( min = valueIntegerMin )
 * and ( max = valueIntegerMax ).
 *
 * @member {string[]} valueNames
 *   The string names of the parameter's all named values. It is an array of strings. They should be all legal identifers too (i.e. A-Z,
 * a-z, 0-9 (not at first character), and "_"). They will become the properties' names of this.valueNameInteger. Note that
 * ( valueNames.length <= range.kinds ). This means that only first valueNames.length values have names. So, it is possible
 * that all values are no names (when valueNames[] is empty).
 *
 * @member {number[]} valueIntegers
 *   The integer values of the parameter's all named values. ( valueIntegers.length == valueNames.length == valueNameInteger.lenth ).
 *
 * @member {Object} Ids
 *   An object contains the parameter's all named values. It is just like a Map, but could be accessed by dot (.) operator
 * (not by .get() method). The this.Ids.valueName will be valueInteger. Or, the this.Ids[ valueName ]
 * will be valueInteger. That is:
 *   - this.Ids[ valueNames[ 0 ] ] = valueIntegers[ 0 ] = ( valueIntegerMin + 0 )
 *   - this.Ids[ valueNames[ 1 ] ] = valueIntegers[ 1 ] = ( valueIntegerMin + 1 )
 *   - ...
 *   - this.Ids[ valueNames[ ( valueNames.length - 1 ) ] ] = valueIntegers[ valueNames.length - 1 ] = ( valueIntegerMin + ( valueNames.length - 1 ) )
 *
 */
class Int {

  /**
   *
   * @param {number} valueIntegerMin
   *   The first (i.e. minimum) integer of the parameter's all possible values.
   *
   * @param {number} valueIntegerMax
   *   The last (i.e. maximum) integer of the parameter's all possible values. It should equal ( valueIntegerMin + ( valueNames.length - 1 ) ).
   */
  constructor( valueIntegerMin, valueIntegerMax, valueNames ) {

    this.range = new ValueRange.Int( valueIntegerMin, valueIntegerMax );

    if ( !valueNames )
      valueNames = []; // ( valueNames == null ), means all values are no names.

    this.valueNames = valueNames;

    this.valueIntegers = new Array( valueNames.length ); // ( valueNames.length <= range.kinds )
    this.Ids = {};
    for ( let i = 0; i < valueNames.length; ++i ) {
      this.Ids[ valueNames[ i ] ] = this.valueIntegers[ i ] = ( valueIntegerMin + i );
    }

  }
}
<commit_msg>Update ValueDesc.js<commit_after>export { Int };

import * as ValueRange from "./ValueRange.js";

//!!! ...unfinished... (2021/03/14)
// Could define a class contains one parameter's key (symbol), range (and adjuster), ids (string?-number), idToNameMap (number-string), nameToIdMap (string-number)?
// But all parameters' keys should be browsable by iterator.
//
// ids is already a kinds of string-number. Perhaps, nameToIdMap should be derived from ids automatically.
//
// Where is Functions?

/**
 * Describe some properties of an integer parameter.
 *
 * @member {ParamRange.Int} range
 *   The integer range of the parameter's all possible values. It is an IntegerRange object with ( min = valueIntegerMin )
 * and ( max = valueIntegerMax ).
 *
 * @member {string[]} valueNames
 *   The string names of the parameter's all named values. It is an array of strings. They should be all legal identifers too (i.e. A-Z,
 * a-z, 0-9 (not at first character), and "_"). They will become the properties' names of this.valueNameInteger. Note that
 * ( valueNames.length <= range.kinds ). This means that only first valueNames.length values have names. So, it is possible
 * that all values are no names (when valueNames[] is empty).
 *
 * @member {number[]} valueIntegers
 *   The integer values of the parameter's all named values. ( valueIntegers.length == valueNames.length == valueNameInteger.lenth ).
 *
 * @member {Object} Ids
 *   An object contains the parameter's all named values. It is just like a Map, but could be accessed by dot (.) operator
 * (not by .get() method). The this.Ids.valueName will be valueInteger. Or, the this.Ids[ valueName ]
 * will be valueInteger. That is:
 *   - this.Ids[ valueNames[ 0 ] ] = valueIntegers[ 0 ] = ( valueIntegerMin + 0 )
 *   - this.Ids[ valueNames[ 1 ] ] = valueIntegers[ 1 ] = ( valueIntegerMin + 1 )
 *   - ...
 *   - this.Ids[ valueNames[ ( valueNames.length - 1 ) ] ] = valueIntegers[ valueNames.length - 1 ] = ( valueIntegerMin + ( valueNames.length - 1 ) )
 *
 */
class Int {

  /**
   *
   * @param {number} valueIntegerMin
   *   The first (i.e. minimum) integer of the parameter's all possible values.
   *
   * @param {number} valueIntegerMax
   *   The last (i.e. maximum) integer of the parameter's all possible values. It should equal ( valueIntegerMin + ( valueNames.length - 1 ) ).
   */
  constructor( valueIntegerMin, valueIntegerMax, valueNames ) {

    this.range = new ValueRange.Int( valueIntegerMin, valueIntegerMax );

    if ( !valueNames )
      valueNames = []; // ( valueNames == null ), means all values are no names.

    this.valueNames = valueNames;

    this.valueIntegers = new Array( valueNames.length ); // ( valueNames.length <= range.kinds )
    this.Ids = {};
    for ( let i = 0; i < valueNames.length; ++i ) {
      this.Ids[ valueNames[ i ] ] = this.valueIntegers[ i ] = ( valueIntegerMin + i );
    }

  }
}
<|endoftext|>


<commit_before>import * as ScriptLoader from "../util/ScriptLoader.js";
import * as ValueMax from "../util/ValueMax.js";
import * as PartTime from "../util/PartTime.js";
import * as Pool from "../util/Pool.js";
import * as Base64ToUint8Array_tester from "./Base64ToUint8Array_tester.js";
import * as GSheets_tester from "./GSheets_tester.js";
import * as AsyncWorker_tester from "./AsyncWorker_tester.js";
import * as NeuralWorker_tester from "./NeuralWorker_tester.js";

window.addEventListener( "load", event => {
  ScriptLoader
    .createPromise(
      "https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@3.19.0/dist/tf.min.js" )
    .then( test );
});

function test() {
  console.log("util testing...");
  let delayMilliseconds = 100;

  let pool_all_issuedCount_before = Pool.All.issuedCount;

  // Aggregate all progress about util_tester.
  let progress = ValueMax.Percentage.Aggregate.Pool.get_or_create_by();

  let progress_Base64ToUint8Array_tester = progress.child_add(
    ValueMax.Percentage.Aggregate.Pool.get_or_create_by() );

  let progress_GSheets_tester = progress.child_add(
    ValueMax.Percentage.Aggregate.Pool.get_or_create_by() );

  let progress_AsyncWorker_tester = progress.child_add(
    ValueMax.Percentage.Aggregate.Pool.get_or_create_by() );

  let progress_NeuralWorker_tester_cpu = progress.child_add(
    ValueMax.Percentage.Aggregate.Pool.get_or_create_by() );

  let progress_NeuralWorker_tester_webgl = progress.child_add(
    ValueMax.Percentage.Aggregate.Pool.get_or_create_by() );

  let progressReceiver
    = new ValueMax.Receiver.HTMLProgress.createByTitle_or_getDummy( "TestProgressBar" );

  async function* testerAll() {
    throw Error( "Hi" );
    yield* NeuralWorker_tester.tester( progress_NeuralWorker_tester_cpu, "cpu" );
    yield* NeuralWorker_tester.tester( progress_NeuralWorker_tester_webgl, "webgl" );
    yield* AsyncWorker_tester.tester( progress_AsyncWorker_tester );
    yield* Base64ToUint8Array_tester.tester( progress_Base64ToUint8Array_tester );
    yield* GSheets_tester.tester( progress_GSheets_tester );
  }

  let tester = testerAll();

  let testPromise = PartTime.forOf(
    tester,
    ( progressRoot ) => {
      progressReceiver.setValueMax( // Report progress to UI.
        progressRoot.valuePercentage, progressRoot.maxPercentage );
    },
    () => { // Release resource.

      if ( 100 != progress.valuePercentage )
        throw Error( `util_tester.test(): `
          + `Progress (${progress.valuePercentage}) should be 100 `
          + `after testing done.`);

      progress.disposeResources_and_recycleToPool();
      progress = null;

      Pool.Asserter.assert_Pool_issuedCount( "util_tester.test()",
        pool_all_issuedCount_before );
    },
    delayMilliseconds
  ).then(r => {
  });

//   progressReceiver.informDone(r); // Inform UI progress done.

  testPromise.then( value => {
    console.log( "util testing... Done." );
  }).catch( reason => {
    debugger;
  });

//!!! ...unfinished... test case by multipler web worker?
}
<commit_msg>catch( reason<commit_after>import * as ScriptLoader from "../util/ScriptLoader.js";
import * as ValueMax from "../util/ValueMax.js";
import * as PartTime from "../util/PartTime.js";
import * as Pool from "../util/Pool.js";
import * as Base64ToUint8Array_tester from "./Base64ToUint8Array_tester.js";
import * as GSheets_tester from "./GSheets_tester.js";
import * as AsyncWorker_tester from "./AsyncWorker_tester.js";
import * as NeuralWorker_tester from "./NeuralWorker_tester.js";

window.addEventListener( "load", event => {
  ScriptLoader
    .createPromise(
      "https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@3.19.0/dist/tf.min.js" )
    .then( test );
});

function test() {
  console.log("util testing...");
  let delayMilliseconds = 100;

  let pool_all_issuedCount_before = Pool.All.issuedCount;

  // Aggregate all progress about util_tester.
  let progress = ValueMax.Percentage.Aggregate.Pool.get_or_create_by();

  let progress_Base64ToUint8Array_tester = progress.child_add(
    ValueMax.Percentage.Aggregate.Pool.get_or_create_by() );

  let progress_GSheets_tester = progress.child_add(
    ValueMax.Percentage.Aggregate.Pool.get_or_create_by() );

  let progress_AsyncWorker_tester = progress.child_add(
    ValueMax.Percentage.Aggregate.Pool.get_or_create_by() );

  let progress_NeuralWorker_tester_cpu = progress.child_add(
    ValueMax.Percentage.Aggregate.Pool.get_or_create_by() );

  let progress_NeuralWorker_tester_webgl = progress.child_add(
    ValueMax.Percentage.Aggregate.Pool.get_or_create_by() );

  let progressReceiver
    = new ValueMax.Receiver.HTMLProgress.createByTitle_or_getDummy( "TestProgressBar" );

  async function* testerAll() {
    throw Error( "Hi" );
    yield* NeuralWorker_tester.tester( progress_NeuralWorker_tester_cpu, "cpu" );
    yield* NeuralWorker_tester.tester( progress_NeuralWorker_tester_webgl, "webgl" );
    yield* AsyncWorker_tester.tester( progress_AsyncWorker_tester );
    yield* Base64ToUint8Array_tester.tester( progress_Base64ToUint8Array_tester );
    yield* GSheets_tester.tester( progress_GSheets_tester );
  }

  let tester = testerAll();

  let testPromise = PartTime.forOf(
    tester,
    ( progressRoot ) => {
      progressReceiver.setValueMax( // Report progress to UI.
        progressRoot.valuePercentage, progressRoot.maxPercentage );
    },
    () => { // Release resource.

      if ( 100 != progress.valuePercentage )
        throw Error( `util_tester.test(): `
          + `Progress (${progress.valuePercentage}) should be 100 `
          + `after testing done.`);

      progress.disposeResources_and_recycleToPool();
      progress = null;

      Pool.Asserter.assert_Pool_issuedCount( "util_tester.test()",
        pool_all_issuedCount_before );
    },
    delayMilliseconds
  );

//   progressReceiver.informDone(r); // Inform UI progress done.

  testPromise.then( value => {
    console.log( "util testing... Done." );
  }).catch( reason => {
    debugger;
  });

//!!! ...unfinished... test case by multipler web worker?
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) WSO2 Inc. (http://wso2.com) All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Description: Pagination
 *              Function 'scroll' bind to the UI event scroll.
 *              Requests next set of assets by calling API endpoint /publisher/apis/assets?type=<type>&sort=<sort-by-attribute>&start=<number-of-already-rendered-assets>&count=<number-of-assets-per-page>
 *              Renders retrieved set of assets by calling caramel client
 *              if no-no-more assets to be retrieved, unbind 'scroll'
 */
var currentPage, infiniteScroll;
currentPage = 1;
infiniteScroll = true;
/**
 * To render the next set of assets by appending to the available container
 * @param {string} partial  : to which partial should be added
 * @param {JSON}   data     : data for the partial
 * @param {String} container : container to be appended
 * @param {String} cb       : callback function if any
 */
function renderView(partial, data, container, cb) {
    var obj = {};
    obj[partial] = '/themes/default/partials/' + partial + '.hbs';
    delete data.content;
    caramel.partials(obj, function() {
        var template = Handlebars.partials[partial](data);
        $(container).append(template);
        if (cb) {
            cb();
        }
    });
}
/**
 * To convert asset.attributes.overview_createdtime to UTC string
 * @param {JSON} assets  The asset object list
 */
function convertTimeToUTC(assets) {
    for (var index in assets) {
        var asset = assets[index];
        if (asset.attributes.overview_createdtime) {
            var value = asset.attributes.overview_createdtime;
            var date = new Date();
            date.setTime(value);
            asset.attributes.overview_createdtime = date.toUTCString();
        }
    }
    return assets;
}
/**
 * Return next set of assets for the next page by calling assets API endpoint
 * @param {String} param  : string of parameters for the api call
 */
function getNextPage(param) {
    var assetType = store.publisher.type; //load type from store global object
    var url = '/publisher/apis/assets?type=' + assetType + param; // build url for the endpoint call
    // call endpoint
    $.ajax({
        url: url,
        type: 'GET',
        success: function(response) { //on success
            var assets = convertTimeToUTC(response.data);
            if (assets) {
                renderView('list_assets_table_body', assets, '#list_assets_table_body', null);
                if (assets.length < store.publisher.itemsPerPage) { // if no more assets for the next page
                    infiniteScroll = false;
                    $('.loading-inf-scroll').hide();
                } else {
                    infiniteScroll = true;
                    if ($(window).height() >= $(document).height()) {
                        scroll();
                    }
                }
            } else { //if no assets retrieved for this page
                infiniteScroll = false;
            }
        },
        error: function(response) { //on error
            $('.loading-inf-scroll').hide();
            $(window).unbind('scroll', scroll);
            infiniteScroll = false;
        }
    });
}
/**
 * Build sorting parameters based on page path
 * @param {string} path  : string
 */
var setSortingParams = function(path) {
    var obj = path.split('?');
    var sorting = '';
    if (obj[1]) {
        var temp = obj[1].split('&');
        var sortby = temp[0].split('=')[1];
        var sort = temp[1].split('=')[1];
    } else {
        sort = 'DESC';
        sortby = 'overview_createdtime';
    }
    if (sort == 'DESC') {
        sorting = '&&sort=-' + sortby;
    } else {
        sorting = '&&sort=+' + sortby;
    }
    return sorting;
};
/**
 * scroll method bind to be scroll window function
 *
 */
var scroll = function() {
    var startInitItems = store.publisher.itemsPerPage; // items-per-page by global store object
    if (infiniteScroll && startInitItems > 1) { //if scroll enabled
        if ($(window).scrollTop() + $(window).height() >= $(document).height()) {
            var start = startInitItems * (currentPage++);
            var path = window.location.href; //current page path
            var param = '&&start=' + start + '&&count=' + startInitItems + setSortingParams(path);
            getNextPage(param); // get next set of assets
            $('.loading-inf-scroll').hide();
            $(window).unbind('scroll', scroll);
            infiniteScroll = false;
            setTimeout(function() {
                if (infiniteScroll) {
                    $(window).bind('scroll', scroll);
                    $('.loading-inf-scroll').show();
                }
            }, 500);
        }
    } else { // if infinite scroll is not enabled
        $('.loading-inf-scroll').hide();
    }
};
var propCount = function(obj) {
    var count = 0;
    for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
            count++;
        }
    }
    return count;
};
var createQuery = function(options) {
    options = options || {};
    var searchUrl = caramel.url('/asts/' + store.publisher.type + '/list');
    var q = {};
    var name = $('#searchQueryTextBox').val();
    var category = options.category || undefined;
    var searchQueryString = '?';
    if (name) {
        q.name = name;
    }
    if (category) {
        q.category = category;
    }
    if (propCount(q) >= 1) {
        searchQueryString += 'q=';
        searchQueryString += JSON.stringify(q);
        searchQueryString = searchQueryString.replace('{', '').replace('}', '');
    }
    return searchUrl + searchQueryString;
};
var initSearch = function() {
    //Support for searching when pressing enter
    $('#assetSearchForm').submit(function(e) {
        e.preventDefault();
        window.location = createQuery();
    });
    //Support for searching by clicking on the search button
    $('#searchButton').click(function(e) {
        e.preventDefault();
        window.location = createQuery();
    });
};
var initCategorySelection = function() {
    $('div.wr-filter-category ul.dropdown-menu li a').click(function(e) {
        e.preventDefault();
        var selectedCategory = $(this).text();
        window.location = createQuery({
            category: selectedCategory
        });
    });
};
// bind to window function
$(window).bind('scroll', scroll);
$(window).load(function() {
    //scroll();
    initSearch();
    initCategorySelection();
});<commit_msg>Fixed publisher search not working due to altered input field name<commit_after>/*
 * Copyright (c) WSO2 Inc. (http://wso2.com) All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Description: Pagination
 *              Function 'scroll' bind to the UI event scroll.
 *              Requests next set of assets by calling API endpoint /publisher/apis/assets?type=<type>&sort=<sort-by-attribute>&start=<number-of-already-rendered-assets>&count=<number-of-assets-per-page>
 *              Renders retrieved set of assets by calling caramel client
 *              if no-no-more assets to be retrieved, unbind 'scroll'
 */
var currentPage, infiniteScroll;
currentPage = 1;
infiniteScroll = true;
/**
 * To render the next set of assets by appending to the available container
 * @param {string} partial  : to which partial should be added
 * @param {JSON}   data     : data for the partial
 * @param {String} container : container to be appended
 * @param {String} cb       : callback function if any
 */
function renderView(partial, data, container, cb) {
    var obj = {};
    obj[partial] = '/themes/default/partials/' + partial + '.hbs';
    delete data.content;
    caramel.partials(obj, function() {
        var template = Handlebars.partials[partial](data);
        $(container).append(template);
        if (cb) {
            cb();
        }
    });
}
/**
 * To convert asset.attributes.overview_createdtime to UTC string
 * @param {JSON} assets  The asset object list
 */
function convertTimeToUTC(assets) {
    for (var index in assets) {
        var asset = assets[index];
        if (asset.attributes.overview_createdtime) {
            var value = asset.attributes.overview_createdtime;
            var date = new Date();
            date.setTime(value);
            asset.attributes.overview_createdtime = date.toUTCString();
        }
    }
    return assets;
}
/**
 * Return next set of assets for the next page by calling assets API endpoint
 * @param {String} param  : string of parameters for the api call
 */
function getNextPage(param) {
    var assetType = store.publisher.type; //load type from store global object
    var url = '/publisher/apis/assets?type=' + assetType + param; // build url for the endpoint call
    // call endpoint
    $.ajax({
        url: url,
        type: 'GET',
        success: function(response) { //on success
            var assets = convertTimeToUTC(response.data);
            if (assets) {
                renderView('list_assets_table_body', assets, '#list_assets_table_body', null);
                if (assets.length < store.publisher.itemsPerPage) { // if no more assets for the next page
                    infiniteScroll = false;
                    $('.loading-inf-scroll').hide();
                } else {
                    infiniteScroll = true;
                    if ($(window).height() >= $(document).height()) {
                        scroll();
                    }
                }
            } else { //if no assets retrieved for this page
                infiniteScroll = false;
            }
        },
        error: function(response) { //on error
            $('.loading-inf-scroll').hide();
            $(window).unbind('scroll', scroll);
            infiniteScroll = false;
        }
    });
}
/**
 * Build sorting parameters based on page path
 * @param {string} path  : string
 */
var setSortingParams = function(path) {
    var obj = path.split('?');
    var sorting = '';
    if (obj[1]) {
        var temp = obj[1].split('&');
        var sortby = temp[0].split('=')[1];
        var sort = temp[1].split('=')[1];
    } else {
        sort = 'DESC';
        sortby = 'overview_createdtime';
    }
    if (sort == 'DESC') {
        sorting = '&&sort=-' + sortby;
    } else {
        sorting = '&&sort=+' + sortby;
    }
    return sorting;
};
/**
 * scroll method bind to be scroll window function
 *
 */
var scroll = function() {
    var startInitItems = store.publisher.itemsPerPage; // items-per-page by global store object
    if (infiniteScroll && startInitItems > 1) { //if scroll enabled
        if ($(window).scrollTop() + $(window).height() >= $(document).height()) {
            var start = startInitItems * (currentPage++);
            var path = window.location.href; //current page path
            var param = '&&start=' + start + '&&count=' + startInitItems + setSortingParams(path);
            getNextPage(param); // get next set of assets
            $('.loading-inf-scroll').hide();
            $(window).unbind('scroll', scroll);
            infiniteScroll = false;
            setTimeout(function() {
                if (infiniteScroll) {
                    $(window).bind('scroll', scroll);
                    $('.loading-inf-scroll').show();
                }
            }, 500);
        }
    } else { // if infinite scroll is not enabled
        $('.loading-inf-scroll').hide();
    }
};
var propCount = function(obj) {
    var count = 0;
    for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
            count++;
        }
    }
    return count;
};
var createQuery = function(options) {
    options = options || {};
    var searchUrl = caramel.url('/asts/' + store.publisher.type + '/list');
    var q = {};
    var name = $('#inp_searchAsset').val();
    var category = options.category || undefined;
    var searchQueryString = '?';
    if (name) {
        q.name = name;
    }
    if (category) {
        q.category = category;
    }
    if (propCount(q) >= 1) {
        searchQueryString += 'q=';
        searchQueryString += JSON.stringify(q);
        searchQueryString = searchQueryString.replace('{', '').replace('}', '');
    }
    return searchUrl + searchQueryString;
};
var initSearch = function() {
    //Support for searching when pressing enter
    $('#assetSearchForm').submit(function(e) {
        e.preventDefault();
        window.location = createQuery();
    });
    //Support for searching by clicking on the search button
    $('#searchButton').click(function(e) {
        e.preventDefault();
        window.location = createQuery();
    });
};
var initCategorySelection = function() {
    $('div.wr-filter-category ul.dropdown-menu li a').click(function(e) {
        e.preventDefault();
        var selectedCategory = $(this).text();
        window.location = createQuery({
            category: selectedCategory
        });
    });
};
// bind to window function
$(window).bind('scroll', scroll);
$(window).load(function() {
    //scroll();
    initSearch();
    initCategorySelection();
});<|endoftext|>


<commit_before>/**
 * @fileOverview Initiates Qunit test running.
 */
var args = arguments;
(function(){
    load('lib/setup.js');
    console.log("Starting QUnit tests...");
    // @@@ Passing args to the URL seems broken.  Delete the
    // following when it works the way it should.  See pre.js.
    Envjs.deleteFile(Envjs.uri(Envjs.tmpdir+"qunitargs"));
    Envjs.writeToFile("Modules.original = '" + args.join('&') + "';", Envjs.uri(Envjs.tmpdir+"qunitargs"));
    window.location = "tests/index.html";
    // Use this instead when it works.
    // + "?" + args.join('&');
})();
<commit_msg>fixing inconsistent / ending for tmpdir<commit_after>/**
 * @fileOverview Initiates Qunit test running.
 */
var args = arguments;
(function(){
    load('lib/setup.js');
    console.log("Starting QUnit tests...");
    // @@@ Passing args to the URL seems broken.  Delete the
    // following when it works the way it should.  See pre.js.
    if (Envjs.tmpdir[Envjs.tmpdir.length - 1] !== '/') {
        Envjs.tmpdir += '/';
    }
    Envjs.deleteFile(Envjs.uri(Envjs.tmpdir+"qunitargs"));
    Envjs.writeToFile("Modules.original = '" + args.join('&') + "';", Envjs.uri(Envjs.tmpdir+"qunitargs"));
    window.location = "tests/index.html";
    // Use this instead when it works.
    // + "?" + args.join('&');
})();
<|endoftext|>


<commit_before>import { alias, or, readOnly, notEmpty, and } from '@ember/object/computed';
import Component from '@ember/component';
import { computed } from '@ember/object';
import { isEqual } from '@ember/utils';
import layout from '../../templates/components/ember-tabella/header-column';
import columnStyle from '../../mixins/column-style';

export default Component.extend(columnStyle, {
  layout: layout,
  scrollLeft: 0,
  scrollTop: 0,

  classNames: ['ember-tabella__header-column'],
  classNameBindings: [
    'isSortable:ember-tabella__header-column--sortable',
    'isSorted:ember-tabella__header-column--sorted',
    'sortedClassName',
    'isResizable:ember-tabella__header-column--resizable',
    'column.isFixed:ember-tabella__header-column--fixed'
  ],
  attributeBindings: ['style'],

  column: null,
  width: alias('column.width'),
  defaultMinWidth: 50,
  minWidth: or('column.minWidth', 'defaultMinWidth'),
  isResizable: readOnly('column.isResizable'),
  sortedColumn: null,
  isSortable: notEmpty('column.sortProperties'),
  isSortReversed: false,
  _isSortReversed: and('isSortReversed', 'isSorted'),

  onColumnSort() {},

  isSorted: computed('sortedColumn', 'column', function() {
    const scolumn = this.get('sortedColumn');
    const column  = this.get('column');

    return isEqual(scolumn, column);
  }),

  sortDirection: computed('isSorted', '_isSortReversed', function() {
    if (!this.get('isSorted')) {
      return null;
    }
    if (this.get('_isSortReversed')) {
      return 'desc';
    }
    return 'asc';
  }),

  sortedClassName: computed('sortDirection', function() {
    const direction = this.get('sortDirection');

    if (!direction) {
      return;
    }

    return `ember-tabella__header-column--sorted-${direction}`;
  }),

  actions: {
    resize(offsetX) {
      const mWidth = this.get('minWidth');
      const width  = this.get('width');

      let nWidth = width + (offsetX || 0);

      if (nWidth <= mWidth) {
        nWidth = mWidth;
      }

      this.set('width', nWidth);
    },

    sort() {
      if (!this.get('isSortable')) {
        return;
      }

      const column = this.get('column');
      const asc    = this.get('isSortReversed');

      this.get('onColumnSort')(column, !asc);
    }
  }
});
<commit_msg>missed a get<commit_after>import { alias, or, readOnly, notEmpty, and } from '@ember/object/computed';
import Component from '@ember/component';
import { get, computed } from '@ember/object';
import { isEqual } from '@ember/utils';
import layout from '../../templates/components/ember-tabella/header-column';
import columnStyle from '../../mixins/column-style';

export default Component.extend(columnStyle, {
  layout: layout,
  scrollLeft: 0,
  scrollTop: 0,

  classNames: ['ember-tabella__header-column'],
  classNameBindings: [
    'isSortable:ember-tabella__header-column--sortable',
    'isSorted:ember-tabella__header-column--sorted',
    'sortedClassName',
    'isResizable:ember-tabella__header-column--resizable',
    'column.isFixed:ember-tabella__header-column--fixed'
  ],
  attributeBindings: ['style'],

  column: null,
  width: alias('column.width'),
  defaultMinWidth: 50,
  minWidth: or('column.minWidth', 'defaultMinWidth'),
  isResizable: readOnly('column.isResizable'),
  sortedColumn: null,
  isSortable: notEmpty('column.sortProperties'),
  isSortReversed: false,
  _isSortReversed: and('isSortReversed', 'isSorted'),

  onColumnSort() {},

  isSorted: computed('sortedColumn', 'column', function() {
    const scolumn = get(this, 'sortedColumn');
    const column  = get(this, 'column');

    return isEqual(scolumn, column);
  }),

  sortDirection: computed('isSorted', '_isSortReversed', function() {
    if (!get(this, 'isSorted')) {
      return null;
    }
    if (get(this, '_isSortReversed')) {
      return 'desc';
    }
    return 'asc';
  }),

  sortedClassName: computed('sortDirection', function() {
    const direction = get(this, 'sortDirection');

    if (!direction) {
      return;
    }

    return `ember-tabella__header-column--sorted-${direction}`;
  }),

  actions: {
    resize(offsetX) {
      const mWidth = get(this, 'minWidth');
      const width  = get(this, 'width');

      let nWidth = width + (offsetX || 0);

      if (nWidth <= mWidth) {
        nWidth = mWidth;
      }

      this.set('width', nWidth);
    },

    sort() {
      if (!get(this, 'isSortable')) {
        return;
      }

      const column = get(this, 'column');
      const asc    = get(this, 'isSortReversed');

      get(this, 'onColumnSort')(column, !asc);
    }
  }
});
<|endoftext|>