function (aziElevR) {

    var x,y,z;
    var xyz = new Array(aziElevR.length);

    for (var i=0; i<aziElevR.length; i++) {
        x = Math.cos(aziElevR[i][0])*Math.cos(aziElevR[i][1]);
        y = Math.sin(aziElevR[i][0])*Math.cos(aziElevR[i][1]);
        z = Math.sin(aziElevR[i][1]);
        if (aziElevR[0].length==2) xyz[i] = [x,y,z];
        else if (aziElevR[0].length==3) xyz[i] = [aziElevR[i][2]*x,aziElevR[i][2]*y,aziElevR[i][2]*z];
    }
    return xyz;
}

function ( aziElevR ) { var x , y , z ; var xyz = new Array ( aziElevR . length ) ; for ( var i = 0 ; i < aziElevR . length ; i ++ ) { x = Math . cos ( aziElevR [ i ] [ 0 ] ) * Math . cos ( aziElevR [ i ] [ 1 ] ) ; y = Math . sin ( aziElevR [ i ] [ 0 ] ) * Math . cos ( aziElevR [ i ] [ 1 ] ) ; z = Math . sin ( aziElevR [ i ] [ 1 ] ) ; if ( aziElevR [ 0 ] . length == 2 ) xyz [ i ] = [ x , y , z ] ; else if ( aziElevR [ 0 ] . length == 3 ) xyz [ i ] = [ aziElevR [ i ] [ 2 ] * x , aziElevR [ i ] [ 2 ] * y , aziElevR [ i ] [ 2 ] * z ] ; } return xyz ; }

convertSph2Cart converts arrays of spherical coordinates to cartesian


function (N, data) {

    var azi = new Array(data.length);
    var elev = new Array(data.length);

    for (var i=0; i<data.length; i++) {
        azi[i] = data[i][0];
        elev[i] = data[i][1];
    }

    var factorials = new Array(2*N+1);
    var Ndirs = azi.length;
    var Nsh = (N+1)*(N+1);
    var leg_n_minus1 = 0;
    var leg_n_minus2 = 0;
    var leg_n;
    var sinel = numeric.sin(elev);
    var index_n = 0;
    var Y_N = new Array(Nsh);
    var Nn0, Nnm;
    var cosmazi, sinmazi;

    // precompute factorials
    for (var i = 0; i < 2*N+1; i++) factorials[i] = factorial(i);

    for (var n = 0; n<N+1; n++) {
        if (n==0) {
            var temp0 = new Array(azi.length);
            temp0.fill(1);
            Y_N[n] = temp0;
            index_n = 1;
        }
        else {
            leg_n = recurseLegendrePoly(n, sinel, leg_n_minus1, leg_n_minus2);
            Nn0 = Math.sqrt(2*n+1);
            for (var m = 0; m<n+1; m++) {
                if (m==0) Y_N[index_n+n] = numeric.mul(Nn0,leg_n[m]);
                else {
                    Nnm = Nn0*Math.sqrt( 2 * factorials[n-m]/factorials[n+m] );
                    cosmazi = numeric.cos(numeric.mul(m,azi));
                    sinmazi = numeric.sin(numeric.mul(m,azi));
                    Y_N[index_n+n-m] = numeric.mul(Nnm, numeric.mul(leg_n[m], sinmazi));
                    Y_N[index_n+n+m] = numeric.mul(Nnm, numeric.mul(leg_n[m], cosmazi));
                }
            }
            index_n = index_n+2*n+1;
        }
        leg_n_minus2 = leg_n_minus1;
        leg_n_minus1 = leg_n;
    }

    return Y_N;
}

function
(
N
,
data
)
{
var
azi
=
new
Array
(
data
.
length
)
;
var
elev
=
new
Array
(
data
.
length
)
;
for
(
var
i
=
0
;
i
<
data
.
length
;
i
++
)
{
azi
[
i
]
=
data
[
i
]
[
0
]
;
elev
[
i
]
=
data
[
i
]
[
1
]
;
}
var
factorials
=
new
Array
(
2
*
N
+
1
)
;
var
Ndirs
=
azi
.
length
;
var
Nsh
=
(
N
+
1
)
*
(
N
+
1
)
;
var
leg_n_minus1
=
0
;
var
leg_n_minus2
=
0
;
var
leg_n
;
var
sinel
=
numeric
.
sin
(
elev
)
;
var
index_n
=
0
;
var
Y_N
=
new
Array
(
Nsh
)
;
var
Nn0
,
Nnm
;
var
cosmazi
,
sinmazi
;
// precompute factorials
for
(
var
i
=
0
;
i
<
2
*
N
+
1
;
i
++
)
factorials
[
i
]
=
factorial
(
i
)
;
for
(
var
n
=
0
;
n
<
N
+
1
;
n
++
)
{
if
(
n
==
0
)
{
var
temp0
=
new
Array
(
azi
.
length
)
;
temp0
.
fill
(
1
)
;
Y_N
[
n
]
=
temp0
;
index_n
=
1
;
}
else
{
leg_n
=
recurseLegendrePoly
(
n
,
sinel
,
leg_n_minus1
,
leg_n_minus2
)
;
Nn0
=
Math
.
sqrt
(
2
*
n
+
1
)
;
for
(
var
m
=
0
;
m
<
n
+
1
;
m
++
)
{
if
(
m
==
0
)
Y_N
[
index_n
+
n
]
=
numeric
.
mul
(
Nn0
,
leg_n
[
m
]
)
;
else
{
Nnm
=
Nn0
*
Math
.
sqrt
(
2
*
factorials
[
n
m
]
/
factorials
[
n
+
m
]
)
;
cosmazi
=
numeric
.
cos
(
numeric
.
mul
(
m
,
azi
)
)
;
sinmazi
=
numeric
.
sin
(
numeric
.
mul
(
m
,
azi
)
)
;
Y_N
[
index_n
+
n
m
]
=
numeric
.
mul
(
Nnm
,
numeric
.
mul
(
leg_n
[
m
]
,
sinmazi
)
)
;
Y_N
[
index_n
+
n
+
m
]
=
numeric
.
mul
(
Nnm
,
numeric
.
mul
(
leg_n
[
m
]
,
cosmazi
)
)
;
}
}
index_n
=
index_n
+
2
*
n
+
1
;
}
leg_n_minus2
=
leg_n_minus1
;
leg_n_minus1
=
leg_n
;
}
return
Y_N
;
}

computeRealSH computes real spherical harmonics up to order N


function (n, x, Pnm_minus1, Pnm_minus2) {

    var Pnm = new Array(n+1);
    switch(n) {
        case 1:
            var x2 = numeric.mul(x,x);
            var P10 = x;
            var P11 = numeric.sqrt(numeric.sub(1,x2));
            Pnm[0] = P10;
            Pnm[1] = P11;
            break;
        case 2:
            var x2 = numeric.mul(x,x);
            var P20 = numeric.mul(3,x2);
            P20 = numeric.sub(P20,1);
            P20 = numeric.div(P20,2);
            var P21 = numeric.sub(1,x2);
            P21 = numeric.sqrt(P21);
            P21 = numeric.mul(3,P21);
            P21 = numeric.mul(P21,x);
            var P22 = numeric.sub(1,x2);
            P22 = numeric.mul(3,P22);
            Pnm[0] = P20;
            Pnm[1] = P21;
            Pnm[2] = P22;
            break;
        default:
            var x2 = numeric.mul(x,x);
            var one_min_x2 = numeric.sub(1,x2);
            // last term m=n
            var k = 2*n-1;
            var dfact_k = 1;
            if ((k % 2) == 0) {
                for (var kk=1; kk<k/2+1; kk++) dfact_k = dfact_k*2*kk;
            }
            else {
                for (var kk=1; kk<(k+1)/2+1; kk++) dfact_k = dfact_k*(2*kk-1);
            }
            Pnm[n] = numeric.mul(dfact_k, numeric.pow(one_min_x2, n/2));
            // before last term
            Pnm[n-1] = numeric.mul(2*n-1, numeric.mul(x, Pnm_minus1[n-1])); // P_{n(n-1)} = (2*n-1)*x*P_{(n-1)(n-1)}
            // three term recursence for the rest
            for (var m=0; m<n-1; m++) {
                var temp1 = numeric.mul( 2*n-1, numeric.mul(x, Pnm_minus1[m]) );
                var temp2 = numeric.mul( n+m-1, Pnm_minus2[m] );
                Pnm[m] = numeric.div( numeric.sub(temp1, temp2), n-m); // P_l = ( (2l-1)xP_(l-1) - (l+m-1)P_(l-2) )/(l-m)
            }
    }
    return Pnm;
}

recurseLegendrePoly computes associated Legendre functions recursively


function (A) {
    var z = numeric.svd(A), foo = z.S[0];
    var U = z.U, S = z.S, V = z.V;
    var m = A.length, n = A[0].length, tol = Math.max(m,n)*numeric.epsilon*foo,M = S.length;
    var Sinv = new Array(M);
    for(var i=M-1;i!==-1;i--) { if(S[i]>tol) Sinv[i] = 1/S[i]; else Sinv[i] = 0; }
    return numeric.dot(numeric.dot(V,numeric.diag(Sinv)),numeric.transpose(U))
}

function ( A ) { var z = numeric . svd ( A ) , foo = z . S [ 0 ] ; var U = z . U , S = z . S , V = z . V ; var m = A . length , n = A [ 0 ] . length , tol = Math . max ( m , n ) * numeric . epsilon * foo , M = S . length ; var Sinv = new Array ( M ) ; for ( var i = M - 1 ; i !== - 1 ; i -- ) { if ( S [ i ] > tol ) Sinv [ i ] = 1 / S [ i ] ; else Sinv [ i ] = 0 ; } return numeric . dot ( numeric . dot ( V , numeric . diag ( Sinv ) ) , numeric . transpose ( U ) ) }

pinv_svd computes the pseudo-inverse using SVD

pinv_svd computes the pseudo - inverse using SVD


function (A) {
    var AT = numeric.transpose(A);
    return numeric.dot(numeric.inv(numeric.dot(AT,A)),AT);
}

function ( A ) { var AT = numeric . transpose ( A ) ; return numeric . dot ( numeric . inv ( numeric . dot ( AT , A ) ) , AT ) ; }

pinv_direct computes the left pseudo-inverse

pinv_direct computes the left pseudo - inverse


function (yaw, pitch, roll) {

    var Rx, Ry, Rz;
    if (roll == 0) Rx = [[1,0,0],[0,1,0],[0,0,1]];
    else Rx = [[1, 0, 0], [0, Math.cos(roll), Math.sin(roll)], [0, -Math.sin(roll), Math.cos(roll)]];
    if (pitch == 0) Ry = [[1,0,0],[0,1,0],[0,0,1]];
    else Ry = [[Math.cos(pitch), 0, -Math.sin(pitch)], [0, 1, 0], [Math.sin(pitch), 0, Math.cos(pitch)]];
    if (yaw == 0) Rz = [[1,0,0],[0,1,0],[0,0,1]];
    else Rz = [[Math.cos(yaw), Math.sin(yaw), 0], [-Math.sin(yaw), Math.cos(yaw), 0], [0, 0, 1]];

    var R = numeric.dotMMsmall(Ry,Rz);
    R = numeric.dotMMsmall(Rx,R);
    return R;
}

function ( yaw , pitch , roll ) { var Rx , Ry , Rz ; if ( roll == 0 ) Rx = [ [ 1 , 0 , 0 ] , [ 0 , 1 , 0 ] , [ 0 , 0 , 1 ] ] ; else Rx = [ [ 1 , 0 , 0 ] , [ 0 , Math . cos ( roll ) , Math . sin ( roll ) ] , [ 0 , - Math . sin ( roll ) , Math . cos ( roll ) ] ] ; if ( pitch == 0 ) Ry = [ [ 1 , 0 , 0 ] , [ 0 , 1 , 0 ] , [ 0 , 0 , 1 ] ] ; else Ry = [ [ Math . cos ( pitch ) , 0 , - Math . sin ( pitch ) ] , [ 0 , 1 , 0 ] , [ Math . sin ( pitch ) , 0 , Math . cos ( pitch ) ] ] ; if ( yaw == 0 ) Rz = [ [ 1 , 0 , 0 ] , [ 0 , 1 , 0 ] , [ 0 , 0 , 1 ] ] ; else Rz = [ [ Math . cos ( yaw ) , Math . sin ( yaw ) , 0 ] , [ - Math . sin ( yaw ) , Math . cos ( yaw ) , 0 ] , [ 0 , 0 , 1 ] ] ; var R = numeric . dotMMsmall ( Ry , Rz ) ; R = numeric . dotMMsmall ( Rx , R ) ; return R ; }

yawPitchRoll2Rzyx computes the rotation matrix from ZY'X'' rotation angles

yawPitchRoll2Rzyx computes the rotation matrix from ZY X rotation angles


function siftdown(compare, a, i, j, k) {

	var current = k - i;

	while (true) {

		// address of the first child in a zero-based
		// binary heap

		var firstchild = 2 * current + 1;

		// if current node has no children
		// then we are done

		if (firstchild >= j - i) break;

		// if current value is smaller than its smallest
		// child then we are done

		var candidate = (0, _nextchild2.default)(compare, a, i + firstchild, j);

		if (compare(a[i + current], a[candidate]) <= 0) break;

		// otherwise
		// swap with smallest child

		var tmp = a[i + current];
		a[i + current] = a[candidate];
		a[candidate] = tmp;

		current = candidate - i;
	}

	return i + current;
}

Sifts down a node.

@param {function} compare the comparison function
@param {array} a the array where the heap is stored
@param {int} i is the root element
@param {int} j - 1 is the last leaf
@param {int} k is the target node


function nextchild(compare, a, i, j) {

  if (j - i < 2) return i;

  if (compare(a[i], a[i + 1]) <= 0) return i;

  return i + 1;
}

function nextchild ( compare , a , i , j ) { if ( j - i < 2 ) return i ; if ( compare ( a [ i ] , a [ i + 1 ] ) <= 0 ) return i ; return i + 1 ; }

Computes which child is the smallest according
to a comparison function.

Hypothesis : i < j i.e. there should be at least one child

@param {function} compare the comparison function
@param {array} a the array where the heap is stored
@param {int} i is the first child
@param {int} j - 1 is the last leaf

Computes which child is the smallest according to a comparison function .


function siftup(compare, a, i, j, k) {

	var current = k - i;

	// while we are not the root

	while (current !== 0) {

		// address of the parent in a zero-based
		// d-ary heap

		var parent = i + (current - 1 >>> 1);

		// if current value is greater than its parent
		// then we are done

		if (compare(a[i + current], a[parent]) >= 0) return i + current;

		// otherwise
		// swap with parent

		var tmp = a[i + current];
		a[i + current] = a[parent];
		a[parent] = tmp;

		current = parent - i;
	}

	return i + current;
}

Sifts up a node.

@param {function} compare the comparison function
@param {array} a the array where the heap is stored
@param {int} i is the root element
@param {int} j - 1 is the last leaf
@param {int} k is the target node


function exec(command, options) {
    return new PromiseWithEvents_1.PromiseWithEvents(function (resolve, reject, eventEmitter) {
        var childProcess = cp.exec(command, options, function (err, stdout, stderr) {
            if (err) {
                reject(err);
            }
            else {
                resolve({
                    stdout: stdout.toString(),
                    stderr: stderr.toString()
                });
            }
        });
        process.nextTick(function () { return eventEmitter.emit('process', childProcess); });
    });
}

function exec ( command , options ) { return new PromiseWithEvents_1 . PromiseWithEvents ( function ( resolve , reject , eventEmitter ) { var childProcess = cp . exec ( command , options , function ( err , stdout , stderr ) { if ( err ) { reject ( err ) ; } else { resolve ( { stdout : stdout . toString ( ) , stderr : stderr . toString ( ) } ) ; } } ) ; process . nextTick ( function ( ) { return eventEmitter . emit ( 'process' , childProcess ) ; } ) ; } ) ; }

Runs a command in a shell and buffers the output.
@param command {string} - The command
@param options {ExecOptions} - Options
@returns {PromiseWithEvents<ExecResult>}
@see {@link https://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback}

Runs a command in a shell and buffers the output .


function field(query) {
    var queryDefinition;
    if (query instanceof Function) {
        queryDefinition = query();
    }
    else {
        queryDefinition = query;
    }
    var customField = queryDefinition.select;
    customField = customField.addSubQuery(queryDefinition);
    // Field query cannot be joined to any other query so don't have set the positional fields
    return customField;
}

Sub-queries in select clause
@param query
@returns {IQF}


function ManyToOne(elements) {
    return function (targetObject, propertyKey) {
        var entityMetadata = targetObject;
        if (!entityMetadata.manyToOneMap) {
            entityMetadata.manyToOneMap = {};
        }
        entityMetadata.manyToOneMap[propertyKey] = elements;
    };
}

function ManyToOne ( elements ) { return function ( targetObject , propertyKey ) { var entityMetadata = targetObject ; if ( ! entityMetadata . manyToOneMap ) { entityMetadata . manyToOneMap = { } ; } entityMetadata . manyToOneMap [ propertyKey ] = elements ; } ; }

Specifies a single-valued association to another entity class that has many-to-one multiplicity.

http://docs.oracle.com/javaee/7/api/javax/persistence/ManyToOne.html

@param elements
@returns {function(any, string)}
@constructor

Specifies a single - valued association to another entity class that has many - to - one multiplicity .


function OneToMany(elements) {
    return function (targetObject, propertyKey) {
        var entityMetadata = targetObject;
        if (!entityMetadata.oneToManyMap) {
            entityMetadata.oneToManyMap = {};
        }
        entityMetadata.oneToManyMap[propertyKey] = elements;
    };
}

function OneToMany ( elements ) { return function ( targetObject , propertyKey ) { var entityMetadata = targetObject ; if ( ! entityMetadata . oneToManyMap ) { entityMetadata . oneToManyMap = { } ; } entityMetadata . oneToManyMap [ propertyKey ] = elements ; } ; }

Specifies a many-valued association with one-to-many multiplicity.

http://docs.oracle.com/javaee/7/api/javax/persistence/OneToMany.html

@param elements
@returns {function(any, string)}
@constructor

Specifies a many - valued association with one - to - many multiplicity .


function Entity(entityConfiguration) {
    return function (constructor) {
        var entityMetadata = constructor;
        if (entityMetadata.entity) {
            throw "Cannot set @Table, it is already set to '" + JSON.stringify(entityMetadata.entity) + "'";
        }
        // FIXME: verify this works! (that it's not constructor.name)
        entityMetadata.name = constructor.prototype.name;
        if (!entityConfiguration) {
            entityConfiguration = true;
        }
        entityMetadata.entity = entityConfiguration;
    };
}

Annotates entities.

@param entityConfiguration
@returns {function(Function)}
@constructor


function Table(tableConfiguration) {
    return function (constructor) {
        var entityMetadata = constructor;
        if (entityMetadata.table) {
            throw "Cannot set @Table, it is already set to '" + JSON.stringify(entityMetadata.table) + "'";
        }
        entityMetadata.table = tableConfiguration;
    };
}

Annotates tables.

@param tableConfiguration
@returns {function(Function)}
@constructor


function observeResize (el, cb) {
  assert.ok(isDom(el), 'observe-resize: el should be a valid DOM element')
  assert.equal(typeof cb, 'function', 'observe-resize: cb should be type function')

  // Make this function a noop in non-browser environments
  if (typeof window !== 'object') return

  var called = false
  var frame = document.createElement('iframe')
  frame.setAttribute('class', '__observe-resize__')
  el.appendChild(frame)

  assert.ok(frame.contentWindow, 'observe-resize: no contentWindow detected - cannot start observing')
  frame.contentWindow.onresize = handleResize

  return function stopObserving () {
    if (frame.parentNode) frame.parentNode.removeChild(frame)
  }

  function handleResize () {
    if (called) return
    called = true
    window.requestAnimationFrame(function () {
      called = false
      cb(el)
    })
  }
}

Trigger a callback when an element is resized


function getTasks() {
	const tasks = {},
	      tmp = {},
	      mods = {},
	      exec = Object.assign({}, execStack);

	let total = 0,
	    count = 0;

	(0, _core2.default)(exec).forEach((el, key) => {
		tmp[key] = (0, _core2.default)(el).map((el, key) => key);
		mods[key] = 0;
		count++;
	}, el => el.length);

	/* eslint-disable no-loop-func */

	const sort = (a, b) => b.value - a.value;

	while (total <= _thread.MAX_PRIORITY) {
		const rands = [];

		(0, _core2.default)(exec).forEach((el, key) => {
			rands.push({
				key,
				value: _thread.PRIORITY[key]
			});
		}, el => el.length);

		rands.sort(sort);

		let pos = rands.length - 1,
		    max = 0;

		(0, _core2.default)(rands).forEach((el, i) => {
			const interval = intervals[pos];

			if (interval[1] > max) {
				max = interval[1];
			}

			rands[i].value = interval;
			pos--;
		});

		const rand = (0, _math.getRandomInt)(0, max);

		(0, _core2.default)(rands).forEach(({ key, value }) => {
			const arr = tmp[key];

			if (rand >= value[0] && rand <= value[1]) {
				tasks[key] = tasks[key] || [];
				let pos = lastPos[key];

				if (arr[pos] == null) {
					lastPos[key] = pos = 0;
					mods[key] = 0;
				}

				const point = exec[key][arr[pos]];

				if (point && !point.pause) {
					mods[key]++;
					tasks[key].push(arr[pos]);
					total += _thread.PRIORITY[key];
				}

				arr.splice(pos, 1);
				if (!arr.length) {
					delete exec[key];
					count--;
				}

				return false;
			}
		});

		if (!count) {
			break;
		}
	}

	/* eslint-enable no-loop-func */

	(0, _core2.default)(mods).forEach((el, key) => {
		lastPos[key] += el;
	});

	return tasks;
}

function
getTasks
(
)
{
const
tasks
=
{
}
,
tmp
=
{
}
,
mods
=
{
}
,
exec
=
Object
.
assign
(
{
}
,
execStack
)
;
let
total
=
0
,
count
=
0
;
(
0
,
_core2
.
default
)
(
exec
)
.
forEach
(
(
el
,
key
)
=>
{
tmp
[
key
]
=
(
0
,
_core2
.
default
)
(
el
)
.
map
(
(
el
,
key
)
=>
key
)
;
mods
[
key
]
=
0
;
count
++
;
}
,
el
=>
el
.
length
)
;
/* eslint-disable no-loop-func */
const
sort
=
(
a
,
b
)
=>
b
.
value
a
.
value
;
while
(
total
<=
_thread
.
MAX_PRIORITY
)
{
const
rands
=
[
]
;
(
0
,
_core2
.
default
)
(
exec
)
.
forEach
(
(
el
,
key
)
=>
{
rands
.
push
(
{
key
,
value
:
_thread
.
PRIORITY
[
key
]
}
)
;
}
,
el
=>
el
.
length
)
;
rands
.
sort
(
sort
)
;
let
pos
=
rands
.
length
1
,
max
=
0
;
(
0
,
_core2
.
default
)
(
rands
)
.
forEach
(
(
el
,
i
)
=>
{
const
interval
=
intervals
[
pos
]
;
if
(
interval
[
1
]
>
max
)
{
max
=
interval
[
1
]
;
}
rands
[
i
]
.
value
=
interval
;
pos
;
}
)
;
const
rand
=
(
0
,
_math
.
getRandomInt
)
(
0
,
max
)
;
(
0
,
_core2
.
default
)
(
rands
)
.
forEach
(
(
{
key
,
value
}
)
=>
{
const
arr
=
tmp
[
key
]
;
if
(
rand
>=
value
[
0
]
&&
rand
<=
value
[
1
]
)
{
tasks
[
key
]
=
tasks
[
key
]
||
[
]
;
let
pos
=
lastPos
[
key
]
;
if
(
arr
[
pos
]
==
)
{
lastPos
[
key
]
=
pos
=
0
;
mods
[
key
]
=
0
;
}
const
point
=
exec
[
key
]
[
arr
[
pos
]
]
;
if
(
point
&&
!
point
.
pause
)
{
mods
[
key
]
++
;
tasks
[
key
]
.
push
(
arr
[
pos
]
)
;
total
+=
_thread
.
PRIORITY
[
key
]
;
}
arr
.
splice
(
pos
,
1
)
;
if
(
!
arr
.
length
)
{
delete
exec
[
key
]
;
count
;
}
return
false
;
}
}
)
;
if
(
!
count
)
{
break
;
}
}
/* eslint-enable no-loop-func */
(
0
,
_core2
.
default
)
(
mods
)
.
forEach
(
(
el
,
key
)
=>
{
lastPos
[
key
]
+=
el
;
}
)
;
return
tasks
;
}

Returns a working plan for the current iteration of the event loop
@return {!Object}


function checkTile(tile) {
        // No tile, ignore
        if (!tile) return false;
        // If an array of indices was provided, tile's index must be in that array
        if (tileIndices && tileIndices.includes(tile.index)) return true;
        // If a tile property was provided, the tile must have a truthy value for that property
        if (tileProperty && tile.properties[tileProperty]) return true;
        // If we only care about colliding tiles, make sure the tile collides
        if (checkCollide && tile.collides) return true;
        // Tile didn't pass any checks, ignore
        return false;
    }

Check to make sure the tile passes the checks, i.e. it is allowed to be in a cluster

Check to make sure the tile passes the checks i . e . it is allowed to be in a cluster


function returnCache(cache) {
	let text = '';

	for (const key in cache) {
		if (!cache.hasOwnProperty(key)) {
			continue;
		}

		text += cache[key];
	}

	return text;
}

function returnCache ( cache ) { let text = '' ; for ( const key in cache ) { if ( ! cache . hasOwnProperty ( key ) ) { continue ; } text += cache [ key ] ; } return text ; }

Returns a cache string by an object

@param {?} cache - cache object
@return {string}


function __encode(raw, key) {

  var len = _.size(key);
  var cc = len; // key switch counter
  return new Buffer(_.map(raw, function(num, index) {

    if (cc-- > 0) {
      return (num + key.shift()) % 256;
    }
    return (num + raw[index - len]) % 256;
  }));
}

function
__encode
(
raw
,
key
)
{
var
len
=
_
.
size
(
key
)
;
var
cc
=
len
;
// key switch counter
return
new
Buffer
(
_
.
map
(
raw
,
function
(
num
,
index
)
{
if
(
cc
>
0
)
{
return
(
num
+
key
.
shift
(
)
)
%
256
;
}
return
(
num
+
raw
[
index
len
]
)
%
256
;
}
)
)
;
}

body cipher encode

@function __encode
@param {Buffer} raw - data
@param {Array} key - user key
@return {Buffer}


function __decode(raw, key) {

  var res = []; // output buffer
  var len = _.size(key);
  var cc = len; // key switch counter
  for (var i = 0, ii = _.size(raw); i < ii; ++i) {
    if (cc-- > 0) {
      res[i] = (raw[i] - key.shift()) % 256;
    } else {
      res[i] = (raw[i] - res[i - len]) % 256;
    }
  }
  return new Buffer(res);
}

function
__decode
(
raw
,
key
)
{
var
res
=
[
]
;
// output buffer
var
len
=
_
.
size
(
key
)
;
var
cc
=
len
;
// key switch counter
for
(
var
i
=
0
,
ii
=
_
.
size
(
raw
)
;
i
<
ii
;
++
i
)
{
if
(
cc
>
0
)
{
res
[
i
]
=
(
raw
[
i
]
key
.
shift
(
)
)
%
256
;
}
else
{
res
[
i
]
=
(
raw
[
i
]
res
[
i
len
]
)
%
256
;
}
}
return
new
Buffer
(
res
)
;
}

body cipher decode

@function __decode
@param {Buffer} raw - data
@param {Array} key - user key
@return {Buffer}


function process (rawXLSX, options) {
  // if no options are passed, set an empty Object as default
  options = options || {}

  // check for errors in the options, and clean up if needed
  options = validateOptions(options)

  // if no processor is set, assume `keyvalue`
  const defaultProcessor = options.processor || 'keyvalue'

  // if no overrides were set, assume there are none
  const overrides = options.overrides || {}

  // if the XLSX file came over as a Buffer, read it differently
  const workbook = rawXLSX instanceof Buffer ? XLSX.read(rawXLSX, {type: 'buffer'}) : XLSX.readFile(rawXLSX)

  // get the names of all the sheets in an Array
  let sheets = workbook.SheetNames

  if (options.includeSheets) {
    sheets = sheets.filter((s) => options.includeSheets.indexOf(s) !== -1)
  }

  if (options.excludeSheets) {
    sheets = sheets.filter((s) => options.excludeSheets.indexOf(s) === -1)
  }

  // the eventual payload returned to the callback
  let payload = {}

  // for each sheet in the workbook process its contents
  sheets.forEach(function (sheet) {
    // determine the appropriate processor, using the override if it exists
    const processor = overrides.hasOwnProperty(sheet) ? overrides[sheet] : defaultProcessor

    // pass pass the sheet on to the process script with the correct processor
    payload[sheet] = getProcessor(processor)(workbook.Sheets[sheet])
  })

  // return the processed data
  return payload
}

Accepts a raw XLSX file and options that determine how `copytext` should
process it.

@param  {String|Buffer} rawXLSX A Buffer of, or path to, an XLSX file
@param  {Object} [options]
@param  {String} [options.processor='keyvalue'] The processor used on all sheets without overrides
@param  {String[]|String} [options.includeSheets=undefined] Sheets to include
@param  {String[]|String} [options.excludeSheets=undefined] Sheets to exclude
@param  {Object} [options.overrides=undefined] Key value pairs of the sheet name and processor that should be used
@return {Object}

Accepts a raw XLSX file and options that determine how copytext should process it .


function validateOptions (options) {
  // doesn't make sense to pass both, so prevent it
  if (options.includeSheets && options.excludeSheets) {
    throw new Error("Do not pass both `includeSheets` and `excludeSheets`. It's confusing.")
  }

  // if `includeSheets` exists and isn't an Array, make it so
  if (options.includeSheets) {
    if (!Array.isArray(options.includeSheets)) options.includeSheets = [options.includeSheets]
  }

  // if `excludeSheets` exists and isn't an Array, make it so
  if (options.excludeSheets) {
    if (!Array.isArray(options.excludeSheets)) options.excludeSheets = [options.excludeSheets]
  }

  // if `excludeSheets` is set and one of them show up in `overrides`, it won't
  // break anything, but the user should be aware it won't work
  if (options.excludeSheets && options.overrides) {
    const overrides = Object.keys(options.overrides)

    overrides.forEach((override) => {
      if (options.excludeSheets.indexOf(override) !== -1) {
        console.warn(`\`${override}\` has an override, but it is also being excluded in \`excludeSheets\`.`)
      }
    })
  }

  return options
}

Validates and normalizes the options passed to `process`.

@private
@param  {Object} options
@return {Object}

Validates and normalizes the options passed to process .


function isLikeArray(obj) {
	const res = isArray(obj) || obj &&

	// The hack for PhantomJS,
	// because it has strange bug for HTMLCollection and NodeList:
	// typeof 'function' && instanceof Function = false
	isObjectInstance(obj) && !isFuncRgxp.test(toString.call(obj)) && (
	// If the object is like an array
	obj.length > 0 && 0 in obj || obj.length === 0);

	return Boolean(res);
}

Returns true if the specified value is an array or like an array

@param {?} obj - source value
@return {boolean}


function isIterator(obj) {
	return Boolean(obj && (typeof Symbol === 'function' ? obj[Symbol.iterator] : isFunction(obj['@@iterator'])));
}

function isIterator ( obj ) { return Boolean ( obj && ( typeof Symbol === 'function' ? obj [ Symbol . iterator ] : isFunction ( obj [ '@@iterator' ] ) ) ) ; }

Returns true if the specified value is an iterator

@param {?} obj - source value
@return {boolean}


function isStream(obj) {
	return Boolean(obj && isFunction(obj.addListener) && isFunction(obj.removeListener) && isFunction(obj.destroy) && (isFunction(obj.write) && isFunction(obj.end) || isFunction(obj.pipe) && isFunction(obj.read) && isFunction(obj.pause) && isFunction(obj.resume)));
}

function isStream ( obj ) { return Boolean ( obj && isFunction ( obj . addListener ) && isFunction ( obj . removeListener ) && isFunction ( obj . destroy ) && ( isFunction ( obj . write ) && isFunction ( obj . end ) || isFunction ( obj . pipe ) && isFunction ( obj . read ) && isFunction ( obj . pause ) && isFunction ( obj . resume ) ) ) ; }

Returns true if the specified value is a stream

@param {?} obj - source value
@return {boolean}


function getType(obj, opt_use) {
	if (!obj) {
		return null;
	}

	switch (opt_use) {
		case 'for':
			return 'array';

		case 'for in':
			return 'object';

		case 'for of':
			return 'iterator';

		case 'async for of':
			return 'asyncIterator';

		default:
			if (obj === Empty) {
				return null;
			}

			if (isMap(obj)) {
				return 'map';
			}

			if (isWeakMap(obj)) {
				return 'weakMap';
			}

			if (isSet(obj)) {
				return 'set';
			}

			if (isWeakSet(obj)) {
				return 'weakSet';
			}

			if (isGenerator(obj)) {
				return 'generator';
			}

			if (isLikeArray(obj)) {
				return 'array';
			}

			if (isIterator(obj)) {
				return 'iterator';
			}

			if (isIDBRequest(obj)) {
				return 'idbRequest';
			}

			if (isStream(obj)) {
				return 'stream';
			}
	}

	return 'object';
}

function
getType
(
obj
,
opt_use
)
{
if
(
!
obj
)
{
return
;
}
switch
(
opt_use
)
{
case
'for'
:
return
'array'
;
case
'for in'
:
return
'object'
;
case
'for of'
:
return
'iterator'
;
case
'async for of'
:
return
'asyncIterator'
;
default
:
if
(
obj
===
Empty
)
{
return
;
}
if
(
isMap
(
obj
)
)
{
return
'map'
;
}
if
(
isWeakMap
(
obj
)
)
{
return
'weakMap'
;
}
if
(
isSet
(
obj
)
)
{
return
'set'
;
}
if
(
isWeakSet
(
obj
)
)
{
return
'weakSet'
;
}
if
(
isGenerator
(
obj
)
)
{
return
'generator'
;
}
if
(
isLikeArray
(
obj
)
)
{
return
'array'
;
}
if
(
isIterator
(
obj
)
)
{
return
'iterator'
;
}
if
(
isIDBRequest
(
obj
)
)
{
return
'idbRequest'
;
}
if
(
isStream
(
obj
)
)
{
return
'stream'
;
}
}
return
'object'
;
}

Returns the current type of an object

@param {Object} obj - source object
@param {?string=} [opt_use] - cycle type for iteration: for, for in, for of, async for of
@return {?string}


function getSameAs(obj) {
	if (!obj) {
		return false;
	}

	if (isArray(obj)) {
		return [];
	}

	if (isPlainObject(obj)) {
		return {};
	}

	if (isMap(obj)) {
		return new Map();
	}

	if (isSet(obj)) {
		return new Set();
	}

	return isFunction(obj.constructor) && !isNative.test(obj.constructor.toString()) ? {} : false;
}

function getSameAs ( obj ) { if ( ! obj ) { return false ; } if ( isArray ( obj ) ) { return [ ] ; } if ( isPlainObject ( obj ) ) { return { } ; } if ( isMap ( obj ) ) { return new Map ( ) ; } if ( isSet ( obj ) ) { return new Set ( ) ; } return isFunction ( obj . constructor ) && ! isNative . test ( obj . constructor . toString ( ) ) ? { } : false ; }

Returns a new object with the same type as source

@param {?} obj - source object
@return {?}


function isStructure(obj) {
	if (!obj) {
		return false;
	}

	if (isArray(obj) || isPlainObject(obj) || isMap(obj) || isSet(obj)) {
		return true;
	}

	return isFunction(obj.constructor) && !isNative.test(obj.constructor.toString());
}

function isStructure ( obj ) { if ( ! obj ) { return false ; } if ( isArray ( obj ) || isPlainObject ( obj ) || isMap ( obj ) || isSet ( obj ) ) { return true ; } return isFunction ( obj . constructor ) && ! isNative . test ( obj . constructor . toString ( ) ) ; }

Returns true if the specified object is one of JS data structures

@param {?} obj - source object
@return {boolean}


function canExtendProto(obj) {
	if (!obj) {
		return false;
	}

	if (isArray(obj) || isPlainObject(obj)) {
		return true;
	}

	return isFunction(obj.constructor) && !isNative.test(obj.constructor.toString());
}

function canExtendProto ( obj ) { if ( ! obj ) { return false ; } if ( isArray ( obj ) || isPlainObject ( obj ) ) { return true ; } return isFunction ( obj . constructor ) && ! isNative . test ( obj . constructor . toString ( ) ) ; }

Returns true if a prototype of the specified object can be extended

@param {?} obj - source object
@return {boolean}


async function asyncRoute(req, res) {
  await fakeWait();
  res.send({ ok: true });
}

async function asyncRoute ( req , res ) { await fakeWait ( ) ; res . send ( { ok : true } ) ; }


async function (query, options) {
        try {
            let response = await fetch(`http://www.ondemandkorea.com/includes15/search?q=${query}`, options);
            let json = await response.json();
            return json;
        } catch (err) {
            return err;
        }
    }

async function ( query , options ) { try { let response = await fetch ( ` ${ query } ` , options ) ; let json = await response . json ( ) ; return json ; } catch ( err ) { return err ; } }

Grabs the links of all movies and dramas including the given query
@param {String} query
@param {Object} options


function wrapRoute(fn) {
  if (!_lodash2.default.isFunction(fn)) {
    throw new Error('fn should be a function');
  }
  return function (req, res, next) {
    try {
      var result = fn(req, res, next);
      if (result && result.catch) {
        result.catch(next);
      }
    } catch (e) {
      next(e);
    }
  };
}

function
wrapRoute
(
fn
)
{
if
(
!
_lodash2
.
default
.
isFunction
(
fn
)
)
{
throw
new
Error
(
'fn should be a function'
)
;
}
return
function
(
req
,
res
,
next
)
{
try
{
var
result
=
fn
(
req
,
res
,
next
)
;
if
(
result
&&
result
.
catch
)
{
result
.
catch
(
next
)
;
}
}
catch
(
e
)
{
next
(
e
)
;
}
}
;
}

Wrap async function to standard express function
@param {Function} fn the async function
@returns {Function} the wrapped function


function(msg, flags) {
    if (flags.exact) {
      seneca.add(_.extend({}, msg, { role: 'entity', cmd: 'save' }), save)
      seneca.add(_.extend({}, msg, { role: 'entity', cmd: 'load' }), load)
      seneca.add(_.extend({}, msg, { role: 'entity', cmd: 'list' }), list)
      seneca.add(_.extend({}, msg, { role: 'entity', cmd: 'remove' }), remove)
      return
    }

    var actions = {
      save: save,
      load: load,
      list: list,
      remove: remove
    }

    var core_patterns = [
      { role: 'entity', cmd: 'save' },
      { role: 'entity', cmd: 'load' },
      { role: 'entity', cmd: 'list' },
      { role: 'entity', cmd: 'remove' }
    ]

    _.each(core_patterns, function(core_pat) {
      var pats = seneca.list(core_pat)
      _.each(pats, function(pat) {
        seneca.add(pat, actions[core_pat.cmd])
      })
    })
  }

function ( msg , flags ) { if ( flags . exact ) { seneca . add ( _ . extend ( { } , msg , { role : 'entity' , cmd : 'save' } ) , save ) seneca . add ( _ . extend ( { } , msg , { role : 'entity' , cmd : 'load' } ) , load ) seneca . add ( _ . extend ( { } , msg , { role : 'entity' , cmd : 'list' } ) , list ) seneca . add ( _ . extend ( { } , msg , { role : 'entity' , cmd : 'remove' } ) , remove ) return } var actions = { save : save , load : load , list : list , remove : remove } var core_patterns = [ { role : 'entity' , cmd : 'save' } , { role : 'entity' , cmd : 'load' } , { role : 'entity' , cmd : 'list' } , { role : 'entity' , cmd : 'remove' } ] _ . each ( core_patterns , function ( core_pat ) { var pats = seneca . list ( core_pat ) _ . each ( pats , function ( pat ) { seneca . add ( pat , actions [ core_pat . cmd ] ) } ) } ) }


function FBOAuth2(appId, appSecret, redirectURL){
  this._appId = appId;
  this._appSecret = appSecret;
  this._redirectURL = redirectURL;
  this._authURL = 'https://www.facebook.com/dialog/oauth';
  this._graphAPIURL = 'https://graph.facebook.com';
  this._accessTokenURI = '/oauth/access_token';
  this._profileURI = '/me';
}

function FBOAuth2 ( appId , appSecret , redirectURL ) { this . _appId = appId ; this . _appSecret = appSecret ; this . _redirectURL = redirectURL ; this . _authURL = 'https://www.facebook.com/dialog/oauth' ; this . _graphAPIURL = 'https://graph.facebook.com' ; this . _accessTokenURI = '/oauth/access_token' ; this . _profileURI = '/me' ; }

Facebook OAuth2 object, make various requests
the the graphAPI
@param {string} appId     the facebook app id
@param {string} appSecret the facebook app secret
@param {string} redirectURL  the url facebook should use as a callback

Facebook OAuth2 object make various requests the the graphAPI


function(options) {
  EventEmitter.apply(this, arguments);
  options = options || {};
  this.limit = options.limit || 16;
  this.json = options.json || false;
  this.records = options.records || [];
}

function ( options ) { EventEmitter . apply ( this , arguments ) ; options = options || { } ; this . limit = options . limit || 16 ; this . json = options . json || false ; this . records = options . records || [ ] ; }

Creates a RingBuffer instance.

@param options The stream configuration options.


function spy(obj, method) {
  if (!obj && !method) {
    obj = { spy: function(){} };
    method = 'spy';
  }
  return double(obj, method);
}

function spy ( obj , method ) { if ( ! obj && ! method ) { obj = { spy : function ( ) { } } ; method = 'spy' ; } return double ( obj , method ) ; }

Create a new spy object.

It can replace existing method if `obj` and `method` are
supplied.

@param {Object} obj (optional)
@param {String} method (optional)
@returns {Function} test double
@api public


function(conf, bitwise, parent) {
  EventEmitter.call(this);
  conf = conf || {};
  constants(this);
  this.keys = keys;
  this.bitwise = (bitwise === true);
  this.configure();
  var cstreams = parent && conf.streams;
  var streams = conf.streams, stream = conf.stream;
  streams = streams || this.getDefaultStream(conf);
  delete conf.streams;
  delete conf.stream;
  var target = parent ? merge(parent.conf, {}) : merge(defaults, {});
  this.conf = merge(conf, target);
  if(typeof this.conf.name !== 'string' || !this.conf.name.length) {
    throw new Error('Logger name \'' + this.conf.name + '\' is invalid');
  }
  this.name = this.conf.name;
  conf.streams = streams;
  if(stream) conf.stream = stream;
  this.pid = this.conf.pid || process.pid;
  this.hostname = this.conf.hostname || os.hostname();
  this.fields = {};
  this.streams = [];
  if(parent && cstreams) {
    streams = Array.isArray(streams) ? streams : [streams];
    streams = streams.concat(conf.streams);
  }
  this.initialize(streams);
}

function
(
conf
,
bitwise
,
parent
)
{
EventEmitter
.
call
(
this
)
;
conf
=
conf
||
{
}
;
constants
(
this
)
;
this
.
keys
=
keys
;
this
.
bitwise
=
(
bitwise
===
true
)
;
this
.
configure
(
)
;
var
cstreams
=
parent
&&
conf
.
streams
;
var
streams
=
conf
.
streams
,
stream
=
conf
.
stream
;
streams
=
streams
||
this
.
getDefaultStream
(
conf
)
;
delete
conf
.
streams
;
delete
conf
.
stream
;
var
target
=
parent
merge
(
parent
.
conf
,
{
}
)
:
merge
(
defaults
,
{
}
)
;
this
.
conf
=
merge
(
conf
,
target
)
;
if
(
typeof
this
.
conf
.
name
!==
'string'
||
!
this
.
conf
.
name
.
length
)
{
throw
new
Error
(
'Logger name \''
+
this
.
conf
.
name
+
'\' is invalid'
)
;
}
this
.
name
=
this
.
conf
.
name
;
conf
.
streams
=
streams
;
if
(
stream
)
conf
.
stream
=
stream
;
this
.
pid
=
this
.
conf
.
pid
||
process
.
pid
;
this
.
hostname
=
this
.
conf
.
hostname
||
os
.
hostname
(
)
;
this
.
fields
=
{
}
;
this
.
streams
=
[
]
;
if
(
parent
&&
cstreams
)
{
streams
=
Array
.
isArray
(
streams
)
streams
:
[
streams
]
;
streams
=
streams
.
concat
(
conf
.
streams
)
;
}
this
.
initialize
(
streams
)
;
}

Create a Logger instance.

@param conf The logger configuration.
@param bitwise A boolean indicating that log levels
should use bitwise operators.
@param parent A parent logger that owns this logger.


function createLogger(conf, bitwise) {
  conf = conf || {};
  if(conf.json === undefined) conf.json = true;
  return new Logger(conf, bitwise);
}

function createLogger ( conf , bitwise ) { conf = conf || { } ; if ( conf . json === undefined ) conf . json = true ; return new Logger ( conf , bitwise ) ; }

Create a Logger and set json configuration
to true if it has not been defined.

Defined for bunyan compatibility.

@param conf The logger configuration.
@param bitwise A boolean indicating that log levels
should use bitwise operators.

Create a Logger and set json configuration to true if it has not been defined .


function(id, type, attributes, relationships) {
    var _this = this;

    JsonApiResource.call(_this, id, type);
    BaseAttributesCreatedUpdated.call(_this);
    _this['type'] = type;
    _this['attributes'] = attributes;
    _this['relationships'] = relationships;
  }

function ( id , type , attributes , relationships ) { var _this = this ; JsonApiResource . call ( _this , id , type ) ; BaseAttributesCreatedUpdated . call ( _this ) ; _this [ 'type' ] = type ; _this [ 'attributes' ] = attributes ; _this [ 'relationships' ] = relationships ; }

The Folder model module.
@module model/Folder

Constructs a new Folder.
@alias module:model/Folder
@class
@implements module:model/JsonApiResource
@implements module:model/BaseAttributesCreatedUpdated
@param id {String} resource id
@param type {module:model/Folder.TypeEnum}
@param attributes {Object}
@param relationships {Object}


function mergeModels(value, model) {
    const newModel = Object.assign({}, model);
    tools_1.deepExtend(newModel, value);
    return { model: newModel, isChanged: deepEqual(model, newModel) };
}

function mergeModels ( value , model ) { const newModel = Object . assign ( { } , model ) ; tools_1 . deepExtend ( newModel , value ) ; return { model : newModel , isChanged : deepEqual ( model , newModel ) } ; }

Sets `values` to `model`
@param values fields values
@param model [[Form]] `model`


function(name, obj) {
  obj._namespace = name;
  observers = observers.concat(obj._observers);
  obj._emitter = caramel;
}

function ( name , obj ) { obj . _namespace = name ; observers = observers . concat ( obj . _observers ) ; obj . _emitter = caramel ; }

Newly created Cream initializer inside of the container


function(name, obj, after) {
  if (typeof after === 'string' && !inject(after)()) {
    caramel.once('register:' + after, function() {
      register(name, obj);
    });
    return;
  }

  var path = name.split('.');
  var ref = container;

  for (var i = 0; i < path.length - 1; i++) {
    if (!ref[path[i]]) {
      ref = ref[path[i]] = {};
    } else {
      ref = ref[path[i]];
    }
  }

  if (!ref[path[path.length - 1]]) {
    ref[path[path.length - 1]] = { cream : obj };
  } else {
    ref[path[path.length - 1]].cream = obj;
  }

  createCream(name, obj);
  caramel.emit('register:' + name);
}

function ( name , obj , after ) { if ( typeof after === 'string' && ! inject ( after ) ( ) ) { caramel . once ( 'register:' + after , function ( ) { register ( name , obj ) ; } ) ; return ; } var path = name . split ( '.' ) ; var ref = container ; for ( var i = 0 ; i < path . length - 1 ; i ++ ) { if ( ! ref [ path [ i ] ] ) { ref = ref [ path [ i ] ] = { } ; } else { ref = ref [ path [ i ] ] ; } } if ( ! ref [ path [ path . length - 1 ] ] ) { ref [ path [ path . length - 1 ] ] = { cream : obj } ; } else { ref [ path [ path . length - 1 ] ] . cream = obj ; } createCream ( name , obj ) ; caramel . emit ( 'register:' + name ) ; }

DI register method

@name register
@function
@access public
@param {String} name namespace register object into
@param {Cream} obj
@param {String} after namespace register object after


function(name) {
  var path = name.split('.');
  var ref = container;

  for (var i = 0; i < path.length - 1; i++) {
    if (!(ref = ref[path[i]])) {
      return;
    }
  }

  if (typeof ref[path[path.length - 1]] === 'object') {
    /**
     * Destroy registered Cream
     */
    if (ref[path[path.length - 1]]._type === 'Cream') {
      removeCream(name, ref[path[path.length - 1]].cream);

    } else if (ref[path[path.length - 1]].cream &&
      ref[path[path.length - 1]].cream._type === 'Cream') {

      removeCream(name, ref[path[path.length - 1]].cream);

      delete ref[path[path.length - 1]].cream;
    }

    delete ref[path[path.length - 1]];
  }
}

/**
     * Destroy registered Cream
     */

DI remove method

@name unregister
@function
@access public
@param {String} name namespace remove from


function _reduceStream (stream$, reducer, cb) {

	stream$
		.pipe(reduce(reducer.fn, reducer.memo))
		.once('data', function (reduction) {
			cb(null, reduction);
		})
		.once('error', cb);
}

function _reduceStream ( stream$ , reducer , cb ) { stream$ . pipe ( reduce ( reducer . fn , reducer . memo ) ) . once ( 'data' , function ( reduction ) { cb ( null , reduction ) ; } ) . once ( 'error' , cb ) ; }

Reduce a stream of data into a single value.

@param  {[type]}   stream$ [description]
@param  {Function} reducer [reducer object]
@param  {Function} cb      [description]
@return {[type]}           [description]

Reduce a stream of data into a single value .


function reduceHooks (hooks) {
  return msg => {
    let tmp
    return hooks.reduce((prev, hook) => {
      tmp = hook(prev)
      if (tmp === undefined || tmp === null) { return prev }
      return tmp
    }, msg)
  }
}

function reduceHooks ( hooks ) { return msg => { let tmp return hooks . reduce ( ( prev , hook ) => { tmp = hook ( prev ) if ( tmp === undefined || tmp === null ) { return prev } return tmp } , msg ) } }

Apply hooks on a message in reduce fashion.
Hooks may return a new message. If it's not the case, the previous message is used for the next reduce step.
@private
@param  {function[]} hooks - Set of hooks
@return {function} A function that apply the set of hooks to a message

Apply hooks on a message in reduce fashion . Hooks may return a new message . If it s not the case the previous message is used for the next reduce step .


function pcomp(f, g) {
  return function () {
    return f.apply(null, arguments) && g.apply(null, arguments);
  }
}

function pcomp ( f , g ) { return function ( ) { return f . apply ( null , arguments ) && g . apply ( null , arguments ) ; } }


function replace (regex, replacement, fileFilter) {
  if (fileFilter instanceof Array) {
    fileFilter = fileFilter.reduce(pcomp);
  } else if (!fileFilter) {
    fileFilter = () => true;
  }
  return files => {
    _.forEach(files, (file, path) => {
      if (fileFilter(file, path)) {
        file.contents = new Buffer(file.contents.toString().replace(regex, replacement));
      }
    });
  }
}

function replace ( regex , replacement , fileFilter ) { if ( fileFilter instanceof Array ) { fileFilter = fileFilter . reduce ( pcomp ) ; } else if ( ! fileFilter ) { fileFilter = ( ) => true ; } return files => { _ . forEach ( files , ( file , path ) => { if ( fileFilter ( file , path ) ) { file . contents = new Buffer ( file . contents . toString ( ) . replace ( regex , replacement ) ) ; } } ) ; } }

return metalsmith ware for carrying out the given replacement
on files for which the given fileFilter returns true


function paragraph(dict, wordCount, startWithCommon) {
	const result = [];
	let totalWords = 0;
	let words;

	if (startWithCommon && dict.common) {
		words = dict.common.slice(0, wordCount);
		totalWords += words.length;
		result.push(sentence(insertCommas(words), '.'));
	}

	while (totalWords < wordCount) {
		words = sample(dict.words, Math.min(rand(2, 30), wordCount - totalWords));
		totalWords += words.length;
		result.push(sentence(insertCommas(words)));
	}

	return result.join(' ');
}

function
paragraph
(
dict
,
wordCount
,
startWithCommon
)
{
const
result
=
[
]
;
let
totalWords
=
0
;
let
words
;
if
(
startWithCommon
&&
dict
.
common
)
{
words
=
dict
.
common
.
slice
(
0
,
wordCount
)
;
totalWords
+=
words
.
length
;
result
.
push
(
sentence
(
insertCommas
(
words
)
,
'.'
)
)
;
}
while
(
totalWords
<
wordCount
)
{
words
=
sample
(
dict
.
words
,
Math
.
min
(
rand
(
2
,
30
)
,
wordCount
totalWords
)
)
;
totalWords
+=
words
.
length
;
result
.
push
(
sentence
(
insertCommas
(
words
)
)
)
;
}
return
result
.
join
(
' '
)
;
}

Generate a paragraph of "Lorem ipsum" text
@param {Object} dict Words dictionary (see `lang/*.json`)
@param {Number} wordCount Words count in paragraph
@param {Boolean} startWithCommon Should paragraph start with common
"lorem ipsum" sentence.
@returns {String}

Generate a paragraph of Lorem ipsum text


function (scriptOrLink) {
    for(var p= 0, len = options.ignorePatterns.length; p < len; p++){
      if(options.ignorePatterns[p].test(scriptOrLink)){
        return true;
      }
    }
    return false;
  }

function ( scriptOrLink ) { for ( var p = 0 , len = options . ignorePatterns . length ; p < len ; p ++ ) { if ( options . ignorePatterns [ p ] . test ( scriptOrLink ) ) { return true ; } } return false ; }

returns true if src or href matches any of the patterns defined with options.ignorePatterns

returns true if src or href matches any of the patterns defined with options . ignorePatterns


function render(activities, highlight) {
    // Top verbs plus 'other'.
    var verbs = topVerbs(activities);

    var selection = d3.select(selector)
      .selectAll("li")
      .data(filterVerbs(activities), function(activity) { return activity.id });
    var li = selection.enter().append("li");

    li.html(function(activity) {
        return activity.html.replace(/(<time.*>).*(<\/time>)/, function(_, head, tail) {
          var date = Date.create(activity.published)
            .format("{Weekday}, {Mon} {d} {h}:{mm} {TT}");
          return head + date + tail;
        })
      });
    li.selectAll("div")
      .append("span").attr("class", "color");
    if (highlight)
      li.attr("class", "highlight").transition()
        .delay(1).attr("class", "");
    selection.exit().remove();
    // Set the color of each activity based on its verb.
    selection.select(".color")
      .style("background-color", function(d) { return verbColor(verbs, d.verb); })
    selection.order();

    renderVerbs(verbs);
  }

Render activities.  activities - Array with activities highlight  - True to highlight added activities

Render activities . activities - Array with activities highlight - True to highlight added activities


function topVerbs(activities, count) {
    var counts = {},
        list = [],
        top;
    for (var i in activities) {
      var verb = activities[i].verb;
      counts[verb] = (counts[verb] || 0) + 1;
    }
    for (key in counts)
      list.push({ key: key, values: counts[key] });
    top = list.sort(function(a, b) { return b.values - a.values })
      .slice(0, count)
      .map(function(verb) { return verb.key })
      .concat("other");

    // Make sure all verbs are showing by default.
    verbsShowing = top.reduce(function(showing, verb) {
      showing[verb.key] = verbsShowing[verb];
      if (showing[verb] == undefined)
        showing[verb] = true;
      return showing;
    }, {});

    return top;
  }

Returns a group with the top verbs.  activities - All activities count      - How many verbs to show  Returns a list of top verbs plus 'other'

Returns a group with the top verbs . activities - All activities count - How many verbs to show Returns a list of top verbs plus other


function filterVerbs(activities) {
    return activities.filter(function(activity) {
      var showing = verbsShowing[activity.verb];
      if (showing == undefined)
        showing = verbsShowing["other"];
      return showing;
    })
  }

function filterVerbs ( activities ) { return activities . filter ( function ( activity ) { var showing = verbsShowing [ activity . verb ] ; if ( showing == undefined ) showing = verbsShowing [ "other" ] ; return showing ; } ) }

Filters and returns only activities that should show based on selected filter.

Filters and returns only activities that should show based on selected filter .


function stdCall(options, call, args, cb) {
  var val = '';

  for (var key in args) {
    val += '&' + encodeURIComponent(key) + '=' + encodeURIComponent(args[key]);
  }

  if (call !== undefined) {
    call = '?command=' + call;
  }

  if (call === undefined) {
    call = '';
  }

  if (val === undefined) {
    val = '';
  }

  http.get({
    hostname: 'localhost',
    port: options.httpPort,
    path: '/requests/status.json' + call + val,
    auth: ':' + options.httpPassword,
    agent: false
  }, function(res) {
    if (cb !== undefined) {
      cb(res);
    }
  });
}

function stdCall ( options , call , args , cb ) { var val = '' ; for ( var key in args ) { val += '&' + encodeURIComponent ( key ) + '=' + encodeURIComponent ( args [ key ] ) ; } if ( call !== undefined ) { call = '?command=' + call ; } if ( call === undefined ) { call = '' ; } if ( val === undefined ) { val = '' ; } http . get ( { hostname : 'localhost' , port : options . httpPort , path : '/requests/status.json' + call + val , auth : ':' + options . httpPassword , agent : false } , function ( res ) { if ( cb !== undefined ) { cb ( res ) ; } } ) ; }

Do a standard call on the VLC API.
@param  {options}  options
@param  {string}   call
@param  {array}    args
@param  {Function} cb


function projectConfigAddPaths(originalConfig) {
	const config = originalConfig;

	if (!Object.prototype.hasOwnProperty.call(config.paths.src, TASK_NAME)) {
		config.paths.src[TASK_NAME] = `${config.dirs.src}/styles/`;
	}

	if (!Object.prototype.hasOwnProperty.call(config.paths.dest, TASK_NAME)) {
		config.paths.dest[TASK_NAME] = `${config.dirs.dest}/styles/`;
	}

	return config;
}

function projectConfigAddPaths ( originalConfig ) { const config = originalConfig ; if ( ! Object . prototype . hasOwnProperty . call ( config . paths . src , TASK_NAME ) ) { config . paths . src [ TASK_NAME ] = ` ${ config . dirs . src } ` ; } if ( ! Object . prototype . hasOwnProperty . call ( config . paths . dest , TASK_NAME ) ) { config . paths . dest [ TASK_NAME ] = ` ${ config . dirs . dest } ` ; } return config ; }


function findHeader(aoa) {
  const {i} = aoa.reduce(
    (prev, row, i) => {
      const len = rowLength(row)
      if (prev.len < len) {
        return {i, len}
      }
      return prev
    },
    {i: -1, len: 0}
  )
  return i
}

function findHeader ( aoa ) { const { i } = aoa . reduce ( ( prev , row , i ) => { const len = rowLength ( row ) if ( prev . len < len ) { return { i , len } } return prev } , { i : - 1 , len : 0 } ) return i }

finds the first row with the most columns


function lookup(name, obj) {
  for (const key in obj) {
    const re = RegExp(key, 'i')
    if (name.match(re)) {
      return obj[key]
    }
  }
  //else
  return null
}

function lookup ( name , obj ) { for ( const key in obj ) { const re = RegExp ( key , 'i' ) if ( name . match ( re ) ) { return obj [ key ] } } //else return null }


function isSsh(input) {

    if (Array.isArray(input)) {
        return input.indexOf("ssh") !== -1 || input.indexOf("rsync") !== -1;
    }

    if (typeof input !== "string") {
        return false;
    }

    var prots = protocols(input);
    input = input.substring(input.indexOf("://") + 3);
    if (isSsh(prots)) {
        return true;
    }

    // TODO This probably could be improved :)
    return input.indexOf("@") < input.indexOf(":");
}

isSsh
Checks if an input value is a ssh url or not.

@name isSsh
@function
@param {String|Array} input The input url or an array of protocols.
@return {Boolean} `true` if the input is a ssh url, `false` otherwise.

isSsh Checks if an input value is a ssh url or not .


function(options, cb) {
    return doNpmCommand({
      npmCommand: 'install',
      cmdArgs: options.dependencies,
      cmdOptions: {
        production: options.production || false,
        loglevel: options.loglevel || undefined,
        save: options.save || false,
        'save-dev': options.saveDev || false,
        'save-exact': options.saveExact || false,
        prefix: options.prefix || undefined,
      },
      dir: options.dir
    }, cb);
  }

function ( options , cb ) { return doNpmCommand ( { npmCommand : 'install' , cmdArgs : options . dependencies , cmdOptions : { production : options . production || false , loglevel : options . loglevel || undefined , save : options . save || false , 'save-dev' : options . saveDev || false , 'save-exact' : options . saveExact || false , prefix : options . prefix || undefined , } , dir : options . dir } , cb ) ; }

Run `npm install`.

@param  {Array}   dependencies	[string names of all your dependencies, plus versions if you want, you know the drill]
@param  {Object}   options
@param  {Object|Function} cb


function(){
    var i = 0, len = SinonExpect.assertions.length,
        matcher;

    for(i, len; i < len; i++){
      matcher = SinonExpect.assertions[i];
      (function(matcher){
        SinonExpect.SinonAssertions.prototype[matcher] = function(){
          var args = Array.prototype.slice.call(arguments),
              sinon = SinonExpect._sinon;

          args.unshift(this.obj);

          sinon.assert[matcher].apply(
            sinon.assert,
            args
          );
        };
      }(matcher));
    }
  }

function ( ) { var i = 0 , len = SinonExpect . assertions . length , matcher ; for ( i , len ; i < len ; i ++ ) { matcher = SinonExpect . assertions [ i ] ; ( function ( matcher ) { SinonExpect . SinonAssertions . prototype [ matcher ] = function ( ) { var args = Array . prototype . slice . call ( arguments ) , sinon = SinonExpect . _sinon ; args . unshift ( this . obj ) ; sinon . assert [ matcher ] . apply ( sinon . assert , args ) ; } ; } ( matcher ) ) ; } }

Creates sinon matchers on the SinonExpect.SinonAssertions prototype.
This could also be done on including the file but I prefer
keeping it in a method.

@private

Creates sinon matchers on the SinonExpect . SinonAssertions prototype . This could also be done on including the file but I prefer keeping it in a method .


function(thingy) {
    // simple DOM lookup utility function
    if (typeof(thingy) == 'string') thingy = document.getElementById(thingy);
    if (!thingy.addClass) {
      // extend element with a few useful methods
      thingy.hide = function() { this.style.display = 'none'; };
      thingy.show = function() { this.style.display = ''; };
      thingy.addClass = function(name) { this.removeClass(name); this.className += ' ' + name; };
      thingy.removeClass = function(name) {
        var classes = this.className.split(/\s+/);
        var idx = -1;
        for (var k = 0; k < classes.length; k++) {
          if (classes[k] == name) { idx = k; k = classes.length; }
        }
        if (idx > -1) {
          classes.splice( idx, 1 );
          this.className = classes.join(' ');
        }
        return this;
      };
      thingy.hasClass = function(name) {
        return !!this.className.match( new RegExp("\\s*" + name + "\\s*") );
      };
    }
    return thingy;
  }


function(elem, appendElem, stylesToAdd) {
    // glue to DOM element
    // elem can be ID or actual DOM element object
    this.domElement = ZeroClipboard.$(elem);

    // float just above object, or zIndex 99 if dom element isn't set
    var zIndex = 99;
    if (this.domElement.style.zIndex) {
      zIndex = parseInt(this.domElement.style.zIndex, 10) + 1;
    }

    if (typeof(appendElem) == 'string') {
      appendElem = ZeroClipboard.$(appendElem);
    }
    else if (typeof(appendElem) == 'undefined') {
      appendElem = document.getElementsByTagName('body')[0];
    }

    // find X/Y position of domElement
    var box = ZeroClipboard.getDOMObjectPosition(this.domElement, appendElem);

    // create floating DIV above element
    this.div = document.createElement('div');
    var style = this.div.style;
    style.position = 'absolute';
    style.left = '' + box.left + 'px';
    style.top = '' + box.top + 'px';
    style.width = '' + box.width + 'px';
    style.height = '' + box.height + 'px';
    style.zIndex = zIndex;

    style.left = '0px';
    style.top = '0px';

    if (typeof(stylesToAdd) == 'object') {
      for (addedStyle in stylesToAdd) {
        style[addedStyle] = stylesToAdd[addedStyle];
      }
    }

    // style.backgroundColor = '#f00'; // debug

    appendElem.appendChild(this.div);

    this.div.innerHTML = this.getHTML( box.width, box.height );
  }


function _full_delete(hash, key1, key2){
	    if( key1 && key2 && hash &&
		hash[key1] && hash[key1][key2] ){
		    delete hash[key1][key2];
		}
	    if( us.isEmpty(hash[key1]) ){
		delete hash[key1];
	    }
	}

function _full_delete ( hash , key1 , key2 ) { if ( key1 && key2 && hash && hash [ key1 ] && hash [ key1 ] [ key2 ] ) { delete hash [ key1 ] [ key2 ] ; } if ( us . isEmpty ( hash [ key1 ] ) ) { delete hash [ key1 ] ; } }

Internal helper to delete a low level key, and then if the top-level is empty, get that one too.

Internal helper to delete a low level key and then if the top - level is empty get that one too .


function SocketTransport(URL, options) {
		if (!URL) {
			throw new Error('A WebSocket URL must be passed to the SocketTransport constructor!');
		}
		if (!(this instanceof SocketTransport)) {
			return new SocketTransport(URL, options);
		}
		/**
		 * The URL to use for connecting to the WebSocket server.
		 * Typically, it looks like "ws://host.tld/path", where path may be empty.
		 * @type {string}
		 */
		this._URL = URL;
		/**
		 * A map of options to control the transport's behaviour.
		 */
		this._options = options || {};
		/**
		 * The current socket object in use.
		 * Since WebSockets can not be re-used after they have been closed,
		 *  this reference points to the current (i.e. most recent) socket in use.
		 * @type {?external:WebSocket}
		 */
		this._socket = null;
		/**
		 * A descriptive state of the transport, for internal logic use.
		 * This controls the various state transitions.
		 * @type {string}
		 */
		this._state = 'unconnected';
		/**
		 * Whether the transport is active.
		 * True means that the user intends to be connected.
		 * False is when the user has explicitly requested a connection shutdown.
		 * Inactive transports do not attempt reconnection when closed or when an error occurs.
		 * @type {boolean}
		 */
		this._active = false;
		/**
		 * The reconnection timeout. Set when an unplanned disconnect occurs.
		 * It is cleared when _deactivate() is called.
		 */
		this._reconnectTimeout = null;
		EventEmitter2.call(this);

		/**
		 * We store a map of "standard listeners" - that is, functions that we are going
		 *  to be adding as event listeners on WebSocket objects.
		 * This way, we have a reference to them, so we can do .removeEventListener().
		 * @type {Object.<string,function>}
		 */
		var self = this;
		var listeners = {
			open: function() {
				self._handleOpen();
			},
			error: function(error) {
				self._handleError(error);
			},
			close: function(closeEvent) {
				self._handleDisconnect();
			},
			message: function(messageEvent) {
				self.emit('message', messageEvent.data);
			}
		};
		this._standardListeners = listeners;

	}

SocketTransport is a class which maintains an active connection to a WebSocket server
and performs reconnection whenever needed. It also notifies the user of the socket
about disconnects and allows sending and receiving messages, mimicking the native
WebSocket API.
@constructor
@extends EventEmitter
@param {string} URL - The URL to connect to. Usually equal to something like "ws://host.tld" or "ws://host.tld/path/to/socket".
@param {Object} [options] - Options for controlling the behaviour of the transport.

SocketTransport is a class which maintains an active connection to a WebSocket server and performs reconnection whenever needed . It also notifies the user of the socket about disconnects and allows sending and receiving messages mimicking the native WebSocket API .


function Commander(client, options) {
		if (!(this instanceof Commander)) {
			return new Commander(client, options);
		}

		EventEmitter2.call(this);
		this.setMaxListeners(0);

		options = options || {};

		options.retryStrategy = options.retryStrategy || defaultRetry;

		this._client = client;
		this._options = options;
	}

function Commander ( client , options ) { if ( ! ( this instanceof Commander ) ) { return new Commander ( client , options ) ; } EventEmitter2 . call ( this ) ; this . setMaxListeners ( 0 ) ; options = options || { } ; options . retryStrategy = options . retryStrategy || defaultRetry ; this . _client = client ; this . _options = options ; }

A Commander is a layer over a JSON-RPC 2.0 Client which controls automatic retries of method calls.
@constructor
@param {JSONRPC} client - The underlying JSON-RPC client to use. Should expose an API equivalent to the one found in the JSONRPC module in this package.
@param {Object} [options] - Tunables that control the behaviour of this automatic layer.
@param {function} [options.retryStrategy] - A function that should accept no arguments and return a function which, when called with arguments (next:function, error:Error), will call that "next" function some time in the future, or reject with the passed error if retry is denied.

A Commander is a layer over a JSON - RPC 2 . 0 Client which controls automatic retries of method calls .


function addListElementFontSize(element)
    {
      var hDataWeight = -9007199254740992;
      var lDataWeight = 9007199254740992;
      $.each(element.find("li"), function(){
        cDataWeight = getDataWeight(this);
        if (cDataWeight == undefined)
        {
          logWarning("No \"data-weight\" attribut defined on <li> element");
        }
        else
        {
          hDataWeight = cDataWeight > hDataWeight ? cDataWeight : hDataWeight;
          lDataWeight = cDataWeight < lDataWeight ? cDataWeight : lDataWeight;
        }
      });
      $.each(element.find("li"), function(){
        var dataWeight = getDataWeight(this);
        var percent = Math.abs((dataWeight - lDataWeight)/(lDataWeight - hDataWeight));
        $(this).css('font-size', (1 + (percent * settings['multiplier'])) + "em");
      });

    }

calculates the font size on each li element
according to their data-weight attribut

calculates the font size on each li element according to their data - weight attribut


function(direction, cloud_element) {
  var start = $( '#cloudGraphPagingStart' ).val();
  var rows = $( '#cloudGraphPagingRows' ).val();
  var startAt = start ? parseInt(start) : 0;
  var numRows = rows ? parseInt(rows) : 20;
  var newStart = Math.max(startAt + (rows * direction),0);
  $( '#cloudGraphPagingStart' ).val(newStart);

  var graph_element = $( '#graph-content', cloud_element );
  $( '#canvas', graph_element).empty();
  init_graph( graph_element );
}

function ( direction , cloud_element ) { var start = $ ( '#cloudGraphPagingStart' ) . val ( ) ; var rows = $ ( '#cloudGraphPagingRows' ) . val ( ) ; var startAt = start ? parseInt ( start ) : 0 ; var numRows = rows ? parseInt ( rows ) : 20 ; var newStart = Math . max ( startAt + ( rows * direction ) , 0 ) ; $ ( '#cloudGraphPagingStart' ) . val ( newStart ) ; var graph_element = $ ( '#graph-content' , cloud_element ) ; $ ( '#canvas' , graph_element ) . empty ( ) ; init_graph ( graph_element ) ; }

updates the starting position for paged navigation and then rebuilds the graph based on the selected page


function doSubmit() {
      // make sure form attrs are set
      var t = $form.attr('target'), a = $form.attr('action');

      // update form attrs in IE friendly way
      form.setAttribute('target',id);
      if (form.getAttribute('method') != 'POST') {
        form.setAttribute('method', 'POST');
      }
      if (form.getAttribute('action') != s.url) {
        form.setAttribute('action', s.url);
      }

      // ie borks in some cases when setting encoding
      if (! s.skipEncodingOverride) {
        $form.attr({
          encoding: 'multipart/form-data',
          enctype:  'multipart/form-data'
        });
      }

      // support timout
      if (s.timeout) {
        setTimeout(function() { timedOut = true; cb(); }, s.timeout);
      }

      // add "extra" data to form if provided in options
      var extraInputs = [];
      try {
        if (s.extraData) {
          for (var n in s.extraData) {
            extraInputs.push(
              $('<input type="hidden" name="'+n+'" value="'+s.extraData[n]+'" />')
                .appendTo(form)[0]);
          }
        }

        // add iframe to doc and submit the form
        $io.appendTo('body');
        $io.data('form-plugin-onload', cb);
        form.submit();
      }
      finally {
        // reset attrs and remove "extra" input elements
        form.setAttribute('action',a);
        if(t) {
          form.setAttribute('target', t);
        } else {
          $form.removeAttr('target');
        }
        $(extraInputs).remove();
      }
    }

take a breath so that pending repaints get some cpu time before the upload starts


function AppClient(URL, options) {
		if (!(this instanceof AppClient)) {
			return new AppClient(URL, options);
		}

		options = options || {};

		//TODO: Implement option passing.
		var transport = options.transport || new SocketTransport(URL);
		var RPC = options.RPC || new JSONRPC(transport);
		var commander = options.commander ||  new Commander(RPC);

		// Every time we manage to connect, all pending calls are retried:
		transport.on('connect', function() {
			setTimeout(function() {
				commander.triggerRetries();
			}, 10000 * Math.random());
		});

		// Make transport errors non-fatal:
		transport.on('error', function() {});

		//TODO: Listen for drop notifications and immediately reject all RPCs with an { isRetriable: true } error.

		// Initialize getters so that all underlying resources may be conveniently accessed.
		Object.defineProperties(this, {
			transport: { enumerable: true, get: function() { return transport; } },
			RPC: { enumerable: true, get: function() { return RPC; } },
			commander: { enumerable: true, get: function() { return commander; } }
		});

		// Start the transport right away!
		transport.start();
	}

The AppClient is a high-level JSON-RPC client with support for method retries and reconnecting.
@constructor
@param {string} URL - The WebSocket URL to connect to.
@param {Object} [options] - The run-time options to control the behavior of the client.
@param {SocketTransport} [options.transport] - A custom SocketTransport instance to use instead of creating one. If passed, the URL argument is not used.
@param {SocketTransport} [options.RPC] - A custom RPC client to use.
@param {SocketTransport} [options.commander] - A custom Commander instance to use.

The AppClient is a high - level JSON - RPC client with support for method retries and reconnecting .


function writeTobuffer(value, buffer) {
  write(buffer, value, OFFSET, LITTLE_ENDIAN, MANTISSA_LENGTH, NUMBER_OF_BYTES);
}

function writeTobuffer ( value , buffer ) { write ( buffer , value , OFFSET , LITTLE_ENDIAN , MANTISSA_LENGTH , NUMBER_OF_BYTES ) ; }

Number of bytes on the buffer.
Writes am IEEE 754 compliant number into a buffer.
@param {number} value - Number to be written on the buffer.
@param {Buffer} buffer - Buffer where the `value` will be written.

Number of bytes on the buffer . Writes am IEEE 754 compliant number into a buffer .


function buf2hex(buffer, options = { prefix: true }) {
  var hex = Array.prototype.map
    .call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2))
    .join('');

  return options.prefix === true ? `0x${hex}` : hex;
}

function buf2hex ( buffer , options = { prefix : true } ) { var hex = Array . prototype . map . call ( new Uint8Array ( buffer ) , x => ( '00' + x . toString ( 16 ) ) . slice ( - 2 ) ) . join ( '' ) ; return options . prefix === true ? ` ${ hex } ` : hex ; }

Reads the information inside a buffer, an returns it as a string.
@param {Buffer} buffer - Converts the data stored in a Buffer to a hex string
@param {Object} options - Options configuration object.
@property {bool} prefix=true - Whether to add the prefix to the string or not
@return {string} Encoded buffer data as a string.

Reads the information inside a buffer an returns it as a string .


function num2hex(value, options) {
  if (value === undefined) throw new Error('Value is undefined');

  var buffer = Buffer.alloc(NUMBER_OF_BYTES);

  writeTobuffer(value, buffer);

  return buf2hex(buffer, options);
}

function
num2hex
(
value
,
options
)
{
if
(
value
===
undefined
)
throw
new
Error
(
'Value is undefined'
)
;
var
buffer
=
Buffer
.
alloc
(
NUMBER_OF_BYTES
)
;
writeTobuffer
(
value
,
buffer
)
;
return
buf2hex
(
buffer
,
options
)
;
}

Converts an IEEE 754 number into a hex representation of it.
@param {number} value - Number to be converted into an hexadecimal string.
@param {object} options - Options configuration object.
@return {string} IEEE 754 hex representation of the number.

Converts an IEEE 754 number into a hex representation of it .


function hex2num(value) {
  if (value === undefined) throw new Error('Value is undefined');

  var buffer = hex2buf(value);

  return readFromBuffer(buffer);
}

function
hex2num
(
value
)
{
if
(
value
===
undefined
)
throw
new
Error
(
'Value is undefined'
)
;
var
buffer
=
hex2buf
(
value
)
;
return
readFromBuffer
(
buffer
)
;
}

Converts an IEEE 754 compliant hexadecimal string into a JavaScript number.
@param {string} value - IEEE 754 compliant hexadecimal string to be converted
into a number.
@return {number} Decoded number.

Converts an IEEE 754 compliant hexadecimal string into a JavaScript number .


function () {
        var f = $.jstree._focused();
        if(f && f !== this) {
          f.get_container().removeClass("jstree-focused");
        }
        if(f !== this) {
          this.get_container().addClass("jstree-focused");
          focused_instance = this.get_index();
        }
        this.__callback();
      }

function ( ) { var f = $ . jstree . _focused ( ) ; if ( f && f !== this ) { f . get_container ( ) . removeClass ( "jstree-focused" ) ; } if ( f !== this ) { this . get_container ( ) . addClass ( "jstree-focused" ) ; focused_instance = this . get_index ( ) ; } this . __callback ( ) ; }


function() {
      var json = {};
      $.each(this, function(k,v) {
        if (!_isFunction(v)) {
          json[k] = v;
        }
      });
      return json;
    }

function ( ) { var json = { } ; $ . each ( this , function ( k , v ) { if ( ! _isFunction ( v ) ) { json [ k ] = v ; } } ) ; return json ; }

Returns a copy of the object with Functions removed.

Returns a copy of the object with Functions removed .


function() {
      var proxy = this, app = this.app;
      $(window).bind('hashchange.' + this.app.eventNamespace(), function(e, non_native) {
        // if we receive a native hash change event, set the proxy accordingly
        // and stop polling
        if (proxy.is_native === false && !non_native) {
          Sammy.log('native hash change exists, using');
          proxy.is_native = true;
          window.clearInterval(Sammy.HashLocationProxy._interval);
        }
        app.trigger('location-changed');
      });
      if (!Sammy.HashLocationProxy._bindings) {
        Sammy.HashLocationProxy._bindings = 0;
      }
      Sammy.HashLocationProxy._bindings++;
    }

bind the proxy events to the current app.

bind the proxy events to the current app .


function() {
      $(window).unbind('hashchange.' + this.app.eventNamespace());
      Sammy.HashLocationProxy._bindings--;
      if (Sammy.HashLocationProxy._bindings <= 0) {
        window.clearInterval(Sammy.HashLocationProxy._interval);
      }
    }

function ( ) { $ ( window ) . unbind ( 'hashchange.' + this . app . eventNamespace ( ) ) ; Sammy . HashLocationProxy . _bindings -- ; if ( Sammy . HashLocationProxy . _bindings <= 0 ) { window . clearInterval ( Sammy . HashLocationProxy . _interval ) ; } }

unbind the proxy events from the current app


function(verb, path) {
      var app = this, routed = false;
      this.trigger('lookup-route', {verb: verb, path: path});
      if (typeof this.routes[verb] != 'undefined') {
        $.each(this.routes[verb], function(i, route) {
          if (app.routablePath(path).match(route.path)) {
            routed = route;
            return false;
          }
        });
      }
      return routed;
    }

function ( verb , path ) { var app = this , routed = false ; this . trigger ( 'lookup-route' , { verb : verb , path : path } ) ; if ( typeof this . routes [ verb ] != 'undefined' ) { $ . each ( this . routes [ verb ] , function ( i , route ) { if ( app . routablePath ( path ) . match ( route . path ) ) { routed = route ; return false ; } } ) ; } return routed ; }

Given a verb and a String path, will return either a route object or false if a matching route can be found within the current defined set.

Given a verb and a String path will return either a route object or false if a matching route can be found within the current defined set .


function(location, name, data, callback) {
      if (_isArray(name)) {
        callback = data;
        data = name;
        name = null;
      }
      return this.load(location).then(function(content) {
          var rctx = this;
          if (!data) {
            data = _isArray(this.previous_content) ? this.previous_content : [];
          }
          if (callback) {
            $.each(data, function(i, value) {
              var idata = {}, engine = this.next_engine || location;
              name ? (idata[name] = value) : (idata = value);
              callback(value, rctx.event_context.interpolate(content, idata, engine));
            });
          } else {
            return this.collect(data, function(i, value) {
              var idata = {}, engine = this.next_engine || location;
              name ? (idata[name] = value) : (idata = value);
              return this.event_context.interpolate(content, idata, engine);
            }, true);
          }
      });
    }

function ( location , name , data , callback ) { if ( _isArray ( name ) ) { callback = data ; data = name ; name = null ; } return this . load ( location ) . then ( function ( content ) { var rctx = this ; if ( ! data ) { data = _isArray ( this . previous_content ) ? this . previous_content : [ ] ; } if ( callback ) { $ . each ( data , function ( i , value ) { var idata = { } , engine = this . next_engine || location ; name ? ( idata [ name ] = value ) : ( idata = value ) ; callback ( value , rctx . event_context . interpolate ( content , idata , engine ) ) ; } ) ; } else { return this . collect ( data , function ( i , value ) { var idata = { } , engine = this . next_engine || location ; name ? ( idata [ name ] = value ) : ( idata = value ) ; return this . event_context . interpolate ( content , idata , engine ) ; } , true ) ; } } ) ; }

loads a template, and then interpolates it for each item in the `data` array. If a callback is passed, it will call the callback with each item in the array _after_ interpolation

loads a template and then interpolates it for each item in the data array . If a callback is passed it will call the callback with each item in the array _after_ interpolation


function(name, data) {
      if (typeof data == 'undefined') { data = {}; }
      if (!data.context) { data.context = this; }
      return this.app.trigger(name, data);
    }

function ( name , data ) { if ( typeof data == 'undefined' ) { data = { } ; } if ( ! data . context ) { data . context = this ; } return this . app . trigger ( name , data ) ; }

Triggers events on `app` within the current context.

Triggers events on app within the current context .


function(partialPath, locals) {
    var normalizedPartialPath = normalizeTemplatePath(partialPath, path.dirname(normalizedTemplatePath));
    return exports.compile(normalizedPartialPath)(locals);
  }

function ( partialPath , locals ) { var normalizedPartialPath = normalizeTemplatePath ( partialPath , path . dirname ( normalizedTemplatePath ) ) ; return exports . compile ( normalizedPartialPath ) ( locals ) ; }

this function is available in the view for rendering partials


function(type, content, textAfter, state) {
                  if (this.jsonMode) {
                    return /^[\[,{]$/.test(content) || /^}/.test(textAfter);
                  } else {
                    if (content == ";" && state.lexical && state.lexical.type == ")") return false;
                    return /^[;{}]$/.test(content) && !/^;/.test(textAfter);
                  }
                }

function ( type , content , textAfter , state ) { if ( this . jsonMode ) { return / ^[\[,{]$ / . test ( content ) || / ^} / . test ( textAfter ) ; } else { if ( content == ";" && state . lexical && state . lexical . type == ")" ) return false ; return / ^[;{}]$ / . test ( content ) && ! / ^; / . test ( textAfter ) ; } }


function enteringString(cm, pos, ch) {
    var line = cm.getLine(pos.line);
    var token = cm.getTokenAt(pos);
    if (/\bstring2?\b/.test(token.type)) return false;
    var stream = new CodeMirror.StringStream(line.slice(0, pos.ch) + ch + line.slice(pos.ch), 4);
    stream.pos = stream.start = token.start;
    for (;;) {
      var type1 = cm.getMode().token(stream, token.state);
      if (stream.pos >= pos.ch + 1) return /\bstring2?\b/.test(type1);
      stream.start = stream.pos;
    }
  }

function enteringString ( cm , pos , ch ) { var line = cm . getLine ( pos . line ) ; var token = cm . getTokenAt ( pos ) ; if ( / \bstring2?\b / . test ( token . type ) ) return false ; var stream = new CodeMirror . StringStream ( line . slice ( 0 , pos . ch ) + ch + line . slice ( pos . ch ) , 4 ) ; stream . pos = stream . start = token . start ; for ( ; ; ) { var type1 = cm . getMode ( ) . token ( stream , token . state ) ; if ( stream . pos >= pos . ch + 1 ) return / \bstring2?\b / . test ( type1 ) ; stream . start = stream . pos ; } }

Project the token type that will exists after the given char is typed, and use it to determine whether it would cause the start of a string token.

Project the token type that will exists after the given char is typed and use it to determine whether it would cause the start of a string token .


function resolve(paths){
    paths = Array.isArray(paths) ? paths : [ paths ];
    var fullPath = path.resolve.apply(this, paths).replace(/\\/g, '/');

    return {
        fullPath: fullPath,
        dirName: path.dirname(fullPath),
        fileName: path.basename(fullPath),
        extName: path.extname(fullPath).replace('.','')
    };
}

function resolve ( paths ) { paths = Array . isArray ( paths ) ? paths : [ paths ] ; var fullPath = path . resolve . apply ( this , paths ) . replace ( / \\ / g , '/' ) ; return { fullPath : fullPath , dirName : path . dirname ( fullPath ) , fileName : path . basename ( fullPath ) , extName : path . extname ( fullPath ) . replace ( '.' , '' ) } ; }

resolve paths and get path, dir, file, ext
@param {Array/String} paths string or array of paths to resolve
@returns {Object}  fullPath, dirName, fileName, extName


function existsOrCreate(filePath, opts, cb){
    if(arguments.length===2){
        cb = arguments[1];
        opts = {};
    }
    opts.encoding = opts.encoding || 'utf8';
    opts.data = opts.data || opts.content || '';
    opts.mode = opts.mode || '0777';
    opts.replace = opts.replace ? true : false;

    var fp = resolve(filePath);
    var isFile = opts.hasOwnProperty('isFile') ? opts.isFile : !!fp.extName;

    fs.exists(fp.fullPath, function(exists){
        if(exists && !opts.replace) cb(null, exists);
        else {

            // file doesn't exists, create folder first
            mkdirp((isFile ? fp.dirName : fp.fullPath), opts.mode, function(err) {
                if (err) cb(new Error('fsExt.existsOrCreate: creating folders failed').cause(err));
                else if(isFile || opts.replace){

                    // folders are created, so create file
                    fs.writeFile(fp.fullPath, opts.data, opts.encoding, function(err){
                        if (err) cb(new Error('fsExt.existsOrCreate: creating file failed').cause(err));
                        else cb(null, exists);
                    });
                }
                else cb(null, exists);
            });
        }
    });
}

check if folder or file exists, if not create it
@param {String} filePath file path or array of paths to resolve
@param {Object} opts aditional options when creating file or directory (encoding, data, mode, replace, isFile) - use isFile when creating file with no extension, or folder with dot inside
@param {Function} cb callback(err,exists)

check if folder or file exists if not create it


function existsOrCreateSync(filePath, opts){
    opts = opts || {};
    opts.encoding = opts.encoding || 'utf8';
    opts.data = opts.data || opts.content || '';
    opts.mode = opts.mode || '0777';

    var fp = resolve(filePath);
    var isFile = opts.hasOwnProperty('isFile') ? opts.isFile : !!fp.extName;

    var exists = fs.existsSync(fp.fullPath);
    if(!exists || opts.replace){
        mkdir((isFile ? fp.dirName : fp.fullPath));
        if(isFile || opts.replace) fs.writeFileSync(fp.fullPath, opts.data, opts.encoding);
    }

    function mkdir(fullPath){
        if(fs.existsSync(fullPath)) return;
        else {
            var parentPath = fullPath.split('/');
            parentPath.pop();
            mkdir(parentPath.join('/'));
            fs.mkdirSync(fullPath, opts.mode);
        }
    }

    return exists;
}

function existsOrCreateSync ( filePath , opts ) { opts = opts || { } ; opts . encoding = opts . encoding || 'utf8' ; opts . data = opts . data || opts . content || '' ; opts . mode = opts . mode || '0777' ; var fp = resolve ( filePath ) ; var isFile = opts . hasOwnProperty ( 'isFile' ) ? opts . isFile : ! ! fp . extName ; var exists = fs . existsSync ( fp . fullPath ) ; if ( ! exists || opts . replace ) { mkdir ( ( isFile ? fp . dirName : fp . fullPath ) ) ; if ( isFile || opts . replace ) fs . writeFileSync ( fp . fullPath , opts . data , opts . encoding ) ; } function mkdir ( fullPath ) { if ( fs . existsSync ( fullPath ) ) return ; else { var parentPath = fullPath . split ( '/' ) ; parentPath . pop ( ) ; mkdir ( parentPath . join ( '/' ) ) ; fs . mkdirSync ( fullPath , opts . mode ) ; } } return exists ; }

sync version of existsOrCreate
@param {String} filePath
@param {Object}  opts     options
@returns {Boolean} exists


function unwatchAll(){
    for(var filePath in _fileWatchers) {
        if(_fileWatchers[filePath]) _fileWatchers[filePath].close();
        delete _fileWatchers[filePath];
    }

    for(var dirPath in _dirWatchers) {
        if(_dirWatchers[dirPath]) _dirWatchers[dirPath].close();
        delete _dirWatchers[dirPath];
    }
}

function unwatchAll ( ) { for ( var filePath in _fileWatchers ) { if ( _fileWatchers [ filePath ] ) _fileWatchers [ filePath ] . close ( ) ; delete _fileWatchers [ filePath ] ; } for ( var dirPath in _dirWatchers ) { if ( _dirWatchers [ dirPath ] ) _dirWatchers [ dirPath ] . close ( ) ; delete _dirWatchers [ dirPath ] ; } }


function writeFile(filePath, data, callback, count){ // callback(err)
    if(typeof callback !== 'function') throw new Error('Wrong arguments');
    filePath = path.resolve(filePath);

    count = count || 0;
    var maxLimit = 5; // 5 * 500ms = 2,5s

    fs.writeFile(filePath, data, function(err) {
        if(err) {
            if(count >= maxLimit) callback(new Error('fsExt.writeFile: max repeat limit reached').cause(err)); // repeat limit reached
            else setTimeout(function(){
                writeFile(filePath, data, callback, count + 1);
            }, 500);
        }
        else callback();
    });
}

very simple write repeater, when gets error, try repeat after 500ms, but max 5 times
@param {String} filePath
@param {String} data to write to file
@param {Function} callback(err)

very simple write repeater when gets error try repeat after 500ms but max 5 times


function readFile(filePath, opts, callback, count){ // callback(err)
    if(arguments.length===2){
        callback = arguments[1];
        opts = null;
    }
    if(typeof callback !== 'function') throw new Error('Wrong arguments');

    filePath = path.resolve(filePath);
    count = count || 0;
    var maxLimit = 5; // 5 * 500ms = 2,5s

    fs.readFile(filePath, opts, function(err, data) {
        if(err) {
            if(count >= maxLimit) callback(new Error('fsExt.readFie: max repeat limit reached').cause(err)); // repeat limit reached
            else setTimeout(function(){
                readFile(filePath, opts, callback, count + 1);
            }, 500);
        }
        else callback(null, data);
    });
}

very simple read repeater, when gets error, try repeat after 500ms, but max 5 times
@param {String} filePath
@param {Function} callback(err, data)

very simple read repeater when gets error try repeat after 500ms but max 5 times


function getFileInfo(fileId, filePath, cb, repeated){ // cb(err, fileInfo)
    repeated = repeated || 0;
    var fullPath = resolve(filePath).fullPath;

    fs.exists(fullPath, function(exists){
        if(!exists) cb();
        else fs.stat(fullPath, function(err, stat){
            if(err && err.code === 'ENOENT') { // directory or file removed, just skip it
                cb();
            }
            else if(err && repeated < 5) setTimeout(function(){
                getFileInfo(fileId, fullPath, cb, repeated+1);
            }, 200);
            else if(err) cb(err);
            else cb(null, getFileItem(fileId, stat, fullPath));
        });
    });
}

get resolved file info & stats
@param {String} fileId
@param {String} fullPath
@param {Function} cb
@param {Integer} repeated


function getPathAncestors(filename){
    var tree = filename.split('/');
    tree.pop(); // remove last

    var treePath = [];
    for(var i=0;i<tree.length;i++){
        treePath.push(createId(tree, i));
    }

    function createId(tree, count){
        var id = '';
        for(var i=0;i<=count;i++){
            id += (i>0 ? '/' : '') + tree[i];
        }
        return id;
    }

    return treePath;
}

function
getPathAncestors
(
filename
)
{
var
tree
=
filename
.
split
(
'/'
)
;
tree
.
pop
(
)
;
// remove last
var
treePath
=
[
]
;
for
(
var
i
=
0
;
i
<
tree
.
length
;
i
++
)
{
treePath
.
push
(
createId
(
tree
,
i
)
)
;
}
function
createId
(
tree
,
count
)
{
var
id
=
''
;
for
(
var
i
=
0
;
i
<=
count
;
i
++
)
{
id
+=
(
i
>
0
'/'
:
''
)
+
tree
[
i
]
;
}
return
id
;
}
return
treePath
;
}

helper - create ancestors list from path
@param {String} filename
@returns {Array}  ancestors list


function getName(fileId, isFile){
    var splitted = fileId.split('/'); // get filename
    var filename = splitted[splitted.length - 1]; // get file name
    if(!isFile) return filename;

    filename = filename.split('.');
    if(filename.length === 1) return filename[0]; // file has no extension
    filename.pop(); // remove extension if it has one
    return filename.join('.');
}

function
getName
(
fileId
,
isFile
)
{
var
splitted
=
fileId
.
split
(
'/'
)
;
// get filename
var
filename
=
splitted
[
splitted
.
length
1
]
;
// get file name
if
(
!
isFile
)
return
filename
;
filename
=
filename
.
split
(
'.'
)
;
if
(
filename
.
length
===
1
)
return
filename
[
0
]
;
// file has no extension
filename
.
pop
(
)
;
// remove extension if it has one
return
filename
.
join
(
'.'
)
;
}

helper - extract name from fileId
@param {String} fileId
@param {Boolean} isFile
@returns {String}  file name


function getExt(filename){
    var splitted = filename.split('.');
    if(splitted.length === 1) return ''; // file has no extension
    return splitted[splitted.length - 1]; // get file extension
}

function
getExt
(
filename
)
{
var
splitted
=
filename
.
split
(
'.'
)
;
if
(
splitted
.
length
===
1
)
return
''
;
// file has no extension
return
splitted
[
splitted
.
length
1
]
;
// get file extension
}

helper - extract file extension from file name
@param {String} filename
@returns {String}  file extension


function getFileItem(fileId, stat, filePath){
    return {
        id:fileId,
        fullPath: filePath,
        name: getName(fileId, !stat.isDirectory()),
        ancestors: getPathAncestors(fileId),
        isDir:stat.isDirectory(),
        isFile:!stat.isDirectory(),
        ext:!stat.isDirectory() ? getExt(fileId) : null,
        modifiedDT: stat.mtime, // (stat.ctime.getTime() > stat.mtime.getTime()) ? stat.ctime : stat.mtime,
        createdDT: stat.birthtime,
        size: stat.size
    };
}

helper - sumarize file info
@param {String} fileId
@param {Object} stat fsStat object
@param {String} filePath
@returns {Object}  file info object


function getDirChildren(parentId, items){
    var children = {};
    for(var id in items){
        if(items[id].ancestors[ items[id].ancestors.length-1 ] === parentId)
            children[id] = items[id];
    }
    return children;
}

function getDirChildren ( parentId , items ) { var children = { } ; for ( var id in items ) { if ( items [ id ] . ancestors [ items [ id ] . ancestors . length - 1 ] === parentId ) children [ id ] = items [ id ] ; } return children ; }

helper - get only direct children of directory
@param {String} parentId directory id
@param {Object} items files
@returns {Object}  children


function compareDirFiles(parentId, old_children, descendants){
    var changes = [],
        not_found = object.extend({}, old_children);

    for(var id in descendants) {
        if(descendants[id].ancestors[ descendants[id].ancestors.length-1 ] === parentId) { // compare only direct children

            if(!old_children[id]) { // not found in current children - created
                changes.push({ event:'created', file:descendants[id] });
                old_children[id] = descendants[id];
            }
            else if(old_children[id].modifiedDT < descendants[id].modifiedDT) { // found and updated
                changes.push({ event:'updated', file:descendants[id] });
                old_children[id] = descendants[id];
                delete not_found[id];
            }
            else { // file found, not not updated
                delete not_found[id];
            }
        }
    }

    // removed files
    for(var id in not_found) {
        changes.push({ event:'removed', file:not_found[id] });
        delete old_children[id];
    }

    return changes;
}

comparing old dir children and new dir children - executed on change event
@param {String} parentId directory id
@param {Object} old_children old directory children
@param {Object} descendants directory descendants
@returns {Array}  recognized changes


function(fn, ctx) {
        var task = !ctx ? fn : fn.bind(ctx);
        this.reads.push(task);
        scheduleFlush(this);
        return task;
    }

function ( fn , ctx ) { var task = ! ctx ? fn : fn . bind ( ctx ) ; this . reads . push ( task ) ; scheduleFlush ( this ) ; return task ; }

Adds a job to the read batch and
schedules a new frame if need be.

@param  {Function} fn
@public

Adds a job to the read batch and schedules a new frame if need be .


function(fn, ctx) {
        var task = !ctx ? fn : fn.bind(ctx);
        this.writes.push(task);
        scheduleFlush(this);
        return task;
    }

function ( fn , ctx ) { var task = ! ctx ? fn : fn . bind ( ctx ) ; this . writes . push ( task ) ; scheduleFlush ( this ) ; return task ; }

Adds a job to the
write batch and schedules
a new frame if need be.

@param  {Function} fn
@public

Adds a job to the write batch and schedules a new frame if need be .


function(props) {
        if (typeof props != 'object') { throw new Error('expected object'); }

        var child = Object.create(this);
        mixin(child, props);
        child.fastdom = this;

        // run optional creation hook
        if (child.initialize) { child.initialize(); }

        return child;
    }

function
(
props
)
{
if
(
typeof
props
!=
'object'
)
{
throw
new
Error
(
'expected object'
)
;
}
var
child
=
Object
.
create
(
this
)
;
mixin
(
child
,
props
)
;
child
.
fastdom
=
this
;
// run optional creation hook
if
(
child
.
initialize
)
{
child
.
initialize
(
)
;
}
return
child
;
}

Extend this FastDom with some
custom functionality.

Because fastdom must *always* be a
singleton, we're actually extending
the fastdom instance. This means tasks
scheduled by an extension still enter
fastdom's global task queue.

The 'super' instance can be accessed
from `this.fastdom`.

@example

var myFastdom = fastdom.extend({
initialize: function() {
// runs on creation
},

// override a method
measure: function(fn) {
// do extra stuff ...

// then call the original
return this.fastdom.measure(fn);
},

...
});

@param  {Object} props  properties to mixin
@return {FastDom}

Extend this FastDom with some custom functionality .


function flush(fastdom) {

    var reads = fastdom.reads.splice(0, fastdom.reads.length),
        writes = fastdom.writes.splice(0, fastdom.writes.length),
        error;

    try {
        runTasks(reads);
        runTasks(writes);
    } catch (e) { error = e; }

    fastdom.scheduled = false;

    // If the batch errored we may still have tasks queued
    if (fastdom.reads.length || fastdom.writes.length) { scheduleFlush(fastdom); }

    if (error) {
        if (fastdom.catch) { fastdom.catch(error); }
        else { throw error; }
    }
}

Runs queued `read` and `write` tasks.

Errors are caught and thrown by default.
If a `.catch` function has been defined
it is called instead.

@private


function create(props) {
    var knob = Object.create(this);

    // apply Widget defaults, then overwrite (if applicable) with Knob defaults
    _canvasWidget2.default.create.call(knob);

    // ...and then finally override with user defaults
    Object.assign(knob, Knob.defaults, props);

    // set underlying value if necessary... TODO: how should this be set given min/max?
    if (props.value) knob.__value = props.value;

    // inherits from Widget
    knob.init();

    return knob;
  }

Create a new Knob instance.
@memberof Knob
@constructs
@param {Object} [props] - A dictionary of properties to initialize Knob with.
@static


function processPointerPosition(e) {
    var xOffset = e.clientX,
        yOffset = e.clientY;

    var radius = this.rect.width / 2;
    this.lastValue = this.value;

    if (!this.usesRotation) {
      if (this.lastPosition !== -1) {
        //this.__value -= ( yOffset - this.lastPosition ) / (radius * 2);
        this.__value = 1 - yOffset / this.rect.height;
      }
    } else {
      var xdiff = radius - xOffset;
      var ydiff = radius - yOffset;
      var angle = Math.PI + Math.atan2(ydiff, xdiff);
      this.__value = (angle + Math.PI * 1.5) % (Math.PI * 2) / (Math.PI * 2);

      if (this.lastRotationValue > .8 && this.__value < .2) {
        this.__value = 1;
      } else if (this.lastRotationValue < .2 && this.__value > .8) {
        this.__value = 0;
      }
    }

    if (this.__value > 1) this.__value = 1;
    if (this.__value < 0) this.__value = 0;

    this.lastRotationValue = this.__value;
    this.lastPosition = yOffset;

    var shouldDraw = this.output();

    if (shouldDraw) this.draw();
  }

Generates a value between 0-1 given the current pointer position in relation
to the Knob's position, and triggers output.
@instance
@memberof Knob
@param {PointerEvent} e - The pointer event to be processed.

Generates a value between 0 - 1 given the current pointer position in relation to the Knob s position and triggers output .


function setContextValue(setChainContext, chainId, name, value) {
    if (value instanceof Function) {
        throw new FunctionAsValueException();
    }
    setChainContext(chainId, name, value);
}

function setContextValue ( setChainContext , chainId , name , value ) { if ( value instanceof Function ) { throw new FunctionAsValueException ( ) ; } setChainContext ( chainId , name , value ) ; }

Sets context value
@param setChainContext
@param chainId
@param name
@param value


function recurse(node) {
    // first navigate to the first sibling
    if (node.previousSibling) recurse(node.previousSibling);
    // then add the string representation of the nodes ('backward' recursion)
    switch (node.nodeType) {
      case 8: // comment
        html += "<!--" + node.nodeValue + "-->";
        break;
        // case 10: // doctype: jsDom does not know doctype as previousSibling.
    }
  }