function only (o, types) {
                    types = libs.object.toArray(arguments);
                    types.shift();

                    // Allows the 'plural' form of the type...
                    libs.object.each(types, function (type, key) { this[key] = type.replace(/s$/, ''); });

                    if(typeof o !== 'object' || !o) return o;
                    var isArray  = o instanceof Array ? true : false,
                        filtered = isArray ? [] : {},
                        typeArr  = types.indexOf('array'),
                        typeObj  = types.indexOf('object object');

                    libs.object.each(o, function (item, key) {
                        var typeItem = types.indexOf(typeof item);

                        if(typeObj !== -1 && typeArr === -1) {
                            if((typeof item === 'object' && !(item instanceof Array)) || (typeof item !== 'object' && typeItem !== -1)) {
                                if(isArray) filtered.push(item); else filtered[key] = item;
                            }
                        }
                        else if(typeObj !== -1 && typeArr !== -1) {
                            types.push('object');
                            if(typeItem !== -1) {
                                if(isArray) filtered.push(item); else filtered[key] = item;
                            }
                        }
                        else if(typeItem !== -1 || (item instanceof Array && typeArr !== -1)) {
                            if(isArray) filtered.push(item); else filtered[key] = item;
                        }
                    });
                    return filtered;
                }

Filters an array or object using only the types allowed. That is, if the item in the array is of a type listed
in the arguments, then it will be added to the filtered array. In this case 'array' is a valid type.
@param {Object} o The object to operate on.
@param {...String} types A list of typeof types that are allowed in the array.
@return {Array<*>} An array filtered by only the allowed types.

Filters an array or object using only the types allowed . That is if the item in the array is of a type listed in the arguments then it will be added to the filtered array . In this case array is a valid type .


function whereKeys (o, predicate) {
                    if(!(predicate instanceof Function)) {
                        var temp = predicate;
                        predicate = function (k) { return k == temp; }; // jshint ignore:line
                    }

                    if(o === null || o === undefined) return o;
                    if(typeof 0 === 'boolean') return predicate.call(o, o, 0);

                    var isObject = typeof o === 'object' && !(o instanceof Array) ? true : false,
                        filtered = !isObject ? [] : {};

                    libs.object.each(o, function (item, key) {
                        if(predicate.call(key, key, item)) {
                            if(isObject) filtered[key] = item; else filtered.push(item);
                        }
                    });

                    if(typeof o !== 'object') filtered = filtered.join('');
                    return filtered;
                }

function
whereKeys
(
o
,
predicate
)
{
if
(
!
(
predicate
instanceof
Function
)
)
{
var
temp
=
predicate
;
predicate
=
function
(
k
)
{
return
k
==
temp
;
}
;
// jshint ignore:line
}
if
(
o
===
||
o
===
undefined
)
return
o
;
if
(
typeof
0
===
'boolean'
)
return
predicate
.
call
(
o
,
o
,
0
)
;
var
isObject
=
typeof
o
===
'object'
&&
!
(
o
instanceof
Array
)
true
:
false
,
filtered
=
!
isObject
[
]
:
{
}
;
libs
.
object
.
each
(
o
,
function
(
item
,
key
)
{
if
(
predicate
.
call
(
key
,
key
,
item
)
)
{
if
(
isObject
)
filtered
[
key
]
=
item
;
else
filtered
.
push
(
item
)
;
}
}
)
;
if
(
typeof
o
!==
'object'
)
filtered
=
filtered
.
join
(
''
)
;
return
filtered
;
}

Filters an object by keys using the given predicate function.
@param {Object} o The object to operate on.
@param {Function} predicate The function used to filter the object.
@return {*} The filtered object

Filters an object by keys using the given predicate function .


function max (o, func) {
                    if(!o || typeof o !== 'object') return o;
                    if(libs.object.size(o) === 0) return;

                    if(!(func instanceof Function)) func = undefined;
                    var max, maxValue;

                    if(!func) {
                        max = libs.object.first(o);
                        libs.object.each(o, 1, function (item) {
                            if(item >= max) max = item;
                        });
                    }
                    else {
                        max      = libs.object.first(o);
                        maxValue = func.call(max, max);

                        libs.object.each(o, 1, function (item) {
                            var value = func.call(item, item);
                            if(value >= maxValue) {
                                max      = item;
                                maxValue = value;
                            }
                        });
                    }
                    return max;
                }

function max ( o , func ) { if ( ! o || typeof o !== 'object' ) return o ; if ( libs . object . size ( o ) === 0 ) return ; if ( ! ( func instanceof Function ) ) func = undefined ; var max , maxValue ; if ( ! func ) { max = libs . object . first ( o ) ; libs . object . each ( o , 1 , function ( item ) { if ( item >= max ) max = item ; } ) ; } else { max = libs . object . first ( o ) ; maxValue = func . call ( max , max ) ; libs . object . each ( o , 1 , function ( item ) { var value = func . call ( item , item ) ; if ( value >= maxValue ) { max = item ; maxValue = value ; } } ) ; } return max ; }

Returns the maximum item in the object.
@param {Object} o The object to operate on.
@param {Function=} func If passed, the function will be invoked for each item in the object collection.
@return {*} The maximum item in the object collection.

Returns the maximum item in the object .


function keyOfMax (o, func) {
                    if(!o || typeof o !== 'object') return o;
                    if(libs.object.size(o) === 0) return;

                    if(!(func instanceof Function)) func = undefined;
                    var max, maxValue, maxKey;

                    if(!func) {
                        max    = libs.object.first(o);
                        maxKey = libs.object.keys(o)[0];
                        libs.object.each(o, 1, function (item, key) {
                            if(item >= max) {
                                max    = item;
                                maxKey = key;
                            }
                        });
                    }
                    else {
                        max      = libs.object.first(o);
                        maxKey   = libs.object.keys(o)[0];
                        maxValue = func.call(max, max);

                        libs.object.each(o, 1, function (item, key) {
                            var value = func.call(item, item);
                            if(value >= maxValue) {
                                if(value >= maxValue) {
                                    max      = item;
                                    maxValue = value;
                                    maxKey   = key;
                                }
                            }
                        });
                    }
                    return maxKey;
                }

function keyOfMax ( o , func ) { if ( ! o || typeof o !== 'object' ) return o ; if ( libs . object . size ( o ) === 0 ) return ; if ( ! ( func instanceof Function ) ) func = undefined ; var max , maxValue , maxKey ; if ( ! func ) { max = libs . object . first ( o ) ; maxKey = libs . object . keys ( o ) [ 0 ] ; libs . object . each ( o , 1 , function ( item , key ) { if ( item >= max ) { max = item ; maxKey = key ; } } ) ; } else { max = libs . object . first ( o ) ; maxKey = libs . object . keys ( o ) [ 0 ] ; maxValue = func . call ( max , max ) ; libs . object . each ( o , 1 , function ( item , key ) { var value = func . call ( item , item ) ; if ( value >= maxValue ) { if ( value >= maxValue ) { max = item ; maxValue = value ; maxKey = key ; } } } ) ; } return maxKey ; }

Returns the key of the item with the highest value in the object.
@param {Object} o The object to operate on.
@param {Function=} func If passed, the function will be invoked for each item in the object collection.
@return {*} The maximum item in the object collection.

Returns the key of the item with the highest value in the object .


function min (o, func) {
                    if(!o || typeof o !== 'object') return o;
                    if(libs.object.size(o) === 0) return;

                    if(!(func instanceof Function)) func = undefined;

                    if(typeof o !== 'object') return o;
                    var min, minValue;

                    if(!func) {
                        min = libs.object.first(o);
                        libs.object.each(o, 1, function (item) {
                            if(item <= min) min = item;
                        });
                    }
                    else {
                        min      = libs.object.first(o);
                        minValue = func.call(min, min);

                        libs.object.each(o, 1, function (item) {
                            var value = func.call(item, item);
                            if(value <= minValue) {
                                min      = item;
                                minValue = value;
                            }
                        });
                    }
                    return min;
                }

function min ( o , func ) { if ( ! o || typeof o !== 'object' ) return o ; if ( libs . object . size ( o ) === 0 ) return ; if ( ! ( func instanceof Function ) ) func = undefined ; if ( typeof o !== 'object' ) return o ; var min , minValue ; if ( ! func ) { min = libs . object . first ( o ) ; libs . object . each ( o , 1 , function ( item ) { if ( item <= min ) min = item ; } ) ; } else { min = libs . object . first ( o ) ; minValue = func . call ( min , min ) ; libs . object . each ( o , 1 , function ( item ) { var value = func . call ( item , item ) ; if ( value <= minValue ) { min = item ; minValue = value ; } } ) ; } return min ; }

Returns the minimum item in the object.
@param {Object} o The object to operate on.
@param {Function=} func If passed, the function will be invoked for each item in the object collection.
@return {*} The minimum item in the object collection.

Returns the minimum item in the object .


function keyOfMin (o, func) {
                    if(!o || typeof o !== 'object') return o;
                    if(libs.object.size(o) === 0) return;

                    if(!(func instanceof Function)) func = undefined;

                    if(typeof o !== 'object') return o;
                    var min, minValue, minKey;

                    if(!func) {
                        min    = libs.object.first(o);
                        minKey = libs.object.keys(o)[0];
                        libs.object.each(o, 1, function (item, key) {
                            if(item <= min) {
                                min    = item;
                                minKey = key;
                            }
                        });
                    }
                    else {
                        min      = libs.object.first(o);
                        minValue = func.call(min, min);
                        minKey   = libs.object.keys(o)[0];

                        libs.object.each(o, 1, function (item, key) {
                            var value = func.call(item, item);
                            if(value <= minValue) {
                                min      = item;
                                minValue = value;
                                minKey   = key;
                            }
                        });
                    }
                    return minKey;
                }

function keyOfMin ( o , func ) { if ( ! o || typeof o !== 'object' ) return o ; if ( libs . object . size ( o ) === 0 ) return ; if ( ! ( func instanceof Function ) ) func = undefined ; if ( typeof o !== 'object' ) return o ; var min , minValue , minKey ; if ( ! func ) { min = libs . object . first ( o ) ; minKey = libs . object . keys ( o ) [ 0 ] ; libs . object . each ( o , 1 , function ( item , key ) { if ( item <= min ) { min = item ; minKey = key ; } } ) ; } else { min = libs . object . first ( o ) ; minValue = func . call ( min , min ) ; minKey = libs . object . keys ( o ) [ 0 ] ; libs . object . each ( o , 1 , function ( item , key ) { var value = func . call ( item , item ) ; if ( value <= minValue ) { min = item ; minValue = value ; minKey = key ; } } ) ; } return minKey ; }

Returns the key of the item with the lowest value in the object.
@param {Object} o The object to operate on.
@param {Function=} func If passed, the function will be invoked for each item in the object collection.
@return {*} The minimum item in the object collection.

Returns the key of the item with the lowest value in the object .


function _implements () {
                    var args = libs.object.toArray(arguments),
                        a    = args.shift();

                    if(!a) return false;
                    return libs.object.every(args, function (m) {
                        if(!(a[m] instanceof Function)) return false;
                    });
                }

function _implements ( ) { var args = libs . object . toArray ( arguments ) , a = args . shift ( ) ; if ( ! a ) return false ; return libs . object . every ( args , function ( m ) { if ( ! ( a [ m ] instanceof Function ) ) return false ; } ) ; }

Tests whether or not the object has a method called 'method'.
@param {Object} o The object to operate on.
@param {String} method The name of the method to test existence for.
@return {Boolean} True if the object has a function called 'method', false otherwise.

Tests whether or not the object has a method called method .


function implementsOwn (o, method) {
                    var args = libs.object.toArray(arguments),
                        a    = args.shift();

                    if(!a) return false;
                    return libs.object.every(args, function (m) {
                        if(!(a[m] instanceof Function) || !o.hasOwnProperty(method)) return false;
                    });
                }

function implementsOwn ( o , method ) { var args = libs . object . toArray ( arguments ) , a = args . shift ( ) ; if ( ! a ) return false ; return libs . object . every ( args , function ( m ) { if ( ! ( a [ m ] instanceof Function ) || ! o . hasOwnProperty ( method ) ) return false ; } ) ; }

Same as Object.j.implements, excepct with a hasOwnProperty check.
@param {Object} o The object to operate on.
@param {String} method The name of the method to test existence for.
@return {Boolean} True if the object has its own function called 'method', false otherwise.

Same as Object . j . implements excepct with a hasOwnProperty check .


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

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

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

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

    // inherits from Widget
    joystick.init();

    return joystick;
  }

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


function create() {
    var shouldUseTouch = _utilities2.default.getMode() === 'touch';

    _widget2.default.create.call(this);

    Object.assign(this, DOMWidget.defaults);

    // ALL INSTANCES OF DOMWIDGET MUST IMPLEMENT CREATE ELEMENT
    if (typeof this.createElement === 'function') {

      /**
       * The DOM element used by the DOMWidget
       * @memberof DOMWidget
       * @instance
       */
      this.element = this.createElement();
    } else {
      throw new Error('widget inheriting from DOMWidget does not implement createElement method; this is required.');
    }
  }

Create a new DOMWidget instance
@memberof DOMWidget
@constructs
@static


function place() {
    var containerWidth = this.container.getWidth(),
        containerHeight = this.container.getHeight(),
        width = this.width <= 1 ? containerWidth * this.width : this.width,
        height = this.height <= 1 ? containerHeight * this.height : this.height,
        x = this.x < 1 ? containerWidth * this.x : this.x,
        y = this.y < 1 ? containerHeight * this.y : this.y;

    if (!this.attached) {
      this.attached = true;
    }

    if (this.isSquare) {
      if (height > width) {
        height = width;
      } else {
        width = height;
      }
    }

    this.element.width = width;
    this.element.style.width = width + 'px';
    this.element.height = height;
    this.element.style.height = height + 'px';
    this.element.style.left = x;
    this.element.style.top = y;

    /**
     * Bounding box, in absolute coordinates, of the DOMWidget
     * @memberof DOMWidget
     * @instance
     * @type {Object}
     */
    this.rect = this.element.getBoundingClientRect();
  }

use CSS to position element element of widget
@memberof DOMWidget


function equalArrayElements (needle, haystack) {
  let missingNeedle = needle.filter(n => haystack.indexOf(n) === -1)
  if (missingNeedle.length !== 0) {
    return false
  }

  let missingHaystack = haystack.filter(h => needle.indexOf(h) === -1)
  return missingHaystack.length === 0
}

function equalArrayElements ( needle , haystack ) { let missingNeedle = needle . filter ( n => haystack . indexOf ( n ) === - 1 ) if ( missingNeedle . length !== 0 ) { return false } let missingHaystack = haystack . filter ( h => needle . indexOf ( h ) === - 1 ) return missingHaystack . length === 0 }

See if two arrays contain the same elements


function Series(asyncFncWrapper) {
    asyncFncWrapper = getAsyncFncWrapper(asyncFncWrapper);

    this.add = function() {
        var fnc, args;
        if(arguments.length===1) {
            fnc=arguments[0];
        }
        else if(arguments.length > 1) {
            fnc=arguments[arguments.length - 1];
            args = [];
            for(var i=0;i<arguments.length-1;i++){
                args.push(arguments[i]);
            }
        }

        if(typeof fnc!=='function')
            throw new Error('Async Series: Last argument have to be function(arg1, arg2, ..., next).');

        this._fncQueue = this._fncQueue || [];
        this._fncQueue.push({ args:args, fnc:fnc });

        this.execute = function(finalFnc){
            var fncQueue = this._fncQueue;
            fncQueue.current = 0;
            fncQueue.scheduled = 0;

            function run(itm) {
                asyncFncWrapper(function(){
                    fncQueue.scheduled = fncQueue.current;

                    if(itm.args) {
                        itm.args.push(next);
                        itm.fnc.apply(itm, itm.args);
                    }
                    else itm.fnc(next);
                });
            }

            function next(){
                if(!fncQueue || fncQueue.scheduled !== fncQueue.current)
                    throw new Error('Async Series: cannot execute next() more than once per function');

                // if(arguments.length > 0) {
                if(arguments.length > 0 && (arguments[0] !== null && typeof arguments[0] !== 'undefined')) {
                    var args = Array.prototype.slice.call(arguments);
                    fncQueue = null;
                    if(typeof finalFnc==='function')
                        asyncFncWrapper(function(){ finalFnc.apply(this, args); });
                }
                else if(fncQueue.current + 1 < fncQueue.length) {
                    fncQueue.current+=1;
                    run(fncQueue[fncQueue.current]);
                }
                else {
                    fncQueue = null;
                    if(typeof finalFnc==='function')
                        asyncFncWrapper(finalFnc);
                }
            }

            if(fncQueue && fncQueue.length>0)
                run(fncQueue[fncQueue.current]);
        };
        return this;
    };

    this.execute = function(fnc){ if(typeof fnc==='function') asyncFncWrapper(fnc); };
}

async Series queue constructor
@param {Object} asyncFncWrapper (optional) by default is setImmediate, but can be setTimeout, or any custom function
@returns {Object}  series queue


function Parallel(asyncFncWrapper) {
    asyncFncWrapper = getAsyncFncWrapper(asyncFncWrapper);

    this.add = function() {
        var fnc, args;
        if(arguments.length===1) {
            fnc=arguments[0];
        }
        else if(arguments.length > 1) {
            fnc=arguments[arguments.length - 1];
            args = [];
            for(var i=0;i<arguments.length-1;i++){
                args.push(arguments[i]);
            }
        }

        if(typeof fnc!=='function')
            throw new Error('Async Parallel: Last argument have to be function(arg1, arg2, ..., next).');

        this._fncQueue = this._fncQueue || [];
        this._fncQueue.push({ args:args, fnc:fnc });

        this.execute = function(finalFnc){
            var fncQueue = this._fncQueue;
            fncQueue.finished = 0;

            function run(itm) {
                asyncFncWrapper(function(){
                    if(itm.args) {
                        itm.args.push(next);
                        itm.fnc.apply(itm, itm.args);
                    }
                    else itm.fnc(next);
                });
            }

            function next(){
                if(arguments.length > 0)
                    throw new Error('Async Parallel: next() callback do not accept any arguments, ' +
                                    'because of parallel behaviour, it cannot stop executing on error argument in callback');

                else if(!fncQueue) // TODO: implement trackign finished queue items // (fncQueue.scheduled !== fncQueue.current)
                    throw new Error('Async Parallel: cannot execute next() more than once per function');

                else if(fncQueue.finished + 1 < fncQueue.length) {
                    fncQueue.finished+=1;
                }
                else {
                    fncQueue = null;
                    if(typeof finalFnc==='function')
                        asyncFncWrapper(finalFnc);
                }
            }

            for(var i=0; i< (fncQueue || []).length; i++) {
                run(fncQueue[i]);
            }
        };
        return this;
    };

    this.execute = function(fnc){ if(typeof fnc==='function') asyncFncWrapper(fnc); };
}

async Parallel queue constructor
@param {Object} asyncFncWrapper (optional) by default is setImmediate, but can be setTimeout, or any custom function
@returns {Object}  parallel queue


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

    _domWidget2.default.create.call(menu);

    Object.assign(menu, Menu.defaults, props);

    menu.createOptions();

    menu.element.addEventListener('change', function (e) {
      menu.__value = e.target.value;
      menu.output();

      if (menu.onvaluechange !== null) {
        menu.onvaluechange(menu.value);
      }
    });

    return menu;
  }

function create ( props ) { var menu = Object . create ( this ) ; _domWidget2 . default . create . call ( menu ) ; Object . assign ( menu , Menu . defaults , props ) ; menu . createOptions ( ) ; menu . element . addEventListener ( 'change' , function ( e ) { menu . __value = e . target . value ; menu . output ( ) ; if ( menu . onvaluechange !== null ) { menu . onvaluechange ( menu . value ) ; } } ) ; return menu ; }

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


function createOptions() {
    this.element.innerHTML = '';

    var _iteratorNormalCompletion = true;
    var _didIteratorError = false;
    var _iteratorError = undefined;

    try {
      for (var _iterator = this.options[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
        var option = _step.value;

        var optionEl = document.createElement('option');
        optionEl.setAttribute('value', option);
        optionEl.innerText = option;
        this.element.appendChild(optionEl);
      }
    } catch (err) {
      _didIteratorError = true;
      _iteratorError = err;
    } finally {
      try {
        if (!_iteratorNormalCompletion && _iterator.return) {
          _iterator.return();
        }
      } finally {
        if (_didIteratorError) {
          throw _iteratorError;
        }
      }
    }
  }

function createOptions ( ) { this . element . innerHTML = '' ; var _iteratorNormalCompletion = true ; var _didIteratorError = false ; var _iteratorError = undefined ; try { for ( var _iterator = this . options [ Symbol . iterator ] ( ) , _step ; ! ( _iteratorNormalCompletion = ( _step = _iterator . next ( ) ) . done ) ; _iteratorNormalCompletion = true ) { var option = _step . value ; var optionEl = document . createElement ( 'option' ) ; optionEl . setAttribute ( 'value' , option ) ; optionEl . innerText = option ; this . element . appendChild ( optionEl ) ; } } catch ( err ) { _didIteratorError = true ; _iteratorError = err ; } finally { try { if ( ! _iteratorNormalCompletion && _iterator . return ) { _iterator . return ( ) ; } } finally { if ( _didIteratorError ) { throw _iteratorError ; } } } }

Generate option elements for menu. Removes previously appended elements.
@memberof Menu
@instance

Generate option elements for menu . Removes previously appended elements .


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

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

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

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

    // inherits from Widget
    multiSlider.init();

    if (props.value === undefined && multiSlider.count !== 4) {
      for (var i = 0; i < multiSlider.count; i++) {
        multiSlider.__value[i] = i / multiSlider.count;
      }
    } else if (typeof props.value === 'number') {
      for (var _i = 0; _i < multiSlider.count; _i++) {
        multiSlider.__value[_i] = props.value;
      }
    }

    return multiSlider;
  }

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


function processPointerPosition(e) {
    var prevValue = this.value,
        sliderNum = void 0;

    if (this.style === 'horizontal') {
      sliderNum = Math.floor(e.clientY / this.rect.height / (1 / this.count));
      this.__value[sliderNum] = (e.clientX - this.rect.left) / this.rect.width;
    } else {
      sliderNum = Math.floor(e.clientX / this.rect.width / (1 / this.count));
      this.__value[sliderNum] = 1 - (e.clientY - this.rect.top) / this.rect.height;
    }

    for (var i = 0; i < this.count; i++) {
      if (this.__value[i] > 1) this.__value[i] = 1;
      if (this.__value[i] < 0) this.__value[i] = 0;
    }

    var shouldDraw = this.output();

    if (shouldDraw) this.draw();
  }

function processPointerPosition ( e ) { var prevValue = this . value , sliderNum = void 0 ; if ( this . style === 'horizontal' ) { sliderNum = Math . floor ( e . clientY / this . rect . height / ( 1 / this . count ) ) ; this . __value [ sliderNum ] = ( e . clientX - this . rect . left ) / this . rect . width ; } else { sliderNum = Math . floor ( e . clientX / this . rect . width / ( 1 / this . count ) ) ; this . __value [ sliderNum ] = 1 - ( e . clientY - this . rect . top ) / this . rect . height ; } for ( var i = 0 ; i < this . count ; i ++ ) { if ( this . __value [ i ] > 1 ) this . __value [ i ] = 1 ; if ( this . __value [ i ] < 0 ) this . __value [ i ] = 0 ; } var shouldDraw = this . output ( ) ; if ( shouldDraw ) this . draw ( ) ; }

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

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


function matchAll (regex, string) {
  let match
  let matches = []
  while ((match = regex.exec(string)) !== null) {
    delete match['index']
    delete match['input']
    matches.push(match)
  }

  return matches
}

function matchAll ( regex , string ) { let match let matches = [ ] while ( ( match = regex . exec ( string ) ) !== null ) { delete match [ 'index' ] delete match [ 'input' ] matches . push ( match ) } return matches }

Get all matches of a regex in a string as an array


function beforeEach(test, context, done) {
    context.dir = tmp.dirSync().name;
    process.chdir(context.dir);
    done && done();
}

function beforeEach ( test , context , done ) { context . dir = tmp . dirSync ( ) . name ; process . chdir ( context . dir ) ; done && done ( ) ; }


function promiseShouldFail(promise, done, handler) {
    promise.then(result => done(new Error('Promise expected to fail'))).
    catch(error => {
        handler(error)
        done()
    }).
    catch(error => done(error))
}

function
promiseShouldFail
(
promise
,
done
,
handler
)
{
promise
.
then
(
result
=>
done
(
new
Error
(
'Promise expected to fail'
)
)
)
.
catch
(
error
=>
{
handler
(
error
)
done
(
)
}
)
.
catch
(
error
=>
done
(
error
)
)
}


function promiseShouldSucceed(promise, done, handler) {
    promise.then(result => {
        handler(result)
        done()
    }).
    catch(error => done(error))
}

function promiseShouldSucceed ( promise , done , handler ) { promise . then ( result => { handler ( result ) done ( ) } ) . catch ( error => done ( error ) ) }


function copyAssetToContext(src, dest, context) {
    var sourceAsset = path.join(testDir, src);
    var targetAsset = path.join(context.dir, dest);

    if (!fs.existsSync(sourceAsset)) {
        // The source asset requested is missing
        throw new Error("The test asset is missing");
    }

    // Attempt to copy the asset
    fs.copySync(sourceAsset, targetAsset);

    if (!fs.existsSync(targetAsset)) {
        // The target asset was not copied successfully
        throw new Error("The test asset could not be copied");
    }
}

Look for a test asset, and if it exists, copy it to the
test context at the given location.

Look for a test asset and if it exists copy it to the test context at the given location .


function deepSet(parent, key, value, mode) {
    // if(typeof value==='string') value = value.replace(/(\r\n|\r|\n)\s*$/, ''); // replace line endings and white spaces
    var parts = key.split('.');
    var current = parent;
    if(key==='this') {
        if(mode==='push') parent.push(value);
        else parent = value.toString();
    }
    else {
        for(var i=0; i<parts.length; i++) {
            if(i >= parts.length-1) {
                if(mode==='push') current[parts[i]].push(value);
                else current[parts[i]] = value;
            }
            else current[parts[i]] = current[parts[i]] || {};
            current = current[parts[i]];
        }
    }
    return parent;
}

Define cascading props in objects in namespace separated by dot,
if props are on lower level, it will create empty object
@param {Object} parent base object where you want add props
@param {String} namespace dot separated
@param {Object} value value to add to object prop
@param {String} mode if "push", it will add value to array
@returns {Object}  parent object after properties are added

Define cascading props in objects in namespace separated by dot if props are on lower level it will create empty object


function (fPath, strict, fn) {
        if (typeof(strict) === 'function') {
          fn = strict;
          strict = false;
        }

        var dir  = path.dirname(fPath);
        var base = path.basename(fPath);

        if (typeof watched === 'undefined')
        {
          return fn && fn('[checkFile] watched array not properly defined.');
        }
        else {
          fs.stat(fPath, function onStat(err, stats) {
            //If we get back an error, then the directory doesn't exist. So we aren't watching it, duh!
            if (err) { return fn && fn(null, false); }

            //If the watched [] has not been initialized, we know the file isn't tracked
            if (typeof watched[dir] === 'undefined' || typeof watched[dir].files === 'undefined') {
              return fn && fn(null, false);
            }

            if (strict) {
              return fn && fn(null, watched[dir].files[base] === stats.mtime.valueOf());
            }
            else {
              return fn && fn(null, typeof watched[dir].files[base] !== 'undefined');
            }

          });
        }
                 }

Returns false if a file is not being tracked. Will ignore mtime unless strict is truthy.

Returns false if a file is not being tracked . Will ignore mtime unless strict is truthy .


function create(props) {
    var shouldUseTouch = _utilities2.default.getMode() === 'touch';

    _domWidget2.default.create.call(this);

    Object.assign(this, CanvasWidget.defaults);

    /**
     * Store a reference to the canvas 2D context.
     * @memberof CanvasWidget
     * @instance
     * @type {CanvasRenderingContext2D}
     */
    this.ctx = this.element.getContext('2d');

    this.applyHandlers(shouldUseTouch);
  }

Create a new CanvasWidget instance
@memberof CanvasWidget
@constructs
@static


function createElement() {
    var element = document.createElement('canvas');
    element.setAttribute('touch-action', 'none');
    element.style.position = 'absolute';
    element.style.display = 'block';

    return element;
  }

function createElement ( ) { var element = document . createElement ( 'canvas' ) ; element . setAttribute ( 'touch-action' , 'none' ) ; element . style . position = 'absolute' ; element . style . display = 'block' ; return element ; }

Create a the canvas element used by the widget and set
some default CSS values.
@memberof CanvasWidget
@static

Create a the canvas element used by the widget and set some default CSS values .


function convertOfficialMap (attributes) {
  let map = {}
  for (let attribute in attributes) {
    let key = officialAttributeMap[attribute]
    map[key] = attributes[attribute]
  }
  return map
}

function convertOfficialMap ( attributes ) { let map = { } for ( let attribute in attributes ) { let key = officialAttributeMap [ attribute ] map [ key ] = attributes [ attribute ] } return map }

Convert a official map into correct attribute names


function() {
        return _.map(ko.unwrap(that.relations), function(relation) {
          return ko.unwrap(relation.relatedPost.id);
        });
      }

function ( ) { return _ . map ( ko . unwrap ( that . relations ) , function ( relation ) { return ko . unwrap ( relation . relatedPost . id ) ; } ) ; }

returns the index value of the entities connected to the entity


function(element, valueAccessor, allBindings, viewModel, bindingContext) {
      var $element = $(element);
      var observable = valueAccessor();

      if (ko.unwrap(observable)) {
        $element.datepicker('update', observable.datePicker().format('DD.MM.YYYY')); // same as for .datepicker()));
      }
    }

function
(
element
,
valueAccessor
,
allBindings
,
viewModel
,
bindingContext
)
{
var
$element
=
$
(
element
)
;
var
observable
=
valueAccessor
(
)
;
if
(
ko
.
unwrap
(
observable
)
)
{
$element
.
datepicker
(
'update'
,
observable
.
datePicker
(
)
.
format
(
'DD.MM.YYYY'
)
)
;
// same as for .datepicker()));
}
}


async function disposable() {
  const name = "tmp" + Math.floor(Math.random() * 10000);
  await connection.dbCreate(name).run();

  const r = Object.create(connection);

  r.dispose = async function() {
    await this.dbDrop(name).run();
  };

  r._poolMaster._options.db = name;

  return r;
}

async function disposable ( ) { const name = "tmp" + Math . floor ( Math . random ( ) * 10000 ) ; await connection . dbCreate ( name ) . run ( ) ; const r = Object . create ( connection ) ; r . dispose = async function ( ) { await this . dbDrop ( name ) . run ( ) ; } ; r . _poolMaster . _options . db = name ; return r ; }

not really disposable, no way to get an instance with a different database, too expensive to open new connection for each test, but this will still work as "intended" for single thread tests.

not really disposable no way to get an instance with a different database too expensive to open new connection for each test but this will still work as intended for single thread tests .


function runRequestQueue (socket) {
      var queue = socket.requestQueue;

      if (!queue) return;
      for (var i in queue) {

        // Double-check that `queue[i]` will not
        // inadvertently discover extra properties attached to the Object
        // and/or Array prototype by other libraries/frameworks/tools.
        // (e.g. Ember does this. See https://github.com/balderdashy/sails.io.js/pull/5)
        var isSafeToDereference = ({}).hasOwnProperty.call(queue, i);
        if (isSafeToDereference) {
          // Emit the request.
          _emitFrom(socket, queue[i]);
        }
      }

      // Now empty the queue to remove it as a source of additional complexity.
      queue = null;
    }

What is the `requestQueue`?

The request queue is used to simplify app-level connection logic--
i.e. so you don't have to wait for the socket to be connected
to start trying to  synchronize data.

@api private
@param  {SailsSocket}  socket


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

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

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

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

    // inherits from Widget
    slider.init();

    return slider;
  }

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


function processPointerPosition(e) {
    var prevValue = this.value;

    if (this.style === 'horizontal') {
      this.__value = (e.clientX - this.rect.left) / this.rect.width;
    } else {
      this.__value = 1 - (e.clientY - this.rect.top) / this.rect.height;
    }

    // clamp __value, which is only used internally
    if (this.__value > 1) this.__value = 1;
    if (this.__value < 0) this.__value = 0;

    var shouldDraw = this.output();

    if (shouldDraw) this.draw();
  }

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

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


function storeJob(jobCompleted) {
    // if jobCompleted is jobFootPrint
    let emitterStore = new EventEmitter();
    let socketStoreJob = io.connect(urlSocket);
    let msg = messageBuilder(jobCompleted, 'storeJob', true);
    socketStoreJob.on('connect', function () {
        socketStoreJob.emit('storeJob', msg);
    })
        .on('addingResponse', (messageRes) => {
        logger_1.logger.log('info', `Job footprint stored in Warehouse`);
        //logger.log('info', `Message receive from server (add job request) \n ${JSON.stringify(messageRes)}`);
        logger_1.logger.log('debug', `Message returned: \n ${JSON.stringify(messageRes)}`);
        if (messageRes.value === 'success')
            emitterStore.emit('addSuccess', messageRes);
        if (messageRes.value === 'errorAddjob')
            emitterStore.emit('addError', messageRes);
    });
    return emitterStore;
}


function handshake(param) {
    return new Promise((resolve, reject) => {
        if (types.isClientConfig(param)) {
            logger_1.logger.log('info', `Client config paramaters perfectly loaded`);
            logger_1.logger.log('debug', `Config file content: \n ${JSON.stringify(param)}`);
            let socket = io.connect(`http://${param.warehouseAddress}:${param.portSocket}`);
            socket.on('connect', function () {
                logger_1.logger.log('info', `Connection with Warehouse server succeed, starting communication...\n`);
                resolve();
            })
                .on('connect_error', function () {
                logger_1.logger.log('debug', `Connection with Warehouse server cannot be establish, disconnecting socket...\n`);
                reject();
                socket.disconnect();
            });
        }
        else {
            logger_1.logger.log('error', `Config file not in good format \n ${JSON.stringify(config)}`);
            reject();
        }
    });
}

function handshake ( param ) { return new Promise ( ( resolve , reject ) => { if ( types . isClientConfig ( param ) ) { logger_1 . logger . log ( 'info' , ` ` ) ; logger_1 . logger . log ( 'debug' , ` \n ${ JSON . stringify ( param ) } ` ) ; let socket = io . connect ( ` ${ param . warehouseAddress } ${ param . portSocket } ` ) ; socket . on ( 'connect' , function ( ) { logger_1 . logger . log ( 'info' , ` \n ` ) ; resolve ( ) ; } ) . on ( 'connect_error' , function ( ) { logger_1 . logger . log ( 'debug' , ` \n ` ) ; reject ( ) ; socket . disconnect ( ) ; } ) ; } else { logger_1 . logger . log ( 'error' , ` \n ${ JSON . stringify ( config ) } ` ) ; reject ( ) ; } } ) ; }

Function handshake that test if the connection with the Warehouse micro-service is available

Function handshake that test if the connection with the Warehouse micro - service is available


function pivotTable(dataset) {
        var column_names = [];
        var xvalues = [];
        var values = {};
        var rows = {};
        for (rn in dataset.data) {
            // at first run fill the existing data (rows/columns/values)
            if (rn == 0) {
                // skip first row as it contains column names we don't need for pivot
                continue;
            }
            var val1 = dataset.data[rn][0];
            var val2 = dataset.data[rn][1];
            if (column_names.indexOf(val2) == -1) {
                column_names.push(val2);
            }
            if (xvalues.indexOf(val1) == -1) {
                xvalues.push(val1);
            }
            if (!(val1 in values)) {
                values[val1] = [];
            }
            values[val1][val2] = dataset.data[rn][2];
        }

        for (n in xvalues) {
            // at second run fill the missing values with nulls
            var val1 = xvalues[n];
            rows[val1] = [];
            for (m in column_names) {
                var val2 = column_names[m];
                if (val1 in values && val2 in values[val1]) {
                    rows[val1].push(values[val1][val2]);
                } else {
                    rows[val1].push(null);
                }
            }
        }

        var res = [];
        column_names.unshift(dataset.fields[0].name);
        res.push(column_names); // first row is pivot column names
        xvalues.forEach(function (item) {
            var r = [item].concat(rows[item]);
            res.push(r);
        });

        return res;
    }


function init(user_id, secret, storage, callback) {
    API_USER_ID = user_id;
    API_SECRET = secret;
    TOKEN_STORAGE = storage;

    if (!callback) {
        callback = function() {}
    }

    if (!fs.existsSync(TOKEN_STORAGE)) {
        mkdirSyncRecursive(TOKEN_STORAGE);
    }

    if (TOKEN_STORAGE.substr(-1) !== '/') {
        TOKEN_STORAGE += '/';
    }

    var hashName = md5(API_USER_ID+'::'+API_SECRET);
    if (fs.existsSync(TOKEN_STORAGE+hashName)) {
        TOKEN = fs.readFileSync(TOKEN_STORAGE+hashName,{encoding:'utf8'});
    }

    if (! TOKEN.length) {
        getToken(callback);
        return;
    }

    callback(TOKEN)
}

function init ( user_id , secret , storage , callback ) { API_USER_ID = user_id ; API_SECRET = secret ; TOKEN_STORAGE = storage ; if ( ! callback ) { callback = function ( ) { } } if ( ! fs . existsSync ( TOKEN_STORAGE ) ) { mkdirSyncRecursive ( TOKEN_STORAGE ) ; } if ( TOKEN_STORAGE . substr ( - 1 ) !== '/' ) { TOKEN_STORAGE += '/' ; } var hashName = md5 ( API_USER_ID + '::' + API_SECRET ) ; if ( fs . existsSync ( TOKEN_STORAGE + hashName ) ) { TOKEN = fs . readFileSync ( TOKEN_STORAGE + hashName , { encoding : 'utf8' } ) ; } if ( ! TOKEN . length ) { getToken ( callback ) ; return ; } callback ( TOKEN ) }

Sendpulse API initialization

@param user_id
@param secret
@param storage
@param callback


function getEmailTemplate(callback, id){
    if (id === undefined) {
        return callback(returnError('Empty email template id'));
    }
    sendRequest('template/' + id, 'GET', {}, true, callback);
}

function
getEmailTemplate
(
callback
,
id
)
{
if
(
id
===
undefined
)
{
return
callback
(
returnError
(
'Empty email template id'
)
)
;
}
sendRequest
(
'template/'
+
id
,
'GET'
,
{
}
,
true
,
callback
)
;
}

Get email template by id

@param callback
@param id


function updateEmailVariables(callback,id,email,variables){
    if ((id===undefined) || (email === undefined) || (variables === undefined) || (! variables.length)) {
        return callback(returnError("Empty email, variables or book id"));
    }
    var data = {
        email: email,
        variables: variables
    };
    sendRequest( 'addressbooks/' + id + '/emails/variable', 'POST', data, true, callback );
}

function
updateEmailVariables
(
callback
,
id
,
email
,
variables
)
{
if
(
(
id
===
undefined
)
||
(
email
===
undefined
)
||
(
variables
===
undefined
)
||
(
!
variables
.
length
)
)
{
return
callback
(
returnError
(
"Empty email, variables or book id"
)
)
;
}
var
data
=
{
email
:
email
,
variables
:
variables
}
;
sendRequest
(
'addressbooks/'
+
id
+
'/emails/variable'
,
'POST'
,
data
,
true
,
callback
)
;
}

Update Variables for an email address in an address book

@param callback
@param id
@param email
@param variables


function smsAddPhonesWithVariables(callback, addressbook_id, phones) {
    if ((addressbook_id === undefined) || (phones === undefined) || (!Object.keys(phones).length)) {
        return callback(returnError("Empty phones or book id"));
    }
    var data = {
        addressBookId: addressbook_id,
        phones: JSON.stringify(phones)
    };
    sendRequest('sms/numbers/variables', 'POST', data, true, callback);
}

function
smsAddPhonesWithVariables
(
callback
,
addressbook_id
,
phones
)
{
if
(
(
addressbook_id
===
undefined
)
||
(
phones
===
undefined
)
||
(
!
Object
.
keys
(
phones
)
.
length
)
)
{
return
callback
(
returnError
(
"Empty phones or book id"
)
)
;
}
var
data
=
{
addressBookId
:
addressbook_id
,
phones
:
JSON
.
stringify
(
phones
)
}
;
sendRequest
(
'sms/numbers/variables'
,
'POST'
,
data
,
true
,
callback
)
;
}

Add new phones to address book with variables

@param callback
@param addressbook_id
@param phones


function smsGetPhoneInfo(callback, addressbook_id, phone) {
    if ((addressbook_id === undefined) || (phone === undefined)) {
        return callback(returnError("Empty phone or book id"));
    }

    sendRequest('sms/numbers/info/' + addressbook_id + '/' + phone, 'GET', {}, true, callback);
}

function
smsGetPhoneInfo
(
callback
,
addressbook_id
,
phone
)
{
if
(
(
addressbook_id
===
undefined
)
||
(
phone
===
undefined
)
)
{
return
callback
(
returnError
(
"Empty phone or book id"
)
)
;
}
sendRequest
(
'sms/numbers/info/'
+
addressbook_id
+
'/'
+
phone
,
'GET'
,
{
}
,
true
,
callback
)
;
}

Get information about phone from the address book

@param callback
@param addressbook_id
@param phone


function smsUpdatePhonesVariables(callback, addressbook_id, phones, variables) {
    if (addressbook_id === undefined) {
        return callback(returnError("Empty book id"));
    }
    if ((phones === undefined) || (!phones.length)) {
        return callback(returnError("Empty phones"));
    }
    if ((variables === undefined) || (!Object.keys(variables).length)) {
        return callback(returnError("Empty variables"));
    }
    var data = {
        'addressBookId': addressbook_id,
        'phones': JSON.stringify(phones),
        'variables': JSON.stringify(variables)
    }

    sendRequest('sms/numbers', 'PUT', data, true, callback);
}

function
smsUpdatePhonesVariables
(
callback
,
addressbook_id
,
phones
,
variables
)
{
if
(
addressbook_id
===
undefined
)
{
return
callback
(
returnError
(
"Empty book id"
)
)
;
}
if
(
(
phones
===
undefined
)
||
(
!
phones
.
length
)
)
{
return
callback
(
returnError
(
"Empty phones"
)
)
;
}
if
(
(
variables
===
undefined
)
||
(
!
Object
.
keys
(
variables
)
.
length
)
)
{
return
callback
(
returnError
(
"Empty variables"
)
)
;
}
var
data
=
{
'addressBookId'
:
addressbook_id
,
'phones'
:
JSON
.
stringify
(
phones
)
,
'variables'
:
JSON
.
stringify
(
variables
)
}
sendRequest
(
'sms/numbers'
,
'PUT'
,
data
,
true
,
callback
)
;
}

Update phones variables from the address book

@param callback
@param addressbook_id
@param phones
@param variables


function smsAddPhonesToBlacklist(callback, phones, comment){
    if ((phones === undefined) || (!phones.length)) {
        return callback(returnError("Empty phones"));
    }
    var data = {
        'phones': JSON.stringify(phones),
        'description': comment
    }

    sendRequest('sms/black_list', 'POST', data, true, callback);
}

function
smsAddPhonesToBlacklist
(
callback
,
phones
,
comment
)
{
if
(
(
phones
===
undefined
)
||
(
!
phones
.
length
)
)
{
return
callback
(
returnError
(
"Empty phones"
)
)
;
}
var
data
=
{
'phones'
:
JSON
.
stringify
(
phones
)
,
'description'
:
comment
}
sendRequest
(
'sms/black_list'
,
'POST'
,
data
,
true
,
callback
)
;
}

Add phones to blacklist

@param callback
@param phones
@param comment


function smsDeletePhonesFromBlacklist(callback, phones) {
    if ((phones === undefined) || (!phones.length)) {
        return callback(returnError("Empty phones"));
    }
    var data = {
        'phones': JSON.stringify(phones),
    }

    sendRequest('sms/black_list', 'DELETE', data, true, callback);
}

function
smsDeletePhonesFromBlacklist
(
callback
,
phones
)
{
if
(
(
phones
===
undefined
)
||
(
!
phones
.
length
)
)
{
return
callback
(
returnError
(
"Empty phones"
)
)
;
}
var
data
=
{
'phones'
:
JSON
.
stringify
(
phones
)
,
}
sendRequest
(
'sms/black_list'
,
'DELETE'
,
data
,
true
,
callback
)
;
}

Remove phones from blacklist

@param callback
@param phones


function smsAddCampaign(callback, sender_name, addressbook_id, body, date, transliterate){
    if (sender_name === undefined) {
        return callback(returnError("Empty sender name"));
    }
    if (addressbook_id === undefined) {
        return callback(returnError("Empty book id"));
    }
    if (body === undefined) {
        return callback(returnError("Empty sms text"));
    }
    var data = {
        'sender': sender_name,
        'addressBookId': addressbook_id,
        'body': body,
        'date': date,
        'transliterate': transliterate
    }

    sendRequest('sms/campaigns', 'POST', data, true, callback);
}

function
smsAddCampaign
(
callback
,
sender_name
,
addressbook_id
,
body
,
date
,
transliterate
)
{
if
(
sender_name
===
undefined
)
{
return
callback
(
returnError
(
"Empty sender name"
)
)
;
}
if
(
addressbook_id
===
undefined
)
{
return
callback
(
returnError
(
"Empty book id"
)
)
;
}
if
(
body
===
undefined
)
{
return
callback
(
returnError
(
"Empty sms text"
)
)
;
}
var
data
=
{
'sender'
:
sender_name
,
'addressBookId'
:
addressbook_id
,
'body'
:
body
,
'date'
:
date
,
'transliterate'
:
transliterate
}
sendRequest
(
'sms/campaigns'
,
'POST'
,
data
,
true
,
callback
)
;
}

Create new sms campaign

@param callback
@param sender_name
@param addressbook_id
@param body
@param date
@param transliterate


function smsSend(callback, sender_name, phones, body, date, transliterate) {
    if (sender_name === undefined) {
        return callback(returnError("Empty sender name"));
    }
    if ((phones === undefined) || (!phones.length)) {
        return callback(returnError("Empty phones"));
    }
    if (body === undefined) {
        return callback(returnError("Empty sms text"));
    }
    var data = {
        'sender': sender_name,
        'phones': JSON.stringify(phones),
        'body': body,
        'date': date,
        'transliterate': transliterate
    }

    sendRequest('sms/send', 'POST', data, true, callback);
}

function
smsSend
(
callback
,
sender_name
,
phones
,
body
,
date
,
transliterate
)
{
if
(
sender_name
===
undefined
)
{
return
callback
(
returnError
(
"Empty sender name"
)
)
;
}
if
(
(
phones
===
undefined
)
||
(
!
phones
.
length
)
)
{
return
callback
(
returnError
(
"Empty phones"
)
)
;
}
if
(
body
===
undefined
)
{
return
callback
(
returnError
(
"Empty sms text"
)
)
;
}
var
data
=
{
'sender'
:
sender_name
,
'phones'
:
JSON
.
stringify
(
phones
)
,
'body'
:
body
,
'date'
:
date
,
'transliterate'
:
transliterate
}
sendRequest
(
'sms/send'
,
'POST'
,
data
,
true
,
callback
)
;
}

Send sms by some phones

@param callback
@param sender_name
@param phones
@param body
@param date
@param transliterate


function smsGetListCampaigns(callback, date_from, date_to) {
    var data = {
        'dateFrom': date_from,
        'dateTo': date_to
    }

    sendRequest('sms/campaigns/list', 'GET', data, true, callback);
}

function smsGetListCampaigns ( callback , date_from , date_to ) { var data = { 'dateFrom' : date_from , 'dateTo' : date_to } sendRequest ( 'sms/campaigns/list' , 'GET' , data , true , callback ) ; }

Get list of campaigns

@param callback
@param date_from
@param date_to


function smsGetCampaignInfo(callback, campaign_id){
    if (campaign_id === undefined) {
        return callback(returnError("Empty sms campaign id"));
    }

    sendRequest('sms/campaigns/info/' + campaign_id, 'GET', {}, true, callback);
}

function
smsGetCampaignInfo
(
callback
,
campaign_id
)
{
if
(
campaign_id
===
undefined
)
{
return
callback
(
returnError
(
"Empty sms campaign id"
)
)
;
}
sendRequest
(
'sms/campaigns/info/'
+
campaign_id
,
'GET'
,
{
}
,
true
,
callback
)
;
}

Get information about sms campaign

@param callback
@param campaign_id


function smsCancelCampaign(callback, campaign_id) {
    if (campaign_id === undefined) {
        return callback(returnError("Empty sms campaign id"));
    }

    sendRequest('sms/campaigns/cancel/' + campaign_id, 'PUT', {}, true, callback);
}

function
smsCancelCampaign
(
callback
,
campaign_id
)
{
if
(
campaign_id
===
undefined
)
{
return
callback
(
returnError
(
"Empty sms campaign id"
)
)
;
}
sendRequest
(
'sms/campaigns/cancel/'
+
campaign_id
,
'PUT'
,
{
}
,
true
,
callback
)
;
}

Cancel sms campaign

@param callback
@param campaign_id


function smsGetCampaignCost(callback, sender_name, body, addressbook_id, phones){
    if (sender_name === undefined) {
        return callback(returnError("Empty sender name"));
    }
    if (body === undefined) {
        return callback(returnError("Empty sms text"));
    }
    if ((addressbook_id === undefined) || (phones === undefined) || (!phones.length)) {
        return callback(returnError("Empty book id or phones"));
    }
    var data = {
        'sender': sender_name,
        'body': body,
        'addressBookId': addressbook_id
    }
    if (phones.length) {
        data['phones'] = JSON.stringify(phones);
    }

    sendRequest('sms/campaigns/cost', 'GET', data, true, callback);
}

function
smsGetCampaignCost
(
callback
,
sender_name
,
body
,
addressbook_id
,
phones
)
{
if
(
sender_name
===
undefined
)
{
return
callback
(
returnError
(
"Empty sender name"
)
)
;
}
if
(
body
===
undefined
)
{
return
callback
(
returnError
(
"Empty sms text"
)
)
;
}
if
(
(
addressbook_id
===
undefined
)
||
(
phones
===
undefined
)
||
(
!
phones
.
length
)
)
{
return
callback
(
returnError
(
"Empty book id or phones"
)
)
;
}
var
data
=
{
'sender'
:
sender_name
,
'body'
:
body
,
'addressBookId'
:
addressbook_id
}
if
(
phones
.
length
)
{
data
[
'phones'
]
=
JSON
.
stringify
(
phones
)
;
}
sendRequest
(
'sms/campaigns/cost'
,
'GET'
,
data
,
true
,
callback
)
;
}

Get cost sms campaign

@param callback
@param sender
@param body
@param addressbook_id
@param phones


function smsDeleteCampaign(callback, campaign_id) {
    if (campaign_id === undefined) {
        return callback(returnError("Empty sms campaign id"));
    }
    var data = {
        'id': campaign_id
    }
    sendRequest('sms/campaigns', 'DELETE', data, true, callback);
}

function
smsDeleteCampaign
(
callback
,
campaign_id
)
{
if
(
campaign_id
===
undefined
)
{
return
callback
(
returnError
(
"Empty sms campaign id"
)
)
;
}
var
data
=
{
'id'
:
campaign_id
}
sendRequest
(
'sms/campaigns'
,
'DELETE'
,
data
,
true
,
callback
)
;
}

Remove sms campaign

@param callback
@param campaign_id


function forEach(arr, callback, scope) {
        var i, len = arr.length;
        for (i = 0; i < len; i += 1) {
          callback.call(scope, arr[i], i);
        }
      }

function forEach ( arr , callback , scope ) { var i , len = arr . length ; for ( i = 0 ; i < len ; i += 1 ) { callback . call ( scope , arr [ i ] , i ) ; } }

A forEach that will work with a NodeList and generic Arrays
@param {array|NodeList} arr The array to iterate over
@param {function} callback Function that executes for each element. First parameter is element, second is index
@param {object} The context to execute callback with


function emit(instance, name) {
        var args = [].slice.call(arguments, 2);
        if (events.indexOf(name) > -1) {
          if (instance.handlers[name] && instance.handlers[name] instanceof Array) {
            forEach(instance.handlers[name], function (handle) {
              window.setTimeout(function () {
                handle.callback.apply(handle.context, args);
              }, 0);
            });
          }
        } else {
          throw new Error(name + ' event cannot be found on TreeView.');
        }
      }

function
emit
(
instance
,
name
)
{
var
args
=
[
]
.
slice
.
call
(
arguments
,
2
)
;
if
(
events
.
indexOf
(
name
)
>
1
)
{
if
(
instance
.
handlers
[
name
]
&&
instance
.
handlers
[
name
]
instanceof
Array
)
{
forEach
(
instance
.
handlers
[
name
]
,
function
(
handle
)
{
window
.
setTimeout
(
function
(
)
{
handle
.
callback
.
apply
(
handle
.
context
,
args
)
;
}
,
0
)
;
}
)
;
}
}
else
{
throw
new
Error
(
name
+
' event cannot be found on TreeView.'
)
;
}
}

Emit an event from the tree view
@param {string} name The name of the event to emit


function render(self) {
        var container = isDOMElement(self.node) ? self.node : document.getElementById(self.node);
        var leaves = [], click;
        var renderLeaf = function (item) {
          var leaf = document.createElement('div');
          var content = document.createElement('div');
          var text = document.createElement('div');
          var expando = document.createElement('div');

          leaf.setAttribute('class', 'tree-leaf');
          content.setAttribute('class', 'tree-leaf-content');
          content.setAttribute('data-item', JSON.stringify(item));
          text.setAttribute('class', 'tree-leaf-text');
          text.textContent = item.name;
          expando.setAttribute('class', 'tree-expando ' + (item.expanded ? 'expanded' : ''));
          expando.textContent = item.expanded ? '-' : '+';
          content.appendChild(expando);
          content.appendChild(text);
          leaf.appendChild(content);
          if (item.children && item.children.length > 0) {
            var children = document.createElement('div');
            children.setAttribute('class', 'tree-child-leaves');
            forEach(item.children, function (child) {
              var childLeaf = renderLeaf(child);
              children.appendChild(childLeaf);
            });
            if (!item.expanded) {
              children.classList.add('hidden');
            }
            leaf.appendChild(children);
          } else {
            expando.classList.add('hidden');
          }
          return leaf;
        };

        forEach(self.data, function (item) {
          leaves.push(renderLeaf.call(self, item));
        });
        container.innerHTML = leaves.map(function (leaf) {
          return leaf.outerHTML;
        }).join('');

        click = function (e) {
          var parent = (e.target || e.currentTarget).parentNode;
          var data = JSON.parse(parent.getAttribute('data-item'));
          var leaves = parent.parentNode.querySelector('.tree-child-leaves');
          if (leaves) {
            if (leaves.classList.contains('hidden')) {
              self.expand(parent, leaves);
            } else {
              self.collapse(parent, leaves);
            }
          } else {
            emit(self, 'select', {
              target: e,
              data: data
            });
          }
        };

        forEach(container.querySelectorAll('.tree-leaf-text'), function (node) {
          node.onclick = click;
        });
        forEach(container.querySelectorAll('.tree-expando'), function (node) {
          node.onclick = click;
        });
      }

function
render
(
self
)
{
var
container
=
isDOMElement
(
self
.
node
)
self
.
node
:
document
.
getElementById
(
self
.
node
)
;
var
leaves
=
[
]
,
click
;
var
renderLeaf
=
function
(
item
)
{
var
leaf
=
document
.
createElement
(
'div'
)
;
var
content
=
document
.
createElement
(
'div'
)
;
var
text
=
document
.
createElement
(
'div'
)
;
var
expando
=
document
.
createElement
(
'div'
)
;
leaf
.
setAttribute
(
'class'
,
'tree-leaf'
)
;
content
.
setAttribute
(
'class'
,
'tree-leaf-content'
)
;
content
.
setAttribute
(
'data-item'
,
JSON
.
stringify
(
item
)
)
;
text
.
setAttribute
(
'class'
,
'tree-leaf-text'
)
;
text
.
textContent
=
item
.
name
;
expando
.
setAttribute
(
'class'
,
'tree-expando '
+
(
item
.
expanded
'expanded'
:
''
)
)
;
expando
.
textContent
=
item
.
expanded
'-'
:
'+'
;
content
.
appendChild
(
expando
)
;
content
.
appendChild
(
text
)
;
leaf
.
appendChild
(
content
)
;
if
(
item
.
children
&&
item
.
children
.
length
>
0
)
{
var
children
=
document
.
createElement
(
'div'
)
;
children
.
setAttribute
(
'class'
,
'tree-child-leaves'
)
;
forEach
(
item
.
children
,
function
(
child
)
{
var
childLeaf
=
renderLeaf
(
child
)
;
children
.
appendChild
(
childLeaf
)
;
}
)
;
if
(
!
item
.
expanded
)
{
children
.
classList
.
add
(
'hidden'
)
;
}
leaf
.
appendChild
(
children
)
;
}
else
{
expando
.
classList
.
add
(
'hidden'
)
;
}
return
leaf
;
}
;
forEach
(
self
.
data
,
function
(
item
)
{
leaves
.
push
(
renderLeaf
.
call
(
self
,
item
)
)
;
}
)
;
container
.
innerHTML
=
leaves
.
map
(
function
(
leaf
)
{
return
leaf
.
outerHTML
;
}
)
.
join
(
''
)
;
click
=
function
(
e
)
{
var
parent
=
(
e
.
target
||
e
.
currentTarget
)
.
parentNode
;
var
data
=
JSON
.
parse
(
parent
.
getAttribute
(
'data-item'
)
)
;
var
leaves
=
parent
.
parentNode
.
querySelector
(
'.tree-child-leaves'
)
;
if
(
leaves
)
{
if
(
leaves
.
classList
.
contains
(
'hidden'
)
)
{
self
.
expand
(
parent
,
leaves
)
;
}
else
{
self
.
collapse
(
parent
,
leaves
)
;
}
}
else
{
emit
(
self
,
'select'
,
{
target
:
e
,
data
:
data
}
)
;
}
}
;
forEach
(
container
.
querySelectorAll
(
'.tree-leaf-text'
)
,
function
(
node
)
{
node
.
onclick
=
click
;
}
)
;
forEach
(
container
.
querySelectorAll
(
'.tree-expando'
)
,
function
(
node
)
{
node
.
onclick
=
click
;
}
)
;
}


function validatePackageName(package_name) {
    //Make the package conform to Java package types
    //http://developer.android.com/guide/topics/manifest/manifest-element.html#package
    //Enforce underscore limitation
    var msg = 'Error validating package name. ';
    if (!/^[a-zA-Z][a-zA-Z0-9_]+(\.[a-zA-Z][a-zA-Z0-9_]*)+$/.test(package_name)) {
        return Q.reject(new CordovaError(msg + 'Package name must look like: com.company.Name'));
    }

    //Class is a reserved word
    if(/\b[Cc]lass\b/.test(package_name)) {
        return Q.reject(new CordovaError(msg + '"class" is a reserved word'));
    }

    return Q.resolve();
}

Test whether a package name is acceptable for use as an android project.
Returns a promise, fulfilled if the package name is acceptable; rejected
otherwise.

Test whether a package name is acceptable for use as an android project . Returns a promise fulfilled if the package name is acceptable ; rejected otherwise .


function validateProjectName(project_name) {
    var msg = 'Error validating project name. ';
    //Make sure there's something there
    if (project_name === '') {
        return Q.reject(new CordovaError(msg + 'Project name cannot be empty'));
    }

    //Enforce stupid name error
    if (project_name === 'CordovaActivity') {
        return Q.reject(new CordovaError(msg + 'Project name cannot be CordovaActivity'));
    }

    //Classes in Java don't begin with numbers
    if (/^[0-9]/.test(project_name)) {
        return Q.reject(new CordovaError(msg + 'Project name must not begin with a number'));
    }

    return Q.resolve();
}

Test whether a project name is acceptable for use as an android class.
Returns a promise, fulfilled if the project name is acceptable; rejected
otherwise.

Test whether a project name is acceptable for use as an android class . Returns a promise fulfilled if the project name is acceptable ; rejected otherwise .


function (file) {
			var contents = fs.readFileSync(file, 'utf-8');

			if (contents) {
				// Windows is the BOM. Skip the Byte Order Mark.
				contents = contents.substring(contents.indexOf('<'));
			}

			var doc = new et.ElementTree(et.XML(contents));		// eslint-disable-line babel/new-cap
			var root = doc.getroot();

			if (root.tag !== 'widget') {
				// Throw an error if widget is not the root tag
				throw new Error(file + ' has incorrect root node name (expected "widget", was "' + root.tag + '")');
			}

			return doc;
		}

This method parses the xml file provided.

@param  {string}	file		The XML file that should be parsed.
@return {ElementTree}		The XML document.

This method parses the xml file provided .


function Config(file) {
		this._file = file;
		this._doc = _this.parse(file);
		this._root = this._doc.getroot();
	}

function Config ( file ) { this . _file = file ; this . _doc = _this . parse ( file ) ; this . _root = this . _doc . getroot ( ) ; }

Creates a new Config object.

@param {string}	file		The path to the XML config file.


function captureStream(name, callback) {
  var stream = process[name];
  var originalWrite = stream.write;

  stream.write = function(str) {
    callback(name, str);
  };

  return {
    restore: function() {
      stream.write = originalWrite;
    }
  };
}

function captureStream ( name , callback ) { var stream = process [ name ] ; var originalWrite = stream . write ; stream . write = function ( str ) { callback ( name , str ) ; } ; return { restore : function ( ) { stream . write = originalWrite ; } } ; }

Captures a specific stream, and invokes the specified callback with the text written to the stream instead. It returns a function that can be used to restore the captured stream.

Captures a specific stream and invokes the specified callback with the text written to the stream instead . It returns a function that can be used to restore the captured stream .


function messageHandler() {
  var message = messages.read(arguments, _session.signer);
  if (!message) {
    return;
  }

  var handler = _session.handlers[message.header.msg_type];
  if (handler) {
    handler(message);
  }
}

function messageHandler ( ) { var message = messages . read ( arguments , _session . signer ) ; if ( ! message ) { return ; } var handler = _session . handlers [ message . header . msg_type ] ; if ( handler ) { handler ( message ) ; } }

The default message handler for both the Shell and Control sockets. This dispatches the message to the appropriate message handler, based on the type of the message.

The default message handler for both the Shell and Control sockets . This dispatches the message to the appropriate message handler based on the type of the message .


function runSession(evaluator, config) {
  _session.signer = signers.create(config.signature_scheme, config.key);
  _session.io = createSocket('pub', config.ip, config.iopub_port);
  _session.shell = createSocket('xrep', config.ip, config.shell_port, messageHandler);
  _session.control = createSocket('xrep', config.ip, config.control_port, messageHandler);

  _session.evaluator = evaluator;
  _session.handlers = handlers.create(_session);

  createSocket('rep', config.ip, config.hb_port, heartbeatHandler);
}

function runSession ( evaluator , config ) { _session . signer = signers . create ( config . signature_scheme , config . key ) ; _session . io = createSocket ( 'pub' , config . ip , config . iopub_port ) ; _session . shell = createSocket ( 'xrep' , config . ip , config . shell_port , messageHandler ) ; _session . control = createSocket ( 'xrep' , config . ip , config . control_port , messageHandler ) ; _session . evaluator = evaluator ; _session . handlers = handlers . create ( _session ) ; createSocket ( 'rep' , config . ip , config . hb_port , heartbeatHandler ) ; }

Runs the session by creating the sockets, and sets up message handlers.

Runs the session by creating the sockets and sets up message handlers .


function inspectCommand(shell, args, data, evaluationId) {
  if (args.names) {
    args.names.forEach(function(n) {
      console.log(n + ':');
      console.dir(shell.state[n]);
      console.log();
    });
  }
}

function inspectCommand ( shell , args , data , evaluationId ) { if ( args . names ) { args . names . forEach ( function ( n ) { console . log ( n + ':' ) ; console . dir ( shell . state [ n ] ) ; console . log ( ) ; } ) ; } }

Implements the %inspect command This command can be used to inspect a variable, or expression within the shell.

Implements the %inspect command This command can be used to inspect a variable or expression within the shell .


function addMessage(message) {
  var text = message.content ? message.content.code.trim() : '';
  if (!text) {
    return;
  }

  message.content.code = text;
  _messages.push(message);

  // If there is no message already being processed, go ahead and process this message
  // immediately.
  if (_idle) {
    processNextMessage();
  }
}


function textCommand(shell, args, data, evaluationId) {
  return dataCommand(shell, args, data, evaluationId, function(value) {
    return value;
  });
}

function textCommand ( shell , args , data , evaluationId ) { return dataCommand ( shell , args , data , evaluationId , function ( value ) { return value ; } ) ; }

Implements the %%text command. This command can be used to initialize a string variable containing a span of literal text. The text does not have to be specified as a string, i.e. quoted and escaped.

Implements the %%text command . This command can be used to initialize a string variable containing a span of literal text . The text does not have to be specified as a string i . e . quoted and escaped .


function jsonCommand(shell, args, data, evaluationId) {
  return dataCommand(shell, args, data, evaluationId, function(value) {
    return JSON.parse(value);
  });
}

function jsonCommand ( shell , args , data , evaluationId ) { return dataCommand ( shell , args , data , evaluationId , function ( value ) { return JSON . parse ( value ) ; } ) ; }

Implements the %%json command. This command can be used to initialize a variable containing a plain old javascript object parsed from JSON text.

Implements the %%json command . This command can be used to initialize a variable containing a plain old javascript object parsed from JSON text .


function createGlobals(shell) {
  var globals = {
    Buffer: Buffer,
    console: console,
    clearImmediate: clearImmediate,
    clearInterval: clearInterval,
    clearTimeout: clearTimeout,
    setImmediate: setImmediate,
    setInterval: setInterval,
    setTimeout: setTimeout,
    _: ijsrt
  };

  globals.global = globals;

  return globals;
}

function createGlobals ( shell ) { var globals = { Buffer : Buffer , console : console , clearImmediate : clearImmediate , clearInterval : clearInterval , clearTimeout : clearTimeout , setImmediate : setImmediate , setInterval : setInterval , setTimeout : setTimeout , _ : ijsrt } ; globals . global = globals ; return globals ; }

Creates the global objects variables that serves as the initial state managed by the shell.

Creates the global objects variables that serves as the initial state managed by the shell .


function Shell(config) {
  this.config = config;
  this.commands = {};
  this.runtime = ijsrt;
  this.state = vm.createContext(createGlobals(this));
  this.code = '';

  require('../../node_modules/tern/plugin/node.js');
  var ternOptions = {
    defs: [require('../../node_modules/tern/defs/ecma5.json')],
    plugins: { node: {} }
  };
  this.ternServer = new tern.Server(ternOptions);
}

The Shell object to manage configuration, shell functionality and session state.

The Shell object to manage configuration shell functionality and session state .


function createShell(config, callback) {
  var shell = new Shell(config);

  modules.initialize(shell);
  extensions.initialize(shell);

  require('./commands').initialize(shell);
  require('./displayCommands').initialize(shell);
  require('./dataCommands').initialize(shell);

  process.nextTick(function() {
    callback(shell);
  });
}

function createShell ( config , callback ) { var shell = new Shell ( config ) ; modules . initialize ( shell ) ; extensions . initialize ( shell ) ; require ( './commands' ) . initialize ( shell ) ; require ( './displayCommands' ) . initialize ( shell ) ; require ( './dataCommands' ) . initialize ( shell ) ; process . nextTick ( function ( ) { callback ( shell ) ; } ) ; }

Creates and initializes a Shell object .


function moduleCommand(shell, args, data, evaluationId) {
  var deferred = shell.runtime.q.defer();

  installer.install(args.name, shell.config.userPath, /* quiet */ false, function(error) {
    if (error) {
      deferred.reject(shell.createError('Could not install module'));
    }
    else {
      shell.installedModules[args.name] = true;
      deferred.resolve();
    }
  });

  return deferred.promise;
}

function
moduleCommand
(
shell
,
args
,
data
,
evaluationId
)
{
var
deferred
=
shell
.
runtime
.
q
.
defer
(
)
;
installer
.
install
(
args
.
name
,
shell
.
config
.
userPath
,
/* quiet */
false
,
function
(
error
)
{
if
(
error
)
{
deferred
.
reject
(
shell
.
createError
(
'Could not install module'
)
)
;
}
else
{
shell
.
installedModules
[
args
.
name
]
=
true
;
deferred
.
resolve
(
)
;
}
}
)
;
return
deferred
.
promise
;
}

Implements the %module command, that can be used to install a specific named module, using npm. The module gets installed into 'node_modules' within the path specified in configuration.

Implements the %module command that can be used to install a specific named module using npm . The module gets installed into node_modules within the path specified in configuration .


function modulesCommand(shell, args, data, evaluationId) {
  var names = [];
  for (var n in shell.installedModules) {
    names.push(n);
  }

  console.log(names.join('\n'));
}

function modulesCommand ( shell , args , data , evaluationId ) { var names = [ ] ; for ( var n in shell . installedModules ) { names . push ( n ) ; } console . log ( names . join ( '\n' ) ) ; }

Implements the %modules command, that can be used to list the names of installed modules.

Implements the %modules command that can be used to list the names of installed modules .


function initialize(shell) {
  shell.requiredModules = {};
  shell.installedModules = {};

  shell.state.require = function(name) {
    return customRequire(shell, name);
  };

  shell.registerCommand('module', moduleCommand);
  shell.registerCommand('modules', modulesCommand);
}

function initialize ( shell ) { shell . requiredModules = { } ; shell . installedModules = { } ; shell . state . require = function ( name ) { return customRequire ( shell , name ) ; } ; shell . registerCommand ( 'module' , moduleCommand ) ; shell . registerCommand ( 'modules' , modulesCommand ) ; }

Initializes the shell with module related functionality. - The required and installed modules are tracked, and an implementation of a shell-scoped require is created. - The %module and %modules commands are also registered with the shell.

Initializes the shell with module related functionality . - The required and installed modules are tracked and an implementation of a shell - scoped require is created . - The %module and %modules commands are also registered with the shell .


function createMessage(identities, header, parentHeader, metadata, content) {
  return {
    identities: identities,
    header: header,
    parentHeader: parentHeader,
    metadata: metadata,
    content: content
  };
}

function createMessage ( identities , header , parentHeader , metadata , content ) { return { identities : identities , header : header , parentHeader : parentHeader , metadata : metadata , content : content } ; }

Helper method to create a message object from its independent pieces.

Helper method to create a message object from its independent pieces .


function createKernelInfoResponseMessage(parentMessage) {
  var content = {
    language: 'javascript',
    language_version: [1,0],
    protocol_version: [4,1]
  };
  return newMessage(_messageNames.kernelInfoResponse, parentMessage, content);
}

function createKernelInfoResponseMessage ( parentMessage ) { var content = { language : 'javascript' , language_version : [ 1 , 0 ] , protocol_version : [ 4 , 1 ] } ; return newMessage ( _messageNames . kernelInfoResponse , parentMessage , content ) ; }

Creates a kernel info response message .


function createExecuteErrorResponseMessage(parentMessage, executionCount, error, traceback) {
  var content = {
    status: 'error',
    execution_count: executionCount,
    ename: error.constructor.name,
    evalue: error.toString(),
    traceback: traceback
  };

  return newMessage(_messageNames.executeResponse, parentMessage, content);
}

function createExecuteErrorResponseMessage ( parentMessage , executionCount , error , traceback ) { var content = { status : 'error' , execution_count : executionCount , ename : error . constructor . name , evalue : error . toString ( ) , traceback : traceback } ; return newMessage ( _messageNames . executeResponse , parentMessage , content ) ; }

Creates an error execution reply message.

Creates an error execution reply message .


function createExecuteSuccessResponseMessage(parentMessage, executionCount, metadata) {
  var content = {
    status: 'ok',
    execution_count: executionCount,
    payload: [],
    user_variables: {},
    user_expressions: {}
  };

  return newMessage(_messageNames.executeResponse, parentMessage, content, metadata);
}

function createExecuteSuccessResponseMessage ( parentMessage , executionCount , metadata ) { var content = { status : 'ok' , execution_count : executionCount , payload : [ ] , user_variables : { } , user_expressions : { } } ; return newMessage ( _messageNames . executeResponse , parentMessage , content , metadata ) ; }

Creates a success execution reply message.

Creates a success execution reply message .


function createCompleteInfoResponseMessage(parentMessage, matchedText, matches, metadata) {
  var content = {
    status: 'ok',
    matched_text: matchedText,
    matches: matches
  };

  return newMessage(_messageNames.completeResponse, parentMessage, content, metadata);
}

function createCompleteInfoResponseMessage ( parentMessage , matchedText , matches , metadata ) { var content = { status : 'ok' , matched_text : matchedText , matches : matches } ; return newMessage ( _messageNames . completeResponse , parentMessage , content , metadata ) ; }


function createDataMessage(parentMessage, representations) {
  var content = {
    data: representations
  };

  return newMessage(_messageNames.displayData, parentMessage, content);
}

function createDataMessage ( parentMessage , representations ) { var content = { data : representations } ; return newMessage ( _messageNames . displayData , parentMessage , content ) ; }

Creates a display data message for sending results of an execution.

Creates a display data message for sending results of an execution .


function readMessage(socketData, signer) {
  var identities = socketData[0];
  var signature = socketData[2].toString();
  var header = socketData[3];
  var parentHeader = socketData[4];
  var metadata = socketData[5];
  var content = socketData[6];

  if (!signer.validate(signature, [ header, parentHeader, metadata, content ])) {
    return null;
  }

  return createMessage(identities,
                       JSON.parse(header),
                       JSON.parse(parentHeader),
                       JSON.parse(metadata),
                       JSON.parse(content));
}

function readMessage ( socketData , signer ) { var identities = socketData [ 0 ] ; var signature = socketData [ 2 ] . toString ( ) ; var header = socketData [ 3 ] ; var parentHeader = socketData [ 4 ] ; var metadata = socketData [ 5 ] ; var content = socketData [ 6 ] ; if ( ! signer . validate ( signature , [ header , parentHeader , metadata , content ] ) ) { return null ; } return createMessage ( identities , JSON . parse ( header ) , JSON . parse ( parentHeader ) , JSON . parse ( metadata ) , JSON . parse ( content ) ) ; }

Helper to read in a message from incoming message data.

Helper to read in a message from incoming message data .


function writeMessage(message, socket, signer) {
  var header = JSON.stringify(message.header);
  var parentHeader = JSON.stringify(message.parentHeader);
  var metadata = JSON.stringify(message.metadata);
  var content = JSON.stringify(message.content);

  var signature = signer.sign([ header, parentHeader, metadata, content ]);

  var socketData = [
    message.identities,
    '<IDS|MSG>',
    signature,
    header,
    parentHeader,
    metadata,
    content
  ];
  socket.send(socketData);
}

function writeMessage ( message , socket , signer ) { var header = JSON . stringify ( message . header ) ; var parentHeader = JSON . stringify ( message . parentHeader ) ; var metadata = JSON . stringify ( message . metadata ) ; var content = JSON . stringify ( message . content ) ; var signature = signer . sign ( [ header , parentHeader , metadata , content ] ) ; var socketData = [ message . identities , '<IDS|MSG>' , signature , header , parentHeader , metadata , content ] ; socket . send ( socketData ) ; }

Helper to write out a message to as outgoing message data.

Helper to write out a message to as outgoing message data .


function htmlCommand(shell, args, data, evaluationId) {
  return shell.runtime.data.html(data);
}

function htmlCommand ( shell , args , data , evaluationId ) { return shell . runtime . data . html ( data ) ; }

Implements the %%html command. This command simply converts the specified text into an object that is rendered as HTML.

Implements the %%html command . This command simply converts the specified text into an object that is rendered as HTML .


function scriptCommand(shell, args, data, evaluationId) {
  return shell.runtime.data.script(data);
}

function scriptCommand ( shell , args , data , evaluationId ) { return shell . runtime . data . script ( data ) ; }

Implements the %%script command. This command can be used to execute script on the client, instead of on the server.

Implements the %%script command . This command can be used to execute script on the client instead of on the server .


function kernelInfoHandler(message) {
  var infoMessage = messages.kernelInfoResponse(message);
  messages.write(infoMessage, _session.shell, _session.signer);
}

function kernelInfoHandler ( message ) { var infoMessage = messages . kernelInfoResponse ( message ) ; messages . write ( infoMessage , _session . shell , _session . signer ) ; }

Handles the kernel info request to produce a kernel info response.

Handles the kernel info request to produce a kernel info response .


function createHandlers(session) {
  _session = session;
  _queue = queue.create(session);

  var handlers = {};
  handlers[messages.names.kernelInfoRequest] = kernelInfoHandler;
  handlers[messages.names.shutdownRequest] = shutdownHandler;
  handlers[messages.names.executeRequest] = executeHandler;
  handlers[messages.names.completeRequest] = completeHandler;

  return handlers;
}

function createHandlers ( session ) { _session = session ; _queue = queue . create ( session ) ; var handlers = { } ; handlers [ messages . names . kernelInfoRequest ] = kernelInfoHandler ; handlers [ messages . names . shutdownRequest ] = shutdownHandler ; handlers [ messages . names . executeRequest ] = executeHandler ; handlers [ messages . names . completeRequest ] = completeHandler ; return handlers ; }

Creates the message handlers associated with the kernel session.

Creates the message handlers associated with the kernel session .


function setupOutline() {
  var markup = '<select id="tocDropDown" style="float: right"><option>Outline</option></select>';
  IPython.toolbar.element.append(markup);

  var tocDropDown = $('#tocDropDown');
  tocDropDown.change(function(e) {
    var index = tocDropDown.val();
    if (index.length === '') {
      return false;
    }

    var scrollTop = IPython.notebook.get_cell(0).element.position().top -
                    IPython.notebook.get_cell(parseInt(index)).element.position().top;
    IPython.notebook.element.animate({ scrollTop: -scrollTop }, 250, 'easeInOutCubic');

    tocDropDown.blur();
    tocDropDown.find('option').get(0).selected = true;

    return false;
  });

  function createOption(title, value, level) {
    var prefix = level > 1 ? new Array(level + 1).join('  ') : '';
    var text = prefix + IPython.utils.escape_html(title);

    return '<option value="' + value + '">' + text + '</option>';
  }

  function updateOutline() {
    var content = [];
    content.push(createOption('Table of Contents', '', 0));

    var cells = IPython.notebook.get_cells();
    cells.forEach(function(c, i) {
      if ((c.cell_type == 'heading') && (c.level <= 3)) {
        var cell = $(c.element);
        var header = cell.find('h' + c.level);

        // Retrieve the title and strip off the trailing paragraph marker
        var title = header.text();
        title = title.substring(-1, title.length - 1);

        if (title == 'Type Heading Here') {
          // New cells have this placeholder text in them
          return;
        }

        content.push(createOption(title, i, c.level));
      }
    });

    var markup = content.join('');
    tocDropDown.html(markup);
  }

  updateOutline();
  $([IPython.events]).on('set_dirty.Notebook', function(event, data) {
    updateOutline();
  });
  $([IPython.events]).on('command_mode.Cell', function(event, data) {
    updateOutline();
  });
}


function main() {
  var parser = nomnom();
  parser.script('ijs')
        .nocolors()
        .printer(function(s, code) {
          console.log(s);
          if (code) {
            process.exit(code);
          }
        })
        .option('version', {
          abbr: 'v',
          flag: true,
          help: 'print version and exit',
          callback: function() {
            console.log('0.1.0');
            process.exit(0);
          }
        })
        .option('userPath', {
          abbr: 'u',
          full: 'userPath',
          metavar: 'path',
          type: 'string',
          required: true,
          help: 'path that will contain installed node modules',
          callback: function(userPath) {
            if (!fs.existsSync(userPath) || !fs.statSync(userPath).isDirectory()) {
              return 'expected an existing directory for the userPath option';
            }
            return null;
          }
        })
        .option('connectionFile', {
          position: 0,
          required: true,
          help: 'path to file containing kernel connection information'
        });
  var options = parser.parse(process.argv.slice(2));

  if (options) {
    var shellConfig = {
      userPath: options.userPath
    };

    var connectionConfig = JSON.parse(fs.readFileSync(options.connectionFile,
                                                      { encoding: 'utf8' }));

    Shell.create(shellConfig, function(shell) {
      Session.run(shell, connectionConfig);
    });
  }
}

The main method which parses input arguments, creates a Shell providing evaluation functionality and the Session object to handle the kernel protocol.

The main method which parses input arguments creates a Shell providing evaluation functionality and the Session object to handle the kernel protocol .


function computeSignature(values, signatureScheme, signatureKey) {
  var hmac = crypto.createHmac(signatureScheme, signatureKey);
  values.forEach(function(v) {
    hmac.update(v);
  });

  return hmac.digest('hex');
}

function computeSignature ( values , signatureScheme , signatureKey ) { var hmac = crypto . createHmac ( signatureScheme , signatureKey ) ; values . forEach ( function ( v ) { hmac . update ( v ) ; } ) ; return hmac . digest ( 'hex' ) ; }

A helper function to compute a signature using an hmac object.

A helper function to compute a signature using an hmac object .


function createSigner(signatureScheme, signatureKey) {
  if (signatureKey) {
    // Create a SHA256-based signer that generates and validates signatures
    signatureScheme = signatureScheme || 'sha256';
    if (signatureScheme.indexOf('hmac-') === 0) {
      signatureScheme = signatureScheme.substr(5);
    }
    return {
      sign: function(values) {
        return computeSignature(values, signatureScheme, signatureKey);
      },
      validate: function(signature, values) {
        return signature === computeSignature(values, signatureScheme, signatureKey);
      }
    }
  }
  else {
    // Create a no-op signer
    return {
      sign: function() { return ''; },
      validate: function() { return true; }
    }
  }
}

Creates a signer given the specified schema and key.

Creates a signer given the specified schema and key .


function createError() {
  var e = new Error(util.format.apply(null, arguments));
  e.trace = false;

  return e;
}

function createError ( ) { var e = new Error ( util . format . apply ( null , arguments ) ) ; e . trace = false ; return e ; }

Create Error objects with their trace suppressed. This is useful for generating error message responses within the shell.

Create Error objects with their trace suppressed . This is useful for generating error message responses within the shell .


function extensionCommand(shell, args, data, evaluationId) {
  var deferred = shell.runtime.q.defer();

  var name = args.name;
  var moduleName = 'ijs.ext.' + name;
  var modulePath = args.path || moduleName;

  installer.install(modulePath, shell.config.userPath, /* quiet */ true, function(error) {
    if (error) {
      deferred.reject(shell.createError('Unable to install extension module "%s"', moduleName));
    }
    else {
      var extensionPath = path.join(shell.config.userPath, 'node_modules', moduleName);
      var extension = require(extensionPath);

      try {
        extension.initialize(shell, function(error, result) {
          if (error) {
            deferred.reject(shell.createError('Error initializing extension'));
          }
          else {
            shell.loadedExtensions[name] = true;
            deferred.resolve(result);
          }
        });
      }
      catch(e) {
        deferred.reject(shell.createError('Error initializing extension'));
      }
    }
  })

  return deferred.promise;
}

Implements the %extension command, that can be used to install a specific named module as a shell extension, using npm.

Implements the %extension command that can be used to install a specific named module as a shell extension using npm .


function extensionsCommand(shell, args, data, evaluationId) {
  var names = [];
  for (var n in shell.loadedExtensions) {
    names.push(n);
  }

  console.log(names.join('\n'));
}

function extensionsCommand ( shell , args , data , evaluationId ) { var names = [ ] ; for ( var n in shell . loadedExtensions ) { names . push ( n ) ; } console . log ( names . join ( '\n' ) ) ; }

Implements the %extensions command, that can be used to list the names of loaded extensions.

Implements the %extensions command that can be used to list the names of loaded extensions .


function initialize(shell) {
  shell.loadedExtensions = {};

  shell.registerCommand('extension', extensionCommand);
  shell.registerCommand('extensions', extensionsCommand);
}

function initialize ( shell ) { shell . loadedExtensions = { } ; shell . registerCommand ( 'extension' , extensionCommand ) ; shell . registerCommand ( 'extensions' , extensionsCommand ) ; }

Initializes the shell with extensions related functionality.

Initializes the shell with extensions related functionality .


function (dest) {
        if (grunt.util._.endsWith(dest, '/') || grunt.util._.endsWith(dest, '\\')) {
            return 'directory';
        } else {
            return 'file';
        }
    }

function ( dest ) { if ( grunt . util . _ . endsWith ( dest , '/' ) || grunt . util . _ . endsWith ( dest , '\\' ) ) { return 'directory' ; } else { return 'file' ; } }

Get type of destination path
@param {string} dest
@returns {string} directory|file


function findFile(name, dir) {
        dir = dir || process.cwd();

        var filename = path.normalize(path.join(dir, name));
        if (findFileResults[filename] !== undefined) {
            return findFileResults[filename];
        }

        var parent = path.resolve(dir, "../");

        if (shjs.test("-e", filename)) {
            findFileResults[filename] = filename;
            return filename;
        }

        if (dir === parent) {
            findFileResults[filename] = null;
            return null;
        }

        return findFile(name, parent);
    }

function findFile ( name , dir ) { dir = dir || process . cwd ( ) ; var filename = path . normalize ( path . join ( dir , name ) ) ; if ( findFileResults [ filename ] !== undefined ) { return findFileResults [ filename ] ; } var parent = path . resolve ( dir , "../" ) ; if ( shjs . test ( "-e" , filename ) ) { findFileResults [ filename ] = filename ; return filename ; } if ( dir === parent ) { findFileResults [ filename ] = null ; return null ; } return findFile ( name , parent ) ; }

Searches for a file with a specified name starting with
'dir' and going all the way up either until it finds the file
or hits the root.

copied from
https://github.com/jshint/jshint/blob/master/src/cli.js

@param {string} name filename to search for (e.g. .jshintrc)
@param {string} dir  directory to start search from (default:
current working directory)

@returns {string} normalized filename

Searches for a file with a specified name starting with dir and going all the way up either until it finds the file or hits the root .


function (view, offset, length) {
            var trmOffset = lib.locateStrTrm.iso(view, offset, length);
            if (trmOffset !== -1) { length = trmOffset - offset; }
            return lib.readStr.iso(view, offset, length);
        }

function ( view , offset , length ) { var trmOffset = lib . locateStrTrm . iso ( view , offset , length ) ; if ( trmOffset !== - 1 ) { length = trmOffset - offset ; } return lib . readStr . iso ( view , offset , length ) ; }

Similar to `readStr.iso` but will check for a null-terminator determining the end of the string. The returned string will be of _at most_ `length` octets

Similar to readStr . iso but will check for a null - terminator determining the end of the string . The returned string will be of _at most_ length octets


function (view, offset, length) {
            var trmOffset = lib.locateStrTrm.ucs(view, offset, length);
            if (trmOffset !== -1) { length = trmOffset - offset; }
            return lib.readStr.ucs(view, offset, length);
        }

function ( view , offset , length ) { var trmOffset = lib . locateStrTrm . ucs ( view , offset , length ) ; if ( trmOffset !== - 1 ) { length = trmOffset - offset ; } return lib . readStr . ucs ( view , offset , length ) ; }

Similar to `readStr.ucs` but will check for a null-terminator determining the end of the string. The returned string will be of _at most_ `length` octets

Similar to readStr . ucs but will check for a null - terminator determining the end of the string . The returned string will be of _at most_ length octets


function Mailto(form, options){
  /**
   *
   * @type {HTMLElement}
   */
  this.form = null;

  /**
   *
   * @type {boolean}
   */
  this.preventDefault = true;

  /**
   *
   * @type {Function}
   */
  this.formatter = Mailto.defaultFormatter;

  /**
   *
   * @type {Function}
   */
  this.onSubmit = function(m){};

  this.initFormObject(form);
  this.initOptions(options);
  this.initFormHandler();
}

Mailto Constructor.

@param {HTMLElement|String} form
@param {Object=} options
@constructor


function getMailtoUrl(to, fields){
    this.form.action.match(/mailto:([^\?&]+)/);

    to = to || RegExp.$1 || '';
    fields = fields || {
      subject: this.form.getAttribute('data-subject') || '',
      body: this.getBody()
    };

    if (!to && !fields.to){
      throw new Error('Could not find any person to send an email to.');
    }

    return 'mailto:'+to+'?'+Object.keys(fields).reduce(function(a, b, i){
      return a +
        (i > 0 ? '&' : '') +
        encodeURIComponent(b) + '=' +
        encodeURIComponent(fields[b]).replace(/%0A(?!%)/g, '%0D%0A') +    // fixing *nix line break encoding to follow RFC spec
        (b === 'body' ? '%0D%0A' : '')
    }, '');
  }

Returns an hyperlinkable representation of the form values.

@api
@return {String}

Returns an hyperlinkable representation of the form values .