<commit_before>function PortsRow(parent) {
    if (parent === null) {
        throw "Error: Parent of ports row object can not be null";
    }

    this.CIRCLE_RADIUS = 30;
    this.CIRCLE_DIAMETER = 2 * this.CIRCLE_RADIUS;
    this.CIRCLE_SPACING = this.CIRCLE_DIAMETER + 0;

    this.COLOR_NEW_PORT = "green";
    this.COLOR_CLOSED_PORT = "red";

    this._parent = parent;

    this._svg = parent.append("svg")
        .attr('height', this.CIRCLE_DIAMETER + 'px')
        .attr('width', '100%');

    this._ports = [];

    this._arrangePorts = function() {
        for (var i = 0; i<this._ports.length;i++) {
            var port_information = this._ports[i];

            var new_x = (i + 1) * this.CIRCLE_SPACING;
            var new_y = this.CIRCLE_RADIUS;

            port_information.g
              .transition()
              .duration(1000)
              .attr("transform", "translate(" + new_x + ", " + new_y + ")");
        }
    };

    this._createVisualGroup = function(port) {
        var new_x = (this._ports.length + 1) * this.CIRCLE_SPACING;
        var new_y = this.CIRCLE_RADIUS;

        var g = this._svg.append("g")
            .attr("transform", "translate(" + new_x + ", " + new_y + ")");

        g.append("circle")
          .attr("r", this.CIRCLE_RADIUS)
          .style("fill", this.COLOR_NEW_PORT);

        g.append("text")
            .attr('y', 5)
            .attr('fill', 'white')
            .style('font-size', '15px')
            .style('font-weight', 'bold')
            .attr("text-anchor", "middle")
            .text(port);

        return g;
    };

    this._portSorter = function(lhs, rhs) {
        return lhs.port - rhs.port;
    };

    this.addPort = function(port) {
        var port_information = {
            'port': port,
            'g': this._createVisualGroup(port)
        };

        this._ports.push(port_information);
        this._ports.sort(this._portSorter);

        this._arrangePorts();
    };

    this._findPort = function(port) {
        for (var i=0; i<this._ports.length; i++) {
            var port_information = this._ports[i];
            if (port_information.port == port) {
                return port_information;
            }
        }

        return null;
    };

    this._changeColor = function(g) {
        g.select('circle')
            .transition(1000)
            .style("fill", "red");
    };

    this.removePort = function(port) {
        var port_information = this._findPort(port);

        if (port_information !== null) {
            var index = this._ports.indexOf(port_information);
            if (index > -1) {
                this._ports.splice(index, 1);
            }

            var self = this;

            port_information.g.select('circle')
                .transition().duration(1000)
                .style("fill", this.COLOR_CLOSED_PORT)
                .each("end", function() {
                    port_information.g.select("text").remove();
                })
                .transition().duration(1000)
                .attr("r", function(d) { return 0; })
                .each("end", function() {
                    port_information.g.remove();
                    self._arrangePorts();
                });
        }
    };

    this.hasPorts = function() {
        return this._ports.length !== 0;
    };

    this.getParent = function() {
        return this._parent;
    }
}
<commit_msg>Improved new ports animation<commit_after>function PortsRow(parent) {
    if (parent === null) {
        throw "Error: Parent of ports row object can not be null";
    }

    this.CIRCLE_RADIUS = 30;
    this.CIRCLE_DIAMETER = 2 * this.CIRCLE_RADIUS;
    this.CIRCLE_SPACING = this.CIRCLE_DIAMETER + 0;

    this.COLOR_NEW_PORT = "green";
    this.COLOR_CLOSED_PORT = "red";

    this._parent = parent;

    this._svg = parent.append("svg")
        .attr('height', this.CIRCLE_DIAMETER + 'px')
        .attr('width', '100%');

    this._ports = [];

    this._arrangePorts = function() {
        for (var i = 0; i<this._ports.length;i++) {
            var port_information = this._ports[i];

            var new_x = (i + 1) * this.CIRCLE_SPACING;
            var new_y = this.CIRCLE_RADIUS;

            port_information.g
              .transition()
              .duration(1000)
              .attr("transform", "translate(" + new_x + ", " + new_y + ")");
        }
    };

    this._createVisualGroup = function(port) {
        var new_x = (this._ports.length + 2) * this.CIRCLE_SPACING;
        var new_y = this.CIRCLE_RADIUS;

        var g = this._svg.append("g")
            .attr("transform", "translate(" + new_x + ", " + new_y + ")");

        g.append("circle")
          .attr("r", this.CIRCLE_RADIUS)
          .style("fill", this.COLOR_NEW_PORT);

        g.append("text")
            .attr('y', 5)
            .attr('fill', 'white')
            .style('font-size', '15px')
            .style('font-weight', 'bold')
            .attr("text-anchor", "middle")
            .text(port);

        return g;
    };

    this._portSorter = function(lhs, rhs) {
        return lhs.port - rhs.port;
    };

    this.addPort = function(port) {
        var port_information = {
            'port': port,
            'g': this._createVisualGroup(port)
        };

        this._ports.push(port_information);
        this._ports.sort(this._portSorter);

        this._arrangePorts();
    };

    this._findPort = function(port) {
        for (var i=0; i<this._ports.length; i++) {
            var port_information = this._ports[i];
            if (port_information.port == port) {
                return port_information;
            }
        }

        return null;
    };

    this._changeColor = function(g) {
        g.select('circle')
            .transition(1000)
            .style("fill", "red");
    };

    this.removePort = function(port) {
        var port_information = this._findPort(port);

        if (port_information !== null) {
            var index = this._ports.indexOf(port_information);
            if (index > -1) {
                this._ports.splice(index, 1);
            }

            var self = this;

            port_information.g.select('circle')
                .transition().duration(1000)
                .style("fill", this.COLOR_CLOSED_PORT)
                .each("end", function() {
                    port_information.g.select("text").remove();
                })
                .transition().duration(1000)
                .attr("r", function(d) { return 0; })
                .each("end", function() {
                    port_information.g.remove();
                    self._arrangePorts();
                });
        }
    };

    this.hasPorts = function() {
        return this._ports.length !== 0;
    };

    this.getParent = function() {
        return this._parent;
    }
}
<|endoftext|>


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

'use strict';

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var setReadOnlyAccessor = require( '@stdlib/utils/define-read-only-accessor' );
var setReadWriteAccessor = require( '@stdlib/utils/define-read-write-accessor' );
var isObject = require( '@stdlib/assert/is-plain-object' );
var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive;
var isFunction = require( '@stdlib/assert/is-function' );
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var constantFunction = require( '@stdlib/utils/constant-function' );
var noop = require( '@stdlib/utils/noop' );
var randn = require( '@stdlib/random/base/improved-ziggurat' ).factory;
var randu = require( '@stdlib/random/base/mt19937' ).factory;
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var gcopy = require( '@stdlib/blas/base/gcopy' );
var Uint32Array = require( '@stdlib/array/uint32' );
var isUint32Array = require( '@stdlib/assert/is-uint32array' );
var copy = require( '@stdlib/utils/copy' );
var typedarray2json = require( '@stdlib/array/to-json' );
var validate = require( './validate.js' );
var beta0 = require( './beta.js' );

// MAIN //

/**
* Returns a pseudorandom number generator for generating beta distributed random numbers.
*
* @param {PositiveNumber} [alpha] - first shape parameter
* @param {PositiveNumber} [beta] - second shape parameter
* @param {Options} [options] - function options
* @param {Function} [options.prng] - pseudorandom number generator which generates uniformly distributed pseudorandom numbers
* @param {(uinteger32|Collection<uinteger32>)} [options.seed] - pseudorandom number generator seed
* @param {Uint32Array} [options.state] - pseudorandom number generator state
* @param {boolean} [options.copy=true] - boolean indicating whether to copy a provided pseudorandom number generator state
* @throws {TypeError} `alpha` must be a positive number
* @throws {TypeError} `beta` must be a positive number
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @throws {Error} must provide a valid state
* @returns {Function} pseudorandom number generator
*
* @example
* var beta = factory( 2.0, 1.0 );
* var v = beta();
* // returns <number>
*
* @example
* var beta = factory( 2.0, 2.0, {
*     'seed': 297
* });
* var v = beta();
* // returns <number>
*/
function factory() {
	var STATE;
	var rnorm;
	var alpha;
	var beta;
	var opts;
	var rand;
	var prng;
	var FLG;
	var err;

	FLG = true;
	if ( arguments.length === 0 ) {
		opts = {
			'copy': false
		};
		rand = randu( opts );
	} else if ( arguments.length === 1 ) {
		opts = arguments[ 0 ];
		if ( !isObject( opts ) ) {
			throw new TypeError( 'invalid argument. Options argument must be an object. Value: `' + opts + '`.' );
		}
		if ( hasOwnProp( opts, 'copy' ) && !isBoolean( opts.copy ) ) {
			throw new TypeError( 'invalid option. `copy` option must be a boolean. Option: `' + opts.copy + '`.' );
		}
		if ( hasOwnProp( opts, 'prng' ) ) {
			if ( !isFunction( opts.prng ) ) {
				throw new TypeError( 'invalid option. `prng` option must be a pseudorandom number generator function. Option: `' + opts.prng + '`.' );
			}
			rand = opts.prng;
		} else {
			if ( hasOwnProp( opts, 'state' ) && !isUint32Array( opts.state ) ) {
				throw new TypeError( 'invalid option. `state` option must be a Uint32Array. Option: `' + opts.state + '`.' );
			}
			opts = copy( opts, 1 );
			if ( opts.copy === false ) {
				FLG = false;
			} else if ( opts.state ) {
				opts.state = gcopy( opts.state.length, opts.state, 1, new Uint32Array( opts.state.length ), 1 ); // eslint-disable-line max-len
			}
			opts.copy = false;
			rand = randu( opts );
		}
	} else {
		alpha = arguments[ 0 ];
		beta = arguments[ 1 ];
		err = validate( alpha, beta );
		if ( err ) {
			throw err;
		}
		if ( arguments.length > 2 ) {
			opts = arguments[ 2 ];
			if ( !isObject( opts ) ) {
				throw new TypeError( 'invalid argument. Options argument must be an object. Value: `' + opts + '`.' );
			}
			if ( hasOwnProp( opts, 'copy' ) && !isBoolean( opts.copy ) ) {
				throw new TypeError( 'invalid option. `copy` option must be a boolean. Option: `' + opts.copy + '`.' );
			}
			if ( hasOwnProp( opts, 'prng' ) ) {
				if ( !isFunction( opts.prng ) ) {
					throw new TypeError( 'invalid option. `prng` option must be a pseudorandom number generator function. Option: `' + opts.prng + '`.' );
				}
				rand = opts.prng;
			} else {
				if ( hasOwnProp( opts, 'state' ) && !isUint32Array( opts.state ) ) {
					throw new TypeError( 'invalid option. `state` option must be a Uint32Array. Option: `' + opts.state + '`.' );
				}
				opts = copy( opts, 1 );
				if ( opts.copy === false ) {
					FLG = false;
				} else if ( opts.state ) {
					opts.state = gcopy( opts.state.length, opts.state, 1, new Uint32Array( opts.state.length ), 1 ); // eslint-disable-line max-len
				}
				opts.copy = false;
				rand = randu( opts );
			}
		} else {
			opts = {
				'copy': false
			};
			rand = randu( opts );
		}
	}
	if ( opts && opts.prng ) {
		rnorm = randn({
			'prng': opts.prng
		});
	} else {
		if ( opts.state ) {
			STATE = opts.state;
		} else {
			STATE = rand.state;
			rand.state = STATE; // updates the underlying PRNG to point to a shared state
		}
		rnorm = randn({
			'state': STATE,
			'copy': false
		});
	}
	if ( alpha === void 0 ) {
		prng = beta2;
	} else {
		prng = beta1;
	}
	setReadOnly( prng, 'NAME', 'beta' );

	// If we are provided an "external" PRNG, we don't support getting or setting PRNG state, as we'd need to check for compatible state value types, etc, entailing considerable complexity.
	if ( opts && opts.prng ) {
		setReadOnly( prng, 'seed', null );
		setReadOnly( prng, 'seedLength', null );
		setReadWriteAccessor( prng, 'state', constantFunction( null ), noop );
		setReadOnly( prng, 'stateLength', null );
		setReadOnly( prng, 'byteLength', null );
		setReadOnly( prng, 'toJSON', constantFunction( null ) );
		setReadOnly( prng, 'PRNG', rand );
	} else {
		setReadOnlyAccessor( prng, 'seed', getSeed );
		setReadOnlyAccessor( prng, 'seedLength', getSeedLength );
		setReadWriteAccessor( prng, 'state', getState, setState );
		setReadOnlyAccessor( prng, 'stateLength', getStateLength );
		setReadOnlyAccessor( prng, 'byteLength', getStateSize );
		setReadOnly( prng, 'toJSON', toJSON );
		setReadOnly( prng, 'PRNG', rand );
		rand = rand.normalized;
	}
	return prng;

	/**
	* Returns the PRNG seed.
	*
	* @private
	* @returns {Uint32Array} seed
	*/
	function getSeed() {
		return rand.seed;
	}

	/**
	* Returns the PRNG seed length.
	*
	* @private
	* @returns {PositiveInteger} seed length
	*/
	function getSeedLength() {
		return rand.seedLength;
	}

	/**
	* Returns the PRNG state length.
	*
	* @private
	* @returns {PositiveInteger} state length
	*/
	function getStateLength() {
		return rand.stateLength;
	}

	/**
	* Returns the PRNG state size (in bytes).
	*
	* @private
	* @returns {PositiveInteger} state size (in bytes)
	*/
	function getStateSize() {
		return rand.byteLength;
	}

	/**
	* Returns the current pseudorandom number generator state.
	*
	* @private
	* @returns {Uint32Array} current state
	*/
	function getState() {
		return rand.state;
	}

	/**
	* Sets the pseudorandom number generator state.
	*
	* @private
	* @param {Uint32Array} s - generator state
	* @throws {TypeError} must provide a `Uint32Array`
	* @throws {Error} must provide a valid state
	*/
	function setState( s ) {
		if ( !isUint32Array( s ) ) {
			throw new TypeError( 'invalid argument. Must provide a Uint32Array. Value: `' + s + '`.' );
		}
		if ( FLG ) {
			s = gcopy( s.length, s, 1, new Uint32Array( s.length ), 1 );
		}
		rand.state = s;
	}

	/**
	* Serializes the pseudorandom number generator as a JSON object.
	*
	* ## Notes
	*
	* -   `JSON.stringify()` implicitly calls this method when stringifying a PRNG.
	*
	* @private
	* @returns {Object} JSON representation
	*/
	function toJSON() {
		var out = {};
		out.type = 'PRNG';
		out.name = prng.NAME;
		out.state = typedarray2json( rand.state );
		if ( alpha === void 0 ) {
			out.params = [];
		} else {
			out.params = [ alpha, beta ];
		}
		return out;
	}

	/**
	* Returns a random number drawn from a beta distribution with bound parameter values.
	*
	* @private
	* @returns {Probability} pseudorandom number
	*
	* @example
	* var v = beta1();
	* // returns <number>
	*/
	function beta1() {
		return beta0( rand, rnorm, alpha, beta );
	}

	/**
	* Returns a random number drawn from a beta distribution.
	*
	* @private
	* @param {PositiveNumber} alpha - first shape parameter
	* @param {PositiveNumber} beta - second shape parameter
	* @returns {Probability} pseudorandom number
	*
	* @example
	* var v = beta2( 2.0, 3.0 );
	* // returns <number>
	*/
	function beta2( alpha, beta ) {
		if (
			isnan( alpha ) ||
			isnan( beta ) ||
			alpha <= 0.0 ||
			beta <= 0.0
		) {
			return NaN;
		}
		return beta0( rand, rnorm, alpha, beta );
	}
}

// EXPORTS //

module.exports = factory;
<commit_msg>Make properties non-enumerable<commit_after>/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*    http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

'use strict';

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var setReadOnlyAccessor = require( '@stdlib/utils/define-nonenumerable-read-only-accessor' );
var setReadWriteAccessor = require( '@stdlib/utils/define-nonenumerable-read-write-accessor' );
var isObject = require( '@stdlib/assert/is-plain-object' );
var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive;
var isFunction = require( '@stdlib/assert/is-function' );
var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var constantFunction = require( '@stdlib/utils/constant-function' );
var noop = require( '@stdlib/utils/noop' );
var randn = require( '@stdlib/random/base/improved-ziggurat' ).factory;
var randu = require( '@stdlib/random/base/mt19937' ).factory;
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var gcopy = require( '@stdlib/blas/base/gcopy' );
var Uint32Array = require( '@stdlib/array/uint32' );
var isUint32Array = require( '@stdlib/assert/is-uint32array' );
var copy = require( '@stdlib/utils/copy' );
var typedarray2json = require( '@stdlib/array/to-json' );
var validate = require( './validate.js' );
var beta0 = require( './beta.js' );

// MAIN //

/**
* Returns a pseudorandom number generator for generating beta distributed random numbers.
*
* @param {PositiveNumber} [alpha] - first shape parameter
* @param {PositiveNumber} [beta] - second shape parameter
* @param {Options} [options] - function options
* @param {Function} [options.prng] - pseudorandom number generator which generates uniformly distributed pseudorandom numbers
* @param {(uinteger32|Collection<uinteger32>)} [options.seed] - pseudorandom number generator seed
* @param {Uint32Array} [options.state] - pseudorandom number generator state
* @param {boolean} [options.copy=true] - boolean indicating whether to copy a provided pseudorandom number generator state
* @throws {TypeError} `alpha` must be a positive number
* @throws {TypeError} `beta` must be a positive number
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @throws {Error} must provide a valid state
* @returns {Function} pseudorandom number generator
*
* @example
* var beta = factory( 2.0, 1.0 );
* var v = beta();
* // returns <number>
*
* @example
* var beta = factory( 2.0, 2.0, {
*     'seed': 297
* });
* var v = beta();
* // returns <number>
*/
function factory() {
	var STATE;
	var rnorm;
	var alpha;
	var beta;
	var opts;
	var rand;
	var prng;
	var FLG;
	var err;

	FLG = true;
	if ( arguments.length === 0 ) {
		opts = {
			'copy': false
		};
		rand = randu( opts );
	} else if ( arguments.length === 1 ) {
		opts = arguments[ 0 ];
		if ( !isObject( opts ) ) {
			throw new TypeError( 'invalid argument. Options argument must be an object. Value: `' + opts + '`.' );
		}
		if ( hasOwnProp( opts, 'copy' ) && !isBoolean( opts.copy ) ) {
			throw new TypeError( 'invalid option. `copy` option must be a boolean. Option: `' + opts.copy + '`.' );
		}
		if ( hasOwnProp( opts, 'prng' ) ) {
			if ( !isFunction( opts.prng ) ) {
				throw new TypeError( 'invalid option. `prng` option must be a pseudorandom number generator function. Option: `' + opts.prng + '`.' );
			}
			rand = opts.prng;
		} else {
			if ( hasOwnProp( opts, 'state' ) && !isUint32Array( opts.state ) ) {
				throw new TypeError( 'invalid option. `state` option must be a Uint32Array. Option: `' + opts.state + '`.' );
			}
			opts = copy( opts, 1 );
			if ( opts.copy === false ) {
				FLG = false;
			} else if ( opts.state ) {
				opts.state = gcopy( opts.state.length, opts.state, 1, new Uint32Array( opts.state.length ), 1 ); // eslint-disable-line max-len
			}
			opts.copy = false;
			rand = randu( opts );
		}
	} else {
		alpha = arguments[ 0 ];
		beta = arguments[ 1 ];
		err = validate( alpha, beta );
		if ( err ) {
			throw err;
		}
		if ( arguments.length > 2 ) {
			opts = arguments[ 2 ];
			if ( !isObject( opts ) ) {
				throw new TypeError( 'invalid argument. Options argument must be an object. Value: `' + opts + '`.' );
			}
			if ( hasOwnProp( opts, 'copy' ) && !isBoolean( opts.copy ) ) {
				throw new TypeError( 'invalid option. `copy` option must be a boolean. Option: `' + opts.copy + '`.' );
			}
			if ( hasOwnProp( opts, 'prng' ) ) {
				if ( !isFunction( opts.prng ) ) {
					throw new TypeError( 'invalid option. `prng` option must be a pseudorandom number generator function. Option: `' + opts.prng + '`.' );
				}
				rand = opts.prng;
			} else {
				if ( hasOwnProp( opts, 'state' ) && !isUint32Array( opts.state ) ) {
					throw new TypeError( 'invalid option. `state` option must be a Uint32Array. Option: `' + opts.state + '`.' );
				}
				opts = copy( opts, 1 );
				if ( opts.copy === false ) {
					FLG = false;
				} else if ( opts.state ) {
					opts.state = gcopy( opts.state.length, opts.state, 1, new Uint32Array( opts.state.length ), 1 ); // eslint-disable-line max-len
				}
				opts.copy = false;
				rand = randu( opts );
			}
		} else {
			opts = {
				'copy': false
			};
			rand = randu( opts );
		}
	}
	if ( opts && opts.prng ) {
		rnorm = randn({
			'prng': opts.prng
		});
	} else {
		if ( opts.state ) {
			STATE = opts.state;
		} else {
			STATE = rand.state;
			rand.state = STATE; // updates the underlying PRNG to point to a shared state
		}
		rnorm = randn({
			'state': STATE,
			'copy': false
		});
	}
	if ( alpha === void 0 ) {
		prng = beta2;
	} else {
		prng = beta1;
	}
	setReadOnly( prng, 'NAME', 'beta' );

	// If we are provided an "external" PRNG, we don't support getting or setting PRNG state, as we'd need to check for compatible state value types, etc, entailing considerable complexity.
	if ( opts && opts.prng ) {
		setReadOnly( prng, 'seed', null );
		setReadOnly( prng, 'seedLength', null );
		setReadWriteAccessor( prng, 'state', constantFunction( null ), noop );
		setReadOnly( prng, 'stateLength', null );
		setReadOnly( prng, 'byteLength', null );
		setReadOnly( prng, 'toJSON', constantFunction( null ) );
		setReadOnly( prng, 'PRNG', rand );
	} else {
		setReadOnlyAccessor( prng, 'seed', getSeed );
		setReadOnlyAccessor( prng, 'seedLength', getSeedLength );
		setReadWriteAccessor( prng, 'state', getState, setState );
		setReadOnlyAccessor( prng, 'stateLength', getStateLength );
		setReadOnlyAccessor( prng, 'byteLength', getStateSize );
		setReadOnly( prng, 'toJSON', toJSON );
		setReadOnly( prng, 'PRNG', rand );
		rand = rand.normalized;
	}
	return prng;

	/**
	* Returns the PRNG seed.
	*
	* @private
	* @returns {Uint32Array} seed
	*/
	function getSeed() {
		return rand.seed;
	}

	/**
	* Returns the PRNG seed length.
	*
	* @private
	* @returns {PositiveInteger} seed length
	*/
	function getSeedLength() {
		return rand.seedLength;
	}

	/**
	* Returns the PRNG state length.
	*
	* @private
	* @returns {PositiveInteger} state length
	*/
	function getStateLength() {
		return rand.stateLength;
	}

	/**
	* Returns the PRNG state size (in bytes).
	*
	* @private
	* @returns {PositiveInteger} state size (in bytes)
	*/
	function getStateSize() {
		return rand.byteLength;
	}

	/**
	* Returns the current pseudorandom number generator state.
	*
	* @private
	* @returns {Uint32Array} current state
	*/
	function getState() {
		return rand.state;
	}

	/**
	* Sets the pseudorandom number generator state.
	*
	* @private
	* @param {Uint32Array} s - generator state
	* @throws {TypeError} must provide a `Uint32Array`
	* @throws {Error} must provide a valid state
	*/
	function setState( s ) {
		if ( !isUint32Array( s ) ) {
			throw new TypeError( 'invalid argument. Must provide a Uint32Array. Value: `' + s + '`.' );
		}
		if ( FLG ) {
			s = gcopy( s.length, s, 1, new Uint32Array( s.length ), 1 );
		}
		rand.state = s;
	}

	/**
	* Serializes the pseudorandom number generator as a JSON object.
	*
	* ## Notes
	*
	* -   `JSON.stringify()` implicitly calls this method when stringifying a PRNG.
	*
	* @private
	* @returns {Object} JSON representation
	*/
	function toJSON() {
		var out = {};
		out.type = 'PRNG';
		out.name = prng.NAME;
		out.state = typedarray2json( rand.state );
		if ( alpha === void 0 ) {
			out.params = [];
		} else {
			out.params = [ alpha, beta ];
		}
		return out;
	}

	/**
	* Returns a random number drawn from a beta distribution with bound parameter values.
	*
	* @private
	* @returns {Probability} pseudorandom number
	*
	* @example
	* var v = beta1();
	* // returns <number>
	*/
	function beta1() {
		return beta0( rand, rnorm, alpha, beta );
	}

	/**
	* Returns a random number drawn from a beta distribution.
	*
	* @private
	* @param {PositiveNumber} alpha - first shape parameter
	* @param {PositiveNumber} beta - second shape parameter
	* @returns {Probability} pseudorandom number
	*
	* @example
	* var v = beta2( 2.0, 3.0 );
	* // returns <number>
	*/
	function beta2( alpha, beta ) {
		if (
			isnan( alpha ) ||
			isnan( beta ) ||
			alpha <= 0.0 ||
			beta <= 0.0
		) {
			return NaN;
		}
		return beta0( rand, rnorm, alpha, beta );
	}
}

// EXPORTS //

module.exports = factory;
<|endoftext|>


<commit_before>/* Copyright (c) 2015-2016 The TagSpaces Authors.
 * Use of this source code is governed by the MIT license which can be found in the LICENSE.txt file. */

define(function(require, exports, module) {
  "use strict";

  var extensionTitle = "ImageSwiper"; // should be equal to the name in the bower.json
  var extensionID = "perspectiveImageSwiper"; // ID should be equal to the directory name where the ext. is located
  var extensionIcon = "fa fa-image"; // icon class from font awesome

  console.log("Loading " + extensionID);

  var TSCORE = require("tscore");
  var marked = require('marked');
  var extensionDirectory = TSCORE.Config.getExtensionPath() + "/" + extensionID;
  var UI;
  var $viewContainer = $("#" + extensionID + "Container");
  var homeScreen;
  var template;
  var UI;
  var aboutContent;
  var extensionLoaded;

  function init() {
    console.log("Initializing perspective " + extensionID);

    $viewContainer = $("#" + extensionID + "Container").empty();

    extensionLoaded = new Promise(function(resolve, reject) {
      require([
        extensionDirectory + "/perspectiveUI.js",
        "text!" + extensionDirectory + "/extension.html",
        "css!" + extensionDirectory + "/libs/photoswipe/dist/photoswipe.css",
        "css!" + extensionDirectory + "/libs/photoswipe/dist/default-skin/default-skin.css",
        "css!" + extensionDirectory + "/extension.css",
        ], function(perspectiveUI, tmpl, marked) {
          UI = perspectiveUI;
          template = tmpl;
          UI.initUI(extensionDirectory);
          resolve(true);
        }
      );
    });
  }

  function load() {
    console.log("Loading perspective " + extensionID);
    extensionLoaded.then(function() {
      UI.load($viewContainer, template);
      platformTuning();
      $('#' + extensionID + 'Container [data-i18n]').i18n();
      TSCORE.hideLoadingAnimation();
      try {
        require(["marked"], function(marked) {
          $('#aboutExtensionModalImageSwiper').on('show.bs.modal', function() {
            $.ajax({
              url: extensionDirectory + '/README.md',
              type: 'GET'
            })
            .done(function(mdData) {
              //console.log("DATA: " + mdData);
              if (marked) {
                var modalBody = $("#aboutExtensionModalImageSwiper .modal-body");
                modalBody.html(marked(mdData, {sanitize: true}));
                handleLinks(modalBody);
              } else {
                console.log("markdown to html transformer not found");
              }
            })
            .fail(function(data) {
              console.warn("Loading file failed " + data);
            });
          });
        });
      } catch (err) {
        console.log("Failed translating extension");
      }
    });
  }

  function handleLinks($element) {
    $element.find("a[href]").each(function() {
      var currentSrc = $(this).attr("href");
      $(this).bind('click', function(e) {
        e.preventDefault();
        var msg = {command: "openLinkExternally", link : currentSrc};
        window.parent.postMessage(JSON.stringify(msg), "*");
      });
    });
  }

  function platformTuning() {
    if (isCordova) {
      $('#imageSwipperTagButton').hide();
      $('#imageSwipperRenameButton').hide();
    }
  }

  function clearSelectedFiles() {}

  function removeFileUI(filePath) {}

  function updateFileUI(oldFilePath, newFilePath) {
    UI.updateFileUI(oldFilePath, newFilePath);
  }

  function getNextFile(filePath) {}

  function getPrevFile(filePath) {}

  function updateTreeData(fsTreeData) {

    console.log("Updating tree data not implemented");
  }

  function setReadOnly(filePath) {
    $('#imageSwipperTagButton').hide();
    $("#imageSwipperRenameButton").hide();

    $(document).off('drop dragend dragenter dragover dragleave', function(event) {
      event.preventDefault();
    });
  }

  // API Vars
  exports.Title = extensionTitle;
  exports.ID = extensionID;
  exports.Icon = extensionIcon;

  // API Methods
  exports.init = init;
  exports.load = load;
  exports.clearSelectedFiles = clearSelectedFiles;
  exports.getNextFile = getNextFile;
  exports.getPrevFile = getPrevFile;
  exports.removeFileUI = removeFileUI;
  exports.updateFileUI = updateFileUI;
  exports.updateTreeData = updateTreeData;
  exports.setReadOnly = setReadOnly;
});<commit_msg>disabling tagging and renaming buttons<commit_after>/* Copyright (c) 2015-2016 The TagSpaces Authors.
 * Use of this source code is governed by the MIT license which can be found in the LICENSE.txt file. */

define(function(require, exports, module) {
  "use strict";

  var extensionTitle = "ImageSwiper"; // should be equal to the name in the bower.json
  var extensionID = "perspectiveImageSwiper"; // ID should be equal to the directory name where the ext. is located
  var extensionIcon = "fa fa-image"; // icon class from font awesome

  console.log("Loading " + extensionID);

  var TSCORE = require("tscore");
  var marked = require('marked');
  var extensionDirectory = TSCORE.Config.getExtensionPath() + "/" + extensionID;
  var UI;
  var $viewContainer = $("#" + extensionID + "Container");
  var homeScreen;
  var template;
  var UI;
  var aboutContent;
  var extensionLoaded;

  function init() {
    console.log("Initializing perspective " + extensionID);

    $viewContainer = $("#" + extensionID + "Container").empty();

    extensionLoaded = new Promise(function(resolve, reject) {
      require([
        extensionDirectory + "/perspectiveUI.js",
        "text!" + extensionDirectory + "/extension.html",
        "css!" + extensionDirectory + "/libs/photoswipe/dist/photoswipe.css",
        "css!" + extensionDirectory + "/libs/photoswipe/dist/default-skin/default-skin.css",
        "css!" + extensionDirectory + "/extension.css",
        ], function(perspectiveUI, tmpl, marked) {
          UI = perspectiveUI;
          template = tmpl;
          UI.initUI(extensionDirectory);
          resolve(true);
        }
      );
    });
  }

  function load() {
    console.log("Loading perspective " + extensionID);
    extensionLoaded.then(function() {
      UI.load($viewContainer, template);
      platformTuning();
      $('#' + extensionID + 'Container [data-i18n]').i18n();
      TSCORE.hideLoadingAnimation();
      try {
        require(["marked"], function(marked) {
          $('#aboutExtensionModalImageSwiper').on('show.bs.modal', function() {
            $.ajax({
              url: extensionDirectory + '/README.md',
              type: 'GET'
            })
            .done(function(mdData) {
              //console.log("DATA: " + mdData);
              if (marked) {
                var modalBody = $("#aboutExtensionModalImageSwiper .modal-body");
                modalBody.html(marked(mdData, {sanitize: true}));
                handleLinks(modalBody);
              } else {
                console.log("markdown to html transformer not found");
              }
            })
            .fail(function(data) {
              console.warn("Loading file failed " + data);
            });
          });
        });
      } catch (err) {
        console.log("Failed translating extension");
      }
    });
  }

  function handleLinks($element) {
    $element.find("a[href]").each(function() {
      var currentSrc = $(this).attr("href");
      $(this).bind('click', function(e) {
        e.preventDefault();
        var msg = {command: "openLinkExternally", link : currentSrc};
        window.parent.postMessage(JSON.stringify(msg), "*");
      });
    });
  }

  function platformTuning() {
    // TODO handle tap events cordova, handle key event: left & right arrows switch the image underneeth
    // if (isCordova) {
    $('#imageSwipperTagButton').hide();
    $('#imageSwipperRenameButton').hide();
    // }
  }

  function clearSelectedFiles() {}

  function removeFileUI(filePath) {}

  function updateFileUI(oldFilePath, newFilePath) {
    UI.updateFileUI(oldFilePath, newFilePath);
  }

  function getNextFile(filePath) {}

  function getPrevFile(filePath) {}

  function updateTreeData(fsTreeData) {

    console.log("Updating tree data not implemented");
  }

  function setReadOnly(filePath) {
    $('#imageSwipperTagButton').hide();
    $("#imageSwipperRenameButton").hide();

    $(document).off('drop dragend dragenter dragover dragleave', function(event) {
      event.preventDefault();
    });
  }

  // API Vars
  exports.Title = extensionTitle;
  exports.ID = extensionID;
  exports.Icon = extensionIcon;

  // API Methods
  exports.init = init;
  exports.load = load;
  exports.clearSelectedFiles = clearSelectedFiles;
  exports.getNextFile = getNextFile;
  exports.getPrevFile = getPrevFile;
  exports.removeFileUI = removeFileUI;
  exports.updateFileUI = updateFileUI;
  exports.updateTreeData = updateTreeData;
  exports.setReadOnly = setReadOnly;
});<|endoftext|>


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

'use strict';

/**
* Remove the last character of a string.
*
* @module @stdlib/string/remove-last
*
* @example
* var removeLast = require( '@stdlib/string/remove-last' );
*
* var out = removeLast( 'last man standing' );
* // returns 'last man standin'
*
* out = removeLast( 'Hidden Treasures' );
* // returns 'Hidden Treasure';
*
* out = removeLast( '🐮🐷🐸🐵', '🐵' ) );
* // returns '🐮🐷🐸'
*/

// MODULES //

var removeLast = require( './main.js' );

// EXPORTS //

module.exports = removeLast;
<commit_msg>Fix main description<commit_after>/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*    http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

'use strict';

/**
* Remove the last character(s) of a string.
*
* @module @stdlib/string/remove-last
*
* @example
* var removeLast = require( '@stdlib/string/remove-last' );
*
* var out = removeLast( 'last man standing' );
* // returns 'last man standin'
*
* out = removeLast( 'Hidden Treasures' );
* // returns 'Hidden Treasure';
*
* out = removeLast( '🐮🐷🐸🐵', 2 ) );
* // returns '🐮🐷'
*/

// MODULES //

var removeLast = require( './main.js' );

// EXPORTS //

module.exports = removeLast;
<|endoftext|>


<commit_before>var fs = require('fs');
var request = require('request'), iconv  = require('iconv-lite');
var cheerio = require('cheerio');
var SnowBall = require('jsnowball');

// Import CSV
var csv = require("fast-csv");

// Create a Limdu Model
function newClassifierFunction() {
		var limdu = require('limdu');

		// First, define our base classifier type (a multi-label classifier based on svm.js):
		var TextClassifier = limdu.classifiers.multilabel.BinaryRelevance.bind(0, {
		    binaryClassifierType: limdu.classifiers.Winnow.bind(0, {retrain_count: 10})
		});

		// Initialize a classifier with a feature extractor and a lookup table:
		return new limdu.classifiers.EnhancedClassifier({
		    classifierType: TextClassifier,
		    featureExtractor: limdu.features.NGramsOfWords(1),  // each word ("1-gram") is a feature
		    featureLookupTable: new limdu.features.FeatureLookupTable(),
		    pastTrainingSamples: []
		});
}

// Limdu
var serialize = require('serialization');
var intentClassifier = serialize.fromString(fs.readFileSync("data/model.data", 'utf8'), __dirname);

//var intentClassifier = newClassifierFunction();

// Extractor
var extractor = require('unfluff');

var startIndex = 0;
var doneIndex = 0;
var end = false;

/*csv
.fromPath("data/import/MatchReports.csv")
.on("data", function(data){
	if ( data[0].indexOf("http") < 0 ) {
		return;
	}

	startIndex++;

	parse(data[0], data[1], function () {
		doneIndex++;

		if ( startIndex == doneIndex && end == true ) {
			console.log(startIndex, doneIndex);
			fs.writeFile( "data/model.data", serialize.toString(intentClassifier, newClassifierFunction), "utf8" );
		}
	});
})
.on("end", function(){
	end = true;
}).on("error", function () {
	console.log("Error");
});*/

// Parse URL
function parse ( url, category, language, callback ) {
	request(url, function (error, response, body) {
		var body = iconv.decode(new Buffer(body), "ISO-8859-1");
		if ( ! error && ( response.statusCode == 200 || response.statusCode == 300 ) ) {
			$ = cheerio.load(body);

			var stopwords = fs.readFileSync("data/stopwords/" + language + ".txt", 'utf8').split("\n");

			var data = extractor(body, language);

			stopwords.forEach(function ( word, index ) {
				word = word.trim();

				data.text = data.text.replace(new RegExp('\\b' + word + '\\b', "gi"), '').replace("  ", " ");
			});

			data.text = data.text.replace(/\n\r/g, " ").replace(/\n/g, " ").replace(".", "").replace(/\s{2,}/g, ' ').trim();

			var snowBall = new SnowBall('danish');
			snowBall.stem(data.text, function( error,response ) {
				if ( ! error ) {
					var text = response.join(" ");
					console.log(intentClassifier.classify(text));
					//intentClassifier.trainOnline(text, category);
					//fs.writeFile( "data/model.data", serialize.toString(intentClassifier, newClassifierFunction), "utf8" );
				}
			});

			//console.log(intentClassifier.classify(data.text));

			//intentClassifier.trainOnline(data.text, category);

			//fs.writeFile( "data/model.data", serialize.toString(intentClassifier, newClassifierFunction), "utf8" );
			//callback();

		} else {
			console.log(error);
			// Error
		}
	});
}

parse("http://www.bold.dk/fodbold/nyheder/broendby-henter-profil-i-lyngby/", "Soccer/Transfers", "da");<commit_msg>Entity Removal<commit_after>var fs = require('fs');
var request = require('request'), iconv  = require('iconv-lite');
var cheerio = require('cheerio');
var SnowBall = require('jsnowball');

// Import CSV
var csv = require("fast-csv");

// Create a Limdu Model
function newClassifierFunction() {
		var limdu = require('limdu');

		// First, define our base classifier type (a multi-label classifier based on svm.js):
		var TextClassifier = limdu.classifiers.multilabel.BinaryRelevance.bind(0, {
		    binaryClassifierType: limdu.classifiers.Winnow.bind(0, {retrain_count: 10})
		});

		// Initialize a classifier with a feature extractor and a lookup table:
		return new limdu.classifiers.EnhancedClassifier({
		    classifierType: TextClassifier,
		    featureExtractor: limdu.features.NGramsOfWords(1),  // each word ("1-gram") is a feature
		    featureLookupTable: new limdu.features.FeatureLookupTable(),
		    pastTrainingSamples: []
		});
}

var arrayUnique = function(a) {
	return a.reduce(function(p, c) {
			if (p.indexOf(c) < 0) p.push(c);
			return p;
	}, []);
};

function removeNewlines(str) {
	//remove line breaks from str
	str = str.replace(/\s{2,}/g, ' : ');
	str = str.replace(/\t/g, ' : ');
	str = str.toString().trim().replace(/(\r\n|\n|\r)/g," : ");
	return str;
}

function removeArray ( arr, text ) {
	text = String(text);
	arr.forEach( function ( element, index ) {
		text = text.replace(new RegExp(element, "g"), "");
	} );

	return text;
}

// Limdu
var serialize = require('serialization');
//var intentClassifier = serialize.fromString(fs.readFileSync("data/model.data", 'utf8'), __dirname);

var intentClassifier = newClassifierFunction();

// Extractor
var extractor = require('unfluff');

var startIndex = 0;
var doneIndex = 0;
var end = false;

/*csv
.fromPath("data/import/MatchReports.csv")
.on("data", function(data){
	if ( data[0].indexOf("http") < 0 ) {
		return;
	}

	startIndex++;

	parse(data[0], data[1], function () {
		doneIndex++;

		if ( startIndex == doneIndex && end == true ) {
			console.log(startIndex, doneIndex);
			fs.writeFile( "data/model.data", serialize.toString(intentClassifier, newClassifierFunction), "utf8" );
		}
	});
})
.on("end", function(){
	end = true;
}).on("error", function () {
	console.log("Error");
});*/

// Parse URL
function parse ( url, category, language, callback ) {
	request(url, function (error, response, body) {
		var body = iconv.decode(new Buffer(body), "ISO-8859-1");
		if ( ! error && ( response.statusCode == 200 || response.statusCode == 300 ) ) {
			$ = cheerio.load(body);

			var stopwords = fs.readFileSync("data/stopwords/" + language + ".txt", 'utf8').split("\n");

			var data = extractor(body, language);

			stopwords.forEach(function ( word, index ) {
				word = word.trim();

				data.text = data.text.replace(new RegExp('\\b' + word + '\\b', "gi"), '').replace("  ", " ");
			});

			data.text = data.text.replace(/\n\r/g, " ").replace(/\n/g, " . ").replace(".", "").replace(/\s{2,}/g, ' ').trim();

			var snowBall = new SnowBall('danish');
			snowBall.stem(data.text, function( error,response ) {
				if ( ! error ) {
					var text = response.join(" ");
					removeEntities( text, language, function ( text ) {
						intentClassifier.trainOnline(text, category);
						fs.writeFile( "data/model.data", serialize.toString(intentClassifier, newClassifierFunction), "utf8" );
					} );
				}
			});

			//console.log(intentClassifier.classify(data.text));

			//intentClassifier.trainOnline(data.text, category);

			//fs.writeFile( "data/model.data", serialize.toString(intentClassifier, newClassifierFunction), "utf8" );
			//callback();

		} else {
			console.log(error);
			// Error
		}
	});
}

function removeEntities ( text, language, callback ) {
	var settings = JSON.parse(require('fs').readFileSync(`data/ner/${language}.json`, 'utf8'));

	text = removeArray(settings.replaces, removeNewlines(text));

	request.post({
		headers: {'content-type' : 'application/json'},
		url:     'http://127.0.0.1:3000/',
		method: 'POST',
		encoding: 'utf8',
		json: {"text": text}
	}, function( error, response, body ){
		if ( error || body == undefined ) {
			return false;
		}

		var entities = [];
		var items = [];

		if ( body["MISC"] != undefined ) {
			items = items.concat(body["MISC"]);
		}

		if ( body["PERSON"] != undefined ) {
			items = items.concat( body["PERSON"]);
		}

		if ( body["LOCATION"] != undefined ) {
			items = items.concat(body["LOCATION"]);
		}

		if ( body["ORGANIZATION"] != undefined ) {
			items = items.concat(body["ORGANIZATION"]);
		}

		entities = arrayUnique(items);

		entities.forEach( function ( element, index ) {
			if ( settings.blacklist.indexOf(element) >= 0 ) {
				entities.splice(index, 1);
			}

			settings.split_list.forEach( function ( el ) {
				var s = element.split(el);
				if ( s[0] != element ) {
					entities.splice(index, 1);

					entities = entities.concat(s);
				}
			} );
		} );

		entities.forEach(function ( entity, index ) {
			if ( index != null && index != undefined && entity != undefined ) {
				text = text.replace(new RegExp('\\b' + entity + '\\b', "gi"), '').replace("  ", " ");
			}
		});

		text = text.replace(/-/g, "").replace(new RegExp(" r ", "g"));

		console.log(text);

		callback(text);
	});
}

parse("http://www.bold.dk/fodbold/nyheder/broendby-henter-profil-i-lyngby/", "Soccer/Transfers", "da");<|endoftext|>


<commit_before>'use strict';

/*
* When adding modules to the namespace, ensure that they are added in alphabetical order according to module name.
*/

// MODULES //

// var setReadOnly = require( '@stdlib/utils/define-read-only-property' );

// MAIN //

/**
* Top-level namespace.
*
* @namespace ns
*/
var ns = {};

// EXPORTS //

module.exports = ns;
<commit_msg>Update namespace<commit_after>'use strict';

/*
* When adding modules to the namespace, ensure that they are added in alphabetical order according to module name.
*/

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );

// MAIN //

/**
* Top-level namespace.
*
* @namespace ns
*/
var ns = {};

/**
* @name bind2vind
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/types/ndarray/base/bind2vind}
*/
setReadOnly( ns, 'bind2vind', require( '@stdlib/types/ndarray/base/bind2vind' ) );

// EXPORTS //

module.exports = ns;
<|endoftext|>


<commit_before>'use strict';

// MODULES //

var tape = require( 'tape' );
var isAlphagram = require( './../lib' );

// TESTS //

tape( 'main export is a function', function test( t ) {
	t.ok( true, __filename );
	t.strictEqual( typeof isAlphagram, 'function', 'main export is a function' );
	t.end();
});

tape( 'the function returns `true` if provided an alphagram', function test( t ) {
	t.strictEqual( isAlphagram( 'abcdef' ), true, 'returns true' );
	t.strictEqual( isAlphagram( new String( 'beep' ) ), true, 'returns true' );
	t.end();
});

tape( 'the function returns `false` if not provided an alphagram', function test( t ) {
	var values;
	var i;

	values = [
		'zba',
		'akjdfa',
		' abc   ',
		'',
		5,
		null,
		NaN,
		undefined,
		true,
		[],
		{},
		function noop() {}
	];

	for ( i = 0; i < values.length; i++ ) {
		t.strictEqual( isAlphagram( 'bat', values[i] ), false, 'returns false when provided ' + values[i] + ' and `bat`' );
	}
	t.end();
});
<commit_msg>Fix test<commit_after>'use strict';

// MODULES //

var tape = require( 'tape' );
var isAlphagram = require( './../lib' );

// TESTS //

tape( 'main export is a function', function test( t ) {
	t.ok( true, __filename );
	t.strictEqual( typeof isAlphagram, 'function', 'main export is a function' );
	t.end();
});

tape( 'the function returns `true` if provided an alphagram', function test( t ) {
	t.strictEqual( isAlphagram( 'abcdef' ), true, 'returns true' );
	t.strictEqual( isAlphagram( new String( 'beep' ) ), true, 'returns true' );
	t.end();
});

tape( 'the function returns `false` if not provided an alphagram', function test( t ) {
	var values;
	var i;

	values = [
		'zba',
		'akjdfa',
		' abc   ',
		'',
		5,
		null,
		NaN,
		undefined,
		true,
		[],
		{},
		function noop() {}
	];

	for ( i = 0; i < values.length; i++ ) {
		t.strictEqual( isAlphagram( values[i] ), false, 'returns false when provided ' + values[i] );
	}
	t.end();
});
<|endoftext|>


<commit_before>// package-test.js: check to make sure that all dependcies are sufficiently up
// to date. If dependencies are too outdated, exit with an error, failing `npm
// run update:packages` and thus eventually the entire build.

const package = require('./package.json');
const packageJson = require('package-json');
const SAFE_TIME = 1000 * 1 * 60 * 60 * 24 * 7; //7days
// webpack has a major update
// copy-webpack-plugin major update
// holding off on husky changes as the cli still has some weird necessary changes to run commitlint
const EXCEPTIONS = [
  'multicoin-address-validator',
  'postcss-import',
  'postcss-url',
  'webpack',
  'copy-webpack-plugin',
  'sass-loader',
  'husky',
  '@aave/protocol-js',
  'sass',
  'web3',
  'web3-core-helpers',
  'web3-core-method',
  'web3-core-requestmanager',
  'web3-utils',
  'remark-cli',
  'node-fetch',
  'vuetify',
  'eslint',
  'imagemin-mozjpeg', // issue with importing it to vue config will look into it more if we need it
  '@vue/eslint-config-prettier', // creates more warnings
  // versions for vue3
  'vue-router',
  'vuex',
  '@vue/test-utils',
  '@vue/babel-preset-app',
  '@vue/cli-plugin-babel',
  '@vue/cli-plugin-eslint',
  '@vue/cli-plugin-pwa',
  '@vue/cli-plugin-unit-jest',
  '@vue/cli-service',
  'vue-i18n',
  'vue'
];
const CUSTOM_DIST = {
  ['babel-core']: 'bridge'
};
const ALL_PACKAGES = Object.assign(
  package.dependencies,
  package.devDependencies
);
const names = Object.keys(ALL_PACKAGES);
let updatesFound = false;
const looper = () => {
  if (!names.length) {
    if (updatesFound) {
      console.error(
        '\nREFUSING TO CONTINUE because above packages are TOO FAR OUT OF DATE!'
      );
      console.error(
        'In order to build MyEtherWallet, you must edit package.json.'
      );
      console.error(
        'Update the versions for the packages above to their current versions.'
      );
      console.error('Then run `npm update`.');
      console.error();
      process.exit(1);
    } else {
      process.exit(0);
    }
  }
  const _name = names.shift();
  if (EXCEPTIONS.includes(_name)) return looper();
  if (ALL_PACKAGES[_name].includes('^') || ALL_PACKAGES[_name].includes('~')) {
    console.error(
      'Invalid character ~ or ^ found in package.json version string, only fixed versions are allowed.'
    );
    process.exit(1);
  }
  packageJson(_name, {
    fullMetadata: true,
    allVersions: true
  })
    .then(info => {
      const latestVersion = info['dist-tags'][CUSTOM_DIST[_name] || 'latest'];
      const latestVersionTime = info['time'][latestVersion];
      if (ALL_PACKAGES[_name] !== latestVersion) {
        const isBehind =
          new Date(latestVersionTime).getTime() <
          new Date().getTime() - SAFE_TIME;
        const isMewComponentBeta =
          _name === '@myetherwallet/mew-components' &&
          latestVersion.includes('-beta');
        if (isBehind) {
          if (!isMewComponentBeta) {
            console.error(
              'ERROR: Update ' +
                _name +
                ' from ' +
                ALL_PACKAGES[_name] +
                ' to ' +
                latestVersion +
                '. Released:',
              latestVersionTime
            );
            updatesFound = true;
          }
        }
      }
    })
    .then(looper);
};
looper();
<commit_msg>chore: 👷 exclude package<commit_after>// package-test.js: check to make sure that all dependcies are sufficiently up
// to date. If dependencies are too outdated, exit with an error, failing `npm
// run update:packages` and thus eventually the entire build.

const package = require('./package.json');
const packageJson = require('package-json');
const SAFE_TIME = 1000 * 1 * 60 * 60 * 24 * 7; //7days
// webpack has a major update
// copy-webpack-plugin major update
// holding off on husky changes as the cli still has some weird necessary changes to run commitlint
const EXCEPTIONS = [
  'multicoin-address-validator',
  'postcss-import',
  'postcss-url',
  'webpack',
  'copy-webpack-plugin',
  'sass-loader',
  'husky',
  '@aave/protocol-js',
  'sass',
  'web3',
  'web3-core-helpers',
  'web3-core-method',
  'web3-core-requestmanager',
  'web3-utils',
  'remark-cli',
  'node-fetch',
  'vuetify',
  'eslint',
  'imagemin-mozjpeg', // issue with importing it to vue config will look into it more if we need it
  '@vue/eslint-config-prettier', // creates more warnings
  // versions for vue3
  'vue-router',
  'vuex',
  '@vue/test-utils',
  '@vue/babel-preset-app',
  '@vue/cli-plugin-babel',
  '@vue/cli-plugin-eslint',
  '@vue/cli-plugin-pwa',
  '@vue/cli-plugin-unit-jest',
  '@vue/cli-service',
  'vue-i18n',
  'vue',
  // update after release
  '@ledgerhq/hw-app-eth'
];
const CUSTOM_DIST = {
  ['babel-core']: 'bridge'
};
const ALL_PACKAGES = Object.assign(
  package.dependencies,
  package.devDependencies
);
const names = Object.keys(ALL_PACKAGES);
let updatesFound = false;
const looper = () => {
  if (!names.length) {
    if (updatesFound) {
      console.error(
        '\nREFUSING TO CONTINUE because above packages are TOO FAR OUT OF DATE!'
      );
      console.error(
        'In order to build MyEtherWallet, you must edit package.json.'
      );
      console.error(
        'Update the versions for the packages above to their current versions.'
      );
      console.error('Then run `npm update`.');
      console.error();
      process.exit(1);
    } else {
      process.exit(0);
    }
  }
  const _name = names.shift();
  if (EXCEPTIONS.includes(_name)) return looper();
  if (ALL_PACKAGES[_name].includes('^') || ALL_PACKAGES[_name].includes('~')) {
    console.error(
      'Invalid character ~ or ^ found in package.json version string, only fixed versions are allowed.'
    );
    process.exit(1);
  }
  packageJson(_name, {
    fullMetadata: true,
    allVersions: true
  })
    .then(info => {
      const latestVersion = info['dist-tags'][CUSTOM_DIST[_name] || 'latest'];
      const latestVersionTime = info['time'][latestVersion];
      if (ALL_PACKAGES[_name] !== latestVersion) {
        const isBehind =
          new Date(latestVersionTime).getTime() <
          new Date().getTime() - SAFE_TIME;
        const isMewComponentBeta =
          _name === '@myetherwallet/mew-components' &&
          latestVersion.includes('-beta');
        if (isBehind) {
          if (!isMewComponentBeta) {
            console.error(
              'ERROR: Update ' +
                _name +
                ' from ' +
                ALL_PACKAGES[_name] +
                ' to ' +
                latestVersion +
                '. Released:',
              latestVersionTime
            );
            updatesFound = true;
          }
        }
      }
    })
    .then(looper);
};
looper();
<|endoftext|>


<commit_before>const { merge } = require("webpack-merge")
const common = require("./webpack.common.js")
const BundleAnalyzerPlugin =
  require("webpack-bundle-analyzer").BundleAnalyzerPlugin
const CopyPlugin = require("copy-webpack-plugin")
const SentryWebpackPlugin = require("@sentry/webpack-plugin")

module.exports = merge(common, {
  mode: "production",
  optimization: {
    minimize: false,
  },
  devtool: "source-map",
  module: {
    rules: [
      {
        test: /\.(j|t)sx?$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
        },
      },
    ],
  },
  plugins: [
    new CopyPlugin({
      patterns: [
        { from: "public/*.sf2", to: "[name][ext]" },
        { from: "public/*.svg", to: "[name][ext]" },
        { from: "public/*.png", to: "[name][ext]" },
        { from: "public/*.js", to: "[name][ext]" },
        { from: "public/*.webmanifest", to: "[name][ext]" },
        { from: "public/*.css", to: "[name][ext]" },
      ],
    }),
    new BundleAnalyzerPlugin({
      analyzerMode: "static",
      openAnalyzer: false,
    }),
    new SentryWebpackPlugin({
      authToken: process.env.SENTRY_AUTH_TOKEN,
      org: "codingcafe_jp",
      project: "signal",
      release: process.env.VERCEL_GIT_COMMIT_SHA,
      include: "./dist",
      ignore: [
        "node_modules",
        "webpack.common.js",
        "webpack.dev.js",
        "webpack.prod.js",
      ],
      dryRun: process.env.VERCEL_ENV !== "production",
      debug: true,
    }),
  ],
})
<commit_msg>Treat sentry errors as warnings<commit_after>const { merge } = require("webpack-merge")
const common = require("./webpack.common.js")
const BundleAnalyzerPlugin =
  require("webpack-bundle-analyzer").BundleAnalyzerPlugin
const CopyPlugin = require("copy-webpack-plugin")
const SentryWebpackPlugin = require("@sentry/webpack-plugin")

module.exports = merge(common, {
  mode: "production",
  optimization: {
    minimize: false,
  },
  devtool: "source-map",
  module: {
    rules: [
      {
        test: /\.(j|t)sx?$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
        },
      },
    ],
  },
  plugins: [
    new CopyPlugin({
      patterns: [
        { from: "public/*.sf2", to: "[name][ext]" },
        { from: "public/*.svg", to: "[name][ext]" },
        { from: "public/*.png", to: "[name][ext]" },
        { from: "public/*.js", to: "[name][ext]" },
        { from: "public/*.webmanifest", to: "[name][ext]" },
        { from: "public/*.css", to: "[name][ext]" },
      ],
    }),
    new BundleAnalyzerPlugin({
      analyzerMode: "static",
      openAnalyzer: false,
    }),
    new SentryWebpackPlugin({
      authToken: process.env.SENTRY_AUTH_TOKEN,
      org: "codingcafe_jp",
      project: "signal",
      release: process.env.VERCEL_GIT_COMMIT_SHA,
      include: "./dist",
      ignore: [
        "node_modules",
        "webpack.common.js",
        "webpack.dev.js",
        "webpack.prod.js",
      ],
      dryRun: process.env.VERCEL_ENV !== "production",
      debug: true,
      errorHandler: (err, invokeErr, compilation) => {
        compilation.warnings.push("Sentry CLI Plugin: " + err.message)
      },
    }),
  ],
})
<|endoftext|>


<commit_before>"use strict";

var async = require("async");
var https = require("https");
var fs = require("fs");

/*meta function used by other test user functions*/
function operate(method, accessToken, apiPath, callback) {
    var options = {
		host: 'graph.facebook.com',
		path: apiPath + 'access_token=' + accessToken,
		method: method
	};

	var buffer = '';

	var request = https.request(options, function(result){
		result.setEncoding('utf8');
		result.on('data', function(chunk){
			buffer += chunk;
		});

		result.on('end', function(){
			return callback(null, buffer);
		});
	});

	request.on('error', function(e){
		return callback(e);
	});
	request.end(); //done with the request
}

class FBZombie{

	constructor(appid, access_token){
		if(!appid || !access_token)
            throw new Error("You need specify both appid and access_token!");
		this.appid = appid;
		this.access_token = access_token;
		this.randomnames= [];
		this.full_permission =  "public_profile,user_friends,email,user_about_me,user_actions.books,user_actions.fitness,user_actions.music,user_actions.news,user_actions.video,user_birthday,user_education_history,user_events,user_games_activity,user_hometown,user_likes,user_location,user_managed_groups,user_photos,user_posts,user_relationships,user_relationship_details,user_religion_politics,user_tagged_places,user_videos,user_website,user_work_history,read_custom_friendlists,read_insights,read_audience_network_insights,read_page_mailboxes,manage_pages,publish_pages,publish_actions,rsvp_event,pages_show_list,pages_manage_cta,pages_manage_leads,ads_read,ads_management";

		var parent = this;
        fs.readFileSync('./randomnames.txt').toString().split('\n').forEach(function (line) {
            if( line.trim() )
            {
                var names = line.split(/[ +|\t]/);
                parent.randomnames.push(names[0]+"+"+names[1]);
            }
        });
	}

	/*list all test users on this account*/
	ls(callback){
	    if(!callback) throw new Error("You need specify a callback funtion for function 'ls'!");
		var parent = this;
		operate("GET", parent.access_token, "/"+parent.appid+"/accounts/test-users?limit=2000&", function(err, res){
			if (err) return callback(err);
			var results = JSON.parse(res).data;
			return callback(null, results);
		});
	}

	/*create a test user*/
	createOne(name,  permission, installed, callback){
	    if(!name || !permission || !installed || !callback)
	        throw new Error("You need spceify 4 parameters for function 'createOne'.");

		name = name.split(/ +|\t/).join("+");

		var parent = this;
		if(permission == "all") permission = parent.full_permission;

		var apiPath = "/"+parent.appid+"/accounts/test-users?permissions="+permission+"&installed="+((installed)?"true":"false")+"&name="+name+"&";

		operate("POST", parent.access_token, apiPath, function(err, res){
			if(err) callback(err);
			var u = JSON.parse(res);
			if(u.hasOwnProperty("id")){
				callback(null, u);
			}
			else
			    callback(new Error("Failed to create test user: "+name));
		});
	}
	/*delete a test user*/
	deleteOne(id, callback){
	    if(!id) callback(new Error("You forget to specify ID of the test user to be deleted."));
		var parent = this;
		operate("GET", parent.access_token, "/"+id+"?", function(err, res){
			if (err) return callback(err);
			var user = JSON.parse(res);
			operate("DELETE", parent.access_token, "/"+id+"?", function(err, cb){
				if(err) return callback(err);
				if(user.name){
					callback(null, user);
				}
				else
					callback(new Error("Test user with ID "+id+" does not exist!"));
			});
		});
	}
	/*create "total" test users with meaningful names*/
	/*num_of_installed: how many test users install the APP*/
	/*all users are created with full permissions*/
	create(total, num_of_installed, callback){
	    if(!total || !num_of_installed || !callback)
	        throw new Error("You need spceify 4 parameters for function 'create'.");
	    if(num_of_installed > total){
	        num_of_installed = total;
	        console.log("Warning: you can create at most "+total+" test users.");
	    }
	    var parent = this;
	    var names = parent.randomnames.slice(0, total);

	    var permission = parent.full_permission;
	    var users = [];
		var apiPath = "";
        async.forEachOf(names, function(name, index, cb){
            if(index < num_of_installed)
                apiPath = "/"+parent.appid+"/accounts/test-users?permissions="+permission+"&installed=true&name="+name+"&";
            else
                apiPath = "/"+parent.appid+"/accounts/test-users?permissions="+permission+"&name="+name+"&";

            operate("POST", parent.access_token, apiPath, function(err, res){
                if(err) return cb(err);
                else{
                    var u = JSON.parse(res);
                    if(u.hasOwnProperty("id")){
	        			users.push(u);
		    			return cb(null);
					}
                    else
		    			return cb(new Error("Failed to create test user: "+name));
                }
            });
        }, function(err){
            if(err) return callback(err);
            else return callback(null, users);
        });
	}
	/*make friends between two test users each of which must have id and access_token information*/
	// a test user cannot friend with a real world user.
	connect(userpair, cb){
		var user1 = userpair[0];
		var user2 = userpair[1];
		var connection = "/" + user1.id + "/friends/" + user2.id + "?";
		operate("POST", user1.access_token, connection, function(err1, res1){
			if(err1) return cb(err1);
			var r = JSON.parse(res1);
			if(r.hasOwnProperty("error")) return cb(new Error(r.error.message));
			connection = "/" + user2.id + "/friends/" + user1.id + "?";

			operate("POST", user2.access_token, connection, function(err2, res2){
				if(err2) return cb(err2);
				r = JSON.parse(res2);
			    if(r.hasOwnProperty("error")) return cb(new Error(r.error.message));
				return cb(null, userpair);
			});
		});
	}
	/*make friends for newly created test users, each user information contailns at least id and access_token*/
	// users: input list of friends
	makeFriends(users, circle_num, cb)
	{
	    var parent = this;
	    var center_user = users[0];
	    users = users.slice(1);
		function friendpairs(){
			var i,j,k;
			var pairs = [];
			var circles = Math.ceil(users.length / circle_num);
			for (i = 0; i < circles; i++){
				for(j = circle_num*i; j<Math.min(users.length-1,circle_num*i+circle_num-1); j++){
					for(k = j+1; k < Math.min(circle_num*i+circle_num,users.length); k++){
						pairs.push([users[j], users[k]]);
					}
				}
			}

			for(i=0;i < users.length; i++){
			    pairs.push([center_user, users[i]]);
			}
			return pairs;
		}

		var pairs = friendpairs();
		async.map(pairs, parent.connect, function(err,results)
        {
			if(err) throw err;
            cb(null, center_user, results);//results:[ [friend1, friend2], ... ], of which, friend1 is a user containing all info.
        });
	}
	/*create 100 test users*/
	create100( callback)
	{
	    create(100, 50, callback);
	}
	/*create 200 test users*/
	create200( callback)
	{
	    create(200, 100, callback);
	}
	/*create 500 test users*/
	create500(callback)
	{
	    create(500, 250, callback);
	}
	/*create 1000 test users*/
	create1000( callback)
	{
	    create(1000, 500, callback);
	}
	/*create 2000 test users*/
	create2000(callback)
	{
	    create(2000, 1000, callback);
	}

	delete(num, callback){
	    if (!num) throw new Error("You forgot to specify the number of test users to delete.");
	    var parent = this;
	    /*delete a test user with callback*/
	    function fbdeluser(user,cb)
        {
        	operate("DELETE", parent.access_token, "/"+user.id+"?", function(err, res){
			    if(err) return cb(err);
			    return cb(null, user.id);
		    });
        }

		parent.ls(function(err, users){
			if(err) return callback(err);
			var del_users = [];
			if (users.length <= num){
				async.map(users, fbdeluser, function(err, results){
					if(err) return callback(err);
					return callback(null, results);
				});
			}
			else{
				async.map(users.slice(0,num), fbdeluser, function(err, results){
					if(err) return callback(err);
					return callback(null, results);
				});
			}
		});
	}
}
module.exports = FBZombie;

<commit_msg>change code format<commit_after>"use strict";

var async = require("async");
var https = require("https");
var fs = require("fs");

/*meta function used by other test user functions*/
function operate(method, accessToken, apiPath, callback) {
    var options = {
		host: 'graph.facebook.com',
		path: apiPath + 'access_token=' + accessToken,
		method: method
	};

	var buffer = '';

	var request = https.request(options, function(result){
		result.setEncoding('utf8');
		result.on('data', function(chunk){
			buffer += chunk;
		});

		result.on('end', function(){
			return callback(null, buffer);
		});
	});

	request.on('error', function(e){
		return callback(e);
	});
	request.end(); //done with the request
}

class FBZombie{

	constructor(appid, access_token){
		if(!appid || !access_token)
                    throw new Error("You need specify both appid and access_token!");
		this.appid = appid;
		this.access_token = access_token;
		this.randomnames= [];
		this.full_permission =  "public_profile,user_friends,email,user_about_me,user_actions.books,user_actions.fitness,user_actions.music,user_actions.news,user_actions.video,user_birthday,user_education_history,user_events,user_games_activity,user_hometown,user_likes,user_location,user_managed_groups,user_photos,user_posts,user_relationships,user_relationship_details,user_religion_politics,user_tagged_places,user_videos,user_website,user_work_history,read_custom_friendlists,read_insights,read_audience_network_insights,read_page_mailboxes,manage_pages,publish_pages,publish_actions,rsvp_event,pages_show_list,pages_manage_cta,pages_manage_leads,ads_read,ads_management";

		var parent = this;
        	fs.readFileSync('./randomnames.txt').toString().split('\n').forEach(function (line) {
		        if( line.trim() )
		        {
		            var names = line.split(/[ +|\t]/);
		            parent.randomnames.push(names[0]+"+"+names[1]);
		        }
        	});
	}

	/*list all test users on this account*/
	ls(callback){
	    if(!callback) throw new Error("You need specify a callback funtion for function 'ls'!");
		var parent = this;
		operate("GET", parent.access_token, "/"+parent.appid+"/accounts/test-users?limit=2000&", function(err, res){
			if (err) return callback(err);
			var results = JSON.parse(res).data;
			return callback(null, results);
		});
	}

	/*create a test user*/
	createOne(name,  permission, installed, callback){
	    if(!name || !permission || !installed || !callback)
	        throw new Error("You need spceify 4 parameters for function 'createOne'.");

		name = name.split(/ +|\t/).join("+");

		var parent = this;
		if(permission == "all") permission = parent.full_permission;

		var apiPath = "/"+parent.appid+"/accounts/test-users?permissions="+permission+"&installed="+((installed)?"true":"false")+"&name="+name+"&";

		operate("POST", parent.access_token, apiPath, function(err, res){
			if(err) callback(err);
			var u = JSON.parse(res);
			if(u.hasOwnProperty("id")){
				callback(null, u);
			}
			else
			    callback(new Error("Failed to create test user: "+name));
		});
	}
	/*delete a test user*/
	deleteOne(id, callback){
	    if(!id) callback(new Error("You forget to specify ID of the test user to be deleted."));
		var parent = this;
		operate("GET", parent.access_token, "/"+id+"?", function(err, res){
			if (err) return callback(err);
			var user = JSON.parse(res);
			operate("DELETE", parent.access_token, "/"+id+"?", function(err, cb){
				if(err) return callback(err);
				if(user.name){
					callback(null, user);
				}
				else
					callback(new Error("Test user with ID "+id+" does not exist!"));
			});
		});
	}
	/*create "total" test users with meaningful names*/
	/*num_of_installed: how many test users install the APP*/
	/*all users are created with full permissions*/
	create(total, num_of_installed, callback){
	    if(!total || !num_of_installed || !callback)
	        throw new Error("You need spceify 4 parameters for function 'create'.");
	    if(num_of_installed > total){
	        num_of_installed = total;
	        console.log("Warning: you can create at most "+total+" test users.");
	    }
	    var parent = this;
	    var names = parent.randomnames.slice(0, total);

	    var permission = parent.full_permission;
	    var users = [];
		var apiPath = "";
        async.forEachOf(names, function(name, index, cb){
            if(index < num_of_installed)
                apiPath = "/"+parent.appid+"/accounts/test-users?permissions="+permission+"&installed=true&name="+name+"&";
            else
                apiPath = "/"+parent.appid+"/accounts/test-users?permissions="+permission+"&name="+name+"&";

            operate("POST", parent.access_token, apiPath, function(err, res){
                if(err) return cb(err);
                else{
                    var u = JSON.parse(res);
                    if(u.hasOwnProperty("id")){
	        			users.push(u);
		    			return cb(null);
					}
                    else
		    			return cb(new Error("Failed to create test user: "+name));
                }
            });
        }, function(err){
            if(err) return callback(err);
            else return callback(null, users);
        });
	}
	/*make friends between two test users each of which must have id and access_token information*/
	// a test user cannot friend with a real world user.
	connect(userpair, cb){
		var user1 = userpair[0];
		var user2 = userpair[1];
		var connection = "/" + user1.id + "/friends/" + user2.id + "?";
		operate("POST", user1.access_token, connection, function(err1, res1){
			if(err1) return cb(err1);
			var r = JSON.parse(res1);
			if(r.hasOwnProperty("error")) return cb(new Error(r.error.message));
			connection = "/" + user2.id + "/friends/" + user1.id + "?";

			operate("POST", user2.access_token, connection, function(err2, res2){
				if(err2) return cb(err2);
				r = JSON.parse(res2);
			    if(r.hasOwnProperty("error")) return cb(new Error(r.error.message));
				return cb(null, userpair);
			});
		});
	}
	/*make friends for newly created test users, each user information contailns at least id and access_token*/
	// users: input list of friends
	makeFriends(users, circle_num, cb)
	{
	    var parent = this;
	    var center_user = users[0];
	    users = users.slice(1);
		function friendpairs(){
			var i,j,k;
			var pairs = [];
			var circles = Math.ceil(users.length / circle_num);
			for (i = 0; i < circles; i++){
				for(j = circle_num*i; j<Math.min(users.length-1,circle_num*i+circle_num-1); j++){
					for(k = j+1; k < Math.min(circle_num*i+circle_num,users.length); k++){
						pairs.push([users[j], users[k]]);
					}
				}
			}

			for(i=0;i < users.length; i++){
			    pairs.push([center_user, users[i]]);
			}
			return pairs;
		}

		var pairs = friendpairs();
		async.map(pairs, parent.connect, function(err,results)
        {
			if(err) throw err;
            cb(null, center_user, results);//results:[ [friend1, friend2], ... ], of which, friend1 is a user containing all info.
        });
	}
	/*create 100 test users*/
	create100( callback)
	{
	    create(100, 50, callback);
	}
	/*create 200 test users*/
	create200( callback)
	{
	    create(200, 100, callback);
	}
	/*create 500 test users*/
	create500(callback)
	{
	    create(500, 250, callback);
	}
	/*create 1000 test users*/
	create1000( callback)
	{
	    create(1000, 500, callback);
	}
	/*create 2000 test users*/
	create2000(callback)
	{
	    create(2000, 1000, callback);
	}

	delete(num, callback){
	    if (!num) throw new Error("You forgot to specify the number of test users to delete.");
	    var parent = this;
	    /*delete a test user with callback*/
	    function fbdeluser(user,cb)
        {
        	operate("DELETE", parent.access_token, "/"+user.id+"?", function(err, res){
			    if(err) return cb(err);
			    return cb(null, user.id);
		    });
        }

		parent.ls(function(err, users){
			if(err) return callback(err);
			var del_users = [];
			if (users.length <= num){
				async.map(users, fbdeluser, function(err, results){
					if(err) return callback(err);
					return callback(null, results);
				});
			}
			else{
				async.map(users.slice(0,num), fbdeluser, function(err, results){
					if(err) return callback(err);
					return callback(null, results);
				});
			}
		});
	}
}
module.exports = FBZombie;

<|endoftext|>


<commit_before>(function() {
  linkTarget = function(el) {
    var title = el.attr('title');
    var target = el.attr('href');

    if(target.match(/mailto:/)) {
      return target.replace(/mailto:/, '');
    }
    if(title) return title;
    if(el.text()) return el.text();

    return target;
  };

  var track = function(prefix, category, selector, label) {
    var el = $(selector);
    var event = 'click';

    if(!el.length && console) return console.error('Needs an element to track');

    if(!label) label = linkTarget(el);

    if($.isFunction(label)) {
      label = label.call(this, el);
    }

    if(el.is('form')) event = 'submit';

    el.on(event, function() {
      _gaq.push(['_trackEvent', prefix + ' - ' + category, label]);
    });
  };

  // Expose track globally or using Node.js module system if possible.
  if(module) {
    module.exports = track;
  } else {
    window.track = track;
  }
})();
<commit_msg>Timeout before links follow their targets<commit_after>(function() {
  linkTarget = function(el) {
    var title = el.attr('title');
    var target = el.attr('href');

    if(target.match(/mailto:/)) {
      return target.replace(/mailto:/, '');
    }
    if(title) return title;
    if(el.text()) return el.text();

    return target;
  };

  var track = function(prefix, category, selector, label) {
    var el = $(selector);
    var event = 'click';

    if(!el.length && console) return console.error('Needs an element to track');

    if(!label) label = linkTarget(el);

    if($.isFunction(label)) {
      label = label.call(this, el);
    }

    if(el.is('form')) event = 'submit';

    el.on(event, function() {
      e.preventDefault();
      _gaq.push(['_trackEvent', prefix + ' - ' + category, label]);
      window.setTimeout(function () {
          window.location.href = el.attr('href');
      }, 100);
    });
  };

  // Expose track globally or using Node.js module system if possible.
  if(module) {
    module.exports = track;
  } else {
    window.track = track;
  }
})();
<|endoftext|>