function getFormData(){
    var form = this.form;
    var selector = ['input', 'select', 'textarea'].join(',');

    return [].slice.call(form.querySelectorAll(selector))
      .filter(Mailto.formDataFilter)
      .map(Mailto.formDataMapper(form));
  }

function getFormData ( ) { var form = this . form ; var selector = [ 'input' , 'select' , 'textarea' ] . join ( ',' ) ; return [ ] . slice . call ( form . querySelectorAll ( selector ) ) . filter ( Mailto . formDataFilter ) . map ( Mailto . formDataMapper ( form ) ) ; }

Returns the filtered values of a form.

They are basically:
- for named options
- one entry per input/checked/selected option (even if they have the same name)

@api
@returns {Array.<{name: String, label: String, value: String|Boolean|Number}>}


function getData(){
    var data = {};

    this.getFormData().forEach(function(d){
      if (Array.isArray(data[d.name])){
        data[d.name].push(d.value);
      }
      else if (data[d.name] !== undefined){
        data[d.name] = [data[d.name], d.value];
      }
      else {
        data[d.name] = d.value;
      }
    });

    return data;
  }

function getData ( ) { var data = { } ; this . getFormData ( ) . forEach ( function ( d ) { if ( Array . isArray ( data [ d . name ] ) ) { data [ d . name ] . push ( d . value ) ; } else if ( data [ d . name ] !== undefined ) { data [ d . name ] = [ data [ d . name ] , d . value ] ; } else { data [ d . name ] = d . value ; } } ) ; return data ; }

Returns an aggregated object of form values.

If form fields has the same name, their value will be aggregated as an array for this given name.

@api
@returns {Object}

Returns an aggregated object of form values .


function getSerialisedData(){
    var data = this.getFormData();

    return data.length === 0 ? '' : '?' + data.map(function(f){
      return encodeURIComponent(f.name) + '=' + encodeURIComponent(f.value);
    }).join('&');
  }

function getSerialisedData ( ) { var data = this . getFormData ( ) ; return data . length === 0 ? '' : '?' + data . map ( function ( f ) { return encodeURIComponent ( f . name ) + '=' + encodeURIComponent ( f . value ) ; } ) . join ( '&' ) ; }

Returns a GET-like serialisation string of the form values.

@api
@returns {string}

Returns a GET - like serialisation string of the form values .


function registerXDiv() {
  // Create our 'x-div' Web Component Prototype
  var xProto = Object.create(HTMLElement.prototype);

  // Create methods for its lifecycle
  xProto.attachedCallback = function () {
    var scriptEl = document.createElement('script');

    if (!this.dataset.controller) {
      console.error('No controller specified for x-div.');
      return;
    }

    scriptEl.src = getControllerSrc(this.dataset.controller);
    scriptEl.async = true;
    this.appendChild(scriptEl);
  };

  // Register the Element
  document.registerElement('x-div', {
    prototype: xProto
  });
}

Registers the `x-div` HTMLElement
@method registerXDiv
@return {void}


function processCondition(condition, errorMessage) {
  if (!condition) {
    var completeErrorMessage = '';
    var re = /at ([^\s]+)\s\(/g;
    var stackTrace = new Error().stack;
    var stackFunctions = [];

    var funcName = re.exec(stackTrace);
    while (funcName && funcName[1]) {
      stackFunctions.push(funcName[1]);
      funcName = re.exec(stackTrace);
    }

    // Number 0 is processCondition itself,
    // Number 1 is assert,
    // Number 2 is the caller function.
    if (stackFunctions[2]) {
      completeErrorMessage = stackFunctions[2] + ': ' + completeErrorMessage;
    }

    completeErrorMessage += errorMessage;
    return completeErrorMessage;
  }

  return null;
}

function
processCondition
(
condition
,
errorMessage
)
{
if
(
!
condition
)
{
var
completeErrorMessage
=
''
;
var
re
=
/
at ([^\s]+)\s\(
/
g
;
var
stackTrace
=
new
Error
(
)
.
stack
;
var
stackFunctions
=
[
]
;
var
funcName
=
re
.
exec
(
stackTrace
)
;
while
(
funcName
&&
funcName
[
1
]
)
{
stackFunctions
.
push
(
funcName
[
1
]
)
;
funcName
=
re
.
exec
(
stackTrace
)
;
}
// Number 0 is processCondition itself,
// Number 1 is assert,
// Number 2 is the caller function.
if
(
stackFunctions
[
2
]
)
{
completeErrorMessage
=
stackFunctions
[
2
]
+
': '
+
completeErrorMessage
;
}
completeErrorMessage
+=
errorMessage
;
return
completeErrorMessage
;
}
return
;
}

Bug checking function that will throw an error whenever the condition sent to it is evaluated to false
Processes the message and outputs the correct message if the condition
is false. Otherwise it outputs null.
@api private
@method processCondition
@param  {Boolean} condition - Result of the evaluated condition
@param  {String} errorMessage - Message explainig the error in case it is thrown
@return {String | null}  - Error message if there is an error, nul otherwise.

Bug checking function that will throw an error whenever the condition sent to it is evaluated to false Processes the message and outputs the correct message if the condition is false . Otherwise it outputs null .


function Credulous(options) {
    var i
      ;
    if (!this) {
      return new Credulous(options);
    }

    options = validateOptions(options);

    this.labels = options.labels;
    this.dataLength = options.dataLength;
    // For the label
    this.trainArgumentsLength = this.dataLength + 1;

    // TODO: make the data store more modular
    this.dataStore = [];
    setUpDataStore(this.dataStore, this.labels, this.dataLength);
    this.instancesTrained = 0;
  }

Constructor for the Naive Bayes learner.
It takes a list of strings, which represent the different
groups of strings to train on, followed by an array of possible
classes.

@param options: object of options that set up the naive bayes model.
It *must* have a `label` property that is an array of possible labels to assign
to things we are classifying.
It can optionally have a `dataLength` that specifies how many groups of strings
we are classifying. This is useful if we are classifying things that have several
separate attributes that we want to compute probabilities for separately. For
example, when calssifying an email, we might have three separate things to classify
on: the text of the email, the text of the subject, and the country of origin in
the sender's address. In this case, we would set `dataLength` to 3, and pass these
in as three separate arguments to the `train()` method.

Constructor for the Naive Bayes learner . It takes a list of strings which represent the different groups of strings to train on followed by an array of possible classes .


function setUpDataStore(dataStore, labels, dataLength) {
    var i
      ;
    for (i = 0; i < dataLength; i++) {
      dataStore[i] = {
          words: {}
        , labels: {}
      };
      labels.forEach(function (label) {
        dataStore[i].labels[label] = 0;
      });
    }
  }

function setUpDataStore ( dataStore , labels , dataLength ) { var i ; for ( i = 0 ; i < dataLength ; i ++ ) { dataStore [ i ] = { words : { } , labels : { } } ; labels . forEach ( function ( label ) { dataStore [ i ] . labels [ label ] = 0 ; } ) ; } }


function argMax(array) {
    var maxIndex = 0
     , i
     ;
    for (i = 0; i < array.length; i++) {
      if (array[i] > array[maxIndex]) {
        maxIndex = i;
      }
    }
    return maxIndex;
  }

function argMax ( array ) { var maxIndex = 0 , i ; for ( i = 0 ; i < array . length ; i ++ ) { if ( array [ i ] > array [ maxIndex ] ) { maxIndex = i ; } } return maxIndex ; }

Return the index of the maximum value in the array.
@param array - an array of numerical values
@return the index of the largest value in the array.

Return the index of the maximum value in the array .


function processDataItems(items) {
    var processedItems = []
      ;

    // TODO: do stemming here
    items.forEach(function (item, i) {
      processedItems[i] = processString(item);
    });
    return processedItems;
  }

function
processDataItems
(
items
)
{
var
processedItems
=
[
]
;
// TODO: do stemming here
items
.
forEach
(
function
(
item
,
i
)
{
processedItems
[
i
]
=
processString
(
item
)
;
}
)
;
return
processedItems
;
}

This is terribly named. Process the array of strings into an
array of arrays of words, with them stemmed, etc.

This is terribly named . Process the array of strings into an array of arrays of words with them stemmed etc .


function addLabel(label, self) {
    if (!(label in self.labels)) {
      self.labels[label] = 1;
    }
    else {
      self.labels[label]++;
    }
  }

function addLabel ( label , self ) { if ( ! ( label in self . labels ) ) { self . labels [ label ] = 1 ; } else { self . labels [ label ] ++ ; } }

Add to the count of classes seen. Instantiate a new object to hold the
classes and counts if it has not been seen yet.

Add to the count of classes seen . Instantiate a new object to hold the classes and counts if it has not been seen yet .


function fromFile(filename, callback) {
  var configFile = filename || '../config/winston-config.json';

  fs.exists(configFile, function (exists) {
    if (exists) {
      var winstonConf = require(configFile).logging;

      fromJson(winstonConf, callback);
    } else {
      callback(new Error('No config file found (at least provide a config/winston-config.json) with winston configuration'), winston);
    }
  });
}

initialize Winston logging mechanism from file


function Debug(...rest) {
  if (new.target) {
    /**
     * @param id
     * @param stats
     * @param rest
     */
    this.debug = (id, stats, ...rest) => {
      debug(id)(...rest);
    };
    return;
  }
  return new Debug(...rest);
}


function log(ctx, start, len, err, event) {
  // get the status code of the response
  const status = err ? (err.status || 500) : (ctx.status || 404);

  // set the color of the status code;
  const s = status / 100 | 0;
  const color = colorCodes[s];

  // get the human readable response length
  let length;
  if (~[204, 205, 304].indexOf(status)) {
    length = "";
  } else if (null == len) {
    length = "-";
  } else {
    length = bytes(len);
  }

  const upstream = err ? chalk.red("xxx")
    : event === "end" ? chalk.yellow("-x-")
      : chalk.gray("-->");

  logger.debug(`${upstream} ${chalk.bold(ctx.method)} ${chalk.gray(ctx.originalUrl)} ${chalk[color](status)} ${chalk.gray(time(start))} ${chalk.gray(length)}`);
}


function sendMessage(id, level, fallbackToLog, ...rest) {
  const levelMethod = level.toLowerCase();
  const options = buildMessageOptions(id);
  const tagsToDisable = get(configRegistry, 'tags.disable', []);
  const namespaceTags = get(configRegistry, `namespaces.${id}.tags`, []);
  const containsDisabledTag = tagsToDisable.some((element) => {
    return namespaceTags.indexOf(element) > -1;
  });

  if (options.disable.indexOf(level) > -1 ||
    containsDisabledTag) {
    // if global or logger's setting is saying to disable logging, proceed silently
    if (!!configRegistry.verbose) {
      console.log(`Level ${level} or namespace ID ${id} has been disabled. skipping...`);
    }
    return;
  }

  const [, , stats, ...args] = applyPlugins(pluginsRegistry, id, level, calcStats(), ...rest);

  wrappers.concat(options.wrappers)
    .forEach((wrapper) => {
      const restOrArgs = equalsWrapperOptValue(wrapper, 'passInitialArguments', true) ? rest : args;
      const plugins = extractWrapperPlugins(wrapper);
      const [, , wrapperStats, ...wrapperArgs] = applyPlugins(plugins, id, level, stats, ...restOrArgs);

      if (typeof wrapper[levelMethod] === 'function') {
        // use specific logging method if exists, for example, wrapper.info()
        return wrapper[levelMethod](id, wrapperStats, ...wrapperArgs);
      } else if (typeof wrapper.log === 'function' && !!fallbackToLog) {
        // use generic log method, if fallbackToLog === true. It is always equal to TRUE for standard levels
        return wrapper.log(id, level, wrapperStats, ...wrapperArgs);
      }
      if (!!configRegistry.verbose) {
        console.log(`Wrapper has no valid logging method. fallbackToLog is equal ${fallbackToLog}. skipping...`);
      }
    });
}

Send log message to all available wrappers

@param {string} id
@param {string} level
@param {boolean} fallbackToLog
@param {[]} rest


function calcStats() {
  return {
    maxIdLength: Math.max(...Object.keys(loggers).map((l) => l.length))
  };
}

function calcStats ( ) { return { maxIdLength : Math . max ( ... Object . keys ( loggers ) . map ( ( l ) => l . length ) ) } ; }

Prepare stats. Currently only maxIdLength supported in core, can be extended
in custom plugin.

@return {{maxIdLength: number}}

Prepare stats . Currently only maxIdLength supported in core can be extended in custom plugin .


function createLogger(id) {
  let log = (level, fallbackToLog, ...rest) => sendMessage(id, level, fallbackToLog, ...rest);
  return {
    get id() {
      return id;
    },
    silly(...rest) {
      log(LEVELS.SILLY, true, ...rest);
    },
    debug(...rest) {
      log(LEVELS.DEBUG, true, ...rest);
    },
    info(...rest) {
      log(LEVELS.INFO, true, ...rest);
    },
    warn(...rest) {
      log(LEVELS.WARN, true, ...rest);
    },
    error(...rest) {
      log(LEVELS.ERROR, true, ...rest);
    },
    // CAUTION: experimental feature
    send(level, ...rest) {
      log(level, false, ...rest);
    }
  }
}

function
createLogger
(
id
)
{
let
log
=
(
level
,
fallbackToLog
,
...
rest
)
=>
sendMessage
(
id
,
level
,
fallbackToLog
,
...
rest
)
;
return
{
get
id
(
)
{
return
id
;
}
,
silly
(
...
rest
)
{
log
(
LEVELS
.
SILLY
,
true
,
...
rest
)
;
}
,
debug
(
...
rest
)
{
log
(
LEVELS
.
DEBUG
,
true
,
...
rest
)
;
}
,
info
(
...
rest
)
{
log
(
LEVELS
.
INFO
,
true
,
...
rest
)
;
}
,
warn
(
...
rest
)
{
log
(
LEVELS
.
WARN
,
true
,
...
rest
)
;
}
,
error
(
...
rest
)
{
log
(
LEVELS
.
ERROR
,
true
,
...
rest
)
;
}
,
// CAUTION: experimental feature
send
(
level
,
...
rest
)
{
log
(
level
,
false
,
...
rest
)
;
}
}
}

Create new logger instance

@param {string} id
@return {{id, silly: (function(...[*])), debug: (function(...[*])), info: (function(...[*])), warn: (function(...[*])), error: (function(...[*]))}}


function getLogger(id, { disable = [], wrappers = [], tags = [] } = {}) {
  let config = {
    disable: normalizeArray(disable).map(v => v + ''),
    wrappers: normalizeArray(wrappers),
    tags: normalizeArray(tags)
  };

  set(configRegistry, `namespaces.${id}`, deepmerge(get(configRegistry, `namespaces.${id}`, {}), config, deepMergeOptions));

  return loggers[id] || (loggers[id] = createLogger(id));
}

function getLogger ( id , { disable = [ ] , wrappers = [ ] , tags = [ ] } = { } ) { let config = { disable : normalizeArray ( disable ) . map ( v => v + '' ) , wrappers : normalizeArray ( wrappers ) , tags : normalizeArray ( tags ) } ; set ( configRegistry , ` ${ id } ` , deepmerge ( get ( configRegistry , ` ${ id } ` , { } ) , config , deepMergeOptions ) ) ; return loggers [ id ] || ( loggers [ id ] = createLogger ( id ) ) ; }

Get logger that exits or create new one

@param {String} id
@param {[]} disable
@param {[]} wrappers
@param {[]} tags
@returns {{silly: Function, debug: Function, info: Function, warn: Function, error: Function}}


function configure({ useGlobal = true, disable = [], namespaces = {}, tags = {}, verbose = false } = {}, override = false) {
  const config = Object.create(null);
  config.useGlobal = !!useGlobal;
  config.disable = normalizeArray(disable).map(v => v + '');
  config.namespaces = namespaces;
  config.tags = {
    disable: normalizeArray(get(tags, 'disable', []))
  };
  config.verbose = verbose;
  configRegistry = override ? config : deepmerge(configRegistry, config, deepMergeOptions);
}

function configure ( { useGlobal = true , disable = [ ] , namespaces = { } , tags = { } , verbose = false } = { } , override = false ) { const config = Object . create ( null ) ; config . useGlobal = ! ! useGlobal ; config . disable = normalizeArray ( disable ) . map ( v => v + '' ) ; config . namespaces = namespaces ; config . tags = { disable : normalizeArray ( get ( tags , 'disable' , [ ] ) ) } ; config . verbose = verbose ; configRegistry = override ? config : deepmerge ( configRegistry , config , deepMergeOptions ) ; }

Add global configs

@param {boolean} useGlobal
@param {[]} disable
@param {{}} namespaces
@param {{}} tags
@param {boolean} verbose
@param {boolean} override


function addPlugin(useLevel, fn) {
  let pluginFn = fn;
  if (typeof fn === 'undefined' && typeof useLevel === 'function') {
    pluginFn = useLevel;
  }

  if (typeof pluginFn !== 'function') {
    throw new Error('Plugin must be a function!');
  }

  if (typeof useLevel === 'string') {
    pluginFn = (id, level, stats, ...rest) => {
      if (level === useLevel.toUpperCase()) {
        return fn(id, level, stats, ...rest);
      }
      return [id, level, stats, ...rest];
    };
  }

  pluginsRegistry.push(pluginFn);
}

function
addPlugin
(
useLevel
,
fn
)
{
let
pluginFn
=
fn
;
if
(
typeof
fn
===
'undefined'
&&
typeof
useLevel
===
'function'
)
{
pluginFn
=
useLevel
;
}
if
(
typeof
pluginFn
!==
'function'
)
{
throw
new
Error
(
'Plugin must be a function!'
)
;
}
if
(
typeof
useLevel
===
'string'
)
{
pluginFn
=
(
id
,
level
,
stats
,
...
rest
)
=>
{
if
(
level
===
useLevel
.
toUpperCase
(
)
)
{
return
fn
(
id
,
level
,
stats
,
...
rest
)
;
}
return
[
id
,
level
,
stats
,
...
rest
]
;
}
;
}
pluginsRegistry
.
push
(
pluginFn
)
;
}

Add plugin function. Plugin function must return array with log argument values.

Add plugin function . Plugin function must return array with log argument values .


function(objects, options) {
          var self = this
          objects.forEach(function(object) {
            self.cache[object._id] = object
          })
          return objects
        }

function ( objects , options ) { var self = this objects . forEach ( function ( object ) { self . cache [ object . _id ] = object } ) return objects }


function(options) {
          var self = this
          var result = []
          if (options._id) {
            var id = Array.isArray(options._id) ? options._id : [options._id]
            id.forEach(function(id) {
              if (self.cache[id]) {
                result.push(self.cache[id])
              }
            })
          } else {
            result = Object.keys(this.cache).map(function(k) {
              return self.cache[k]
            }).sort(function(count1, count2) {
              return count1._id - count2._id
            })
            if (options.skip || options.limit) {
              var skip = options.skip || 0
              var limit = options.limit || 0
              return result.slice(skip, skip + limit)
            }
          }
          return result
        }

function ( options ) { var self = this var result = [ ] if ( options . _id ) { var id = Array . isArray ( options . _id ) ? options . _id : [ options . _id ] id . forEach ( function ( id ) { if ( self . cache [ id ] ) { result . push ( self . cache [ id ] ) } } ) } else { result = Object . keys ( this . cache ) . map ( function ( k ) { return self . cache [ k ] } ) . sort ( function ( count1 , count2 ) { return count1 . _id - count2 . _id } ) if ( options . skip || options . limit ) { var skip = options . skip || 0 var limit = options . limit || 0 return result . slice ( skip , skip + limit ) } } return result }


function(objects, options) {
          var idSet = new Set(objects.map(function(object) {
            return object._id
          }))
          if (idSet.length < objects.length) {
            throw new this.getService().errors.BadRequest('Duplicate IDs')
          }
          this.cache = objects
          return objects
        }

function
(
objects
,
options
)
{
var
idSet
=
new
Set
(
objects
.
map
(
function
(
object
)
{
return
object
.
_id
}
)
)
if
(
idSet
.
length
<
objects
.
length
)
{
throw
new
this
.
getService
(
)
.
errors
.
BadRequest
(
'Duplicate IDs'
)
}
this
.
cache
=
objects
return
objects
}

post - findObject - memCacheCounterAdvanced pre - save - memCacheCounterAdvanced


function(object, options) {
          var created = typeof this.cache[object._id] === 'undefined'
          this.cache[object._id] = object
          return {
            created: created,
            val: object
          }
        }

function ( object , options ) { var created = typeof this . cache [ object . _id ] === 'undefined' this . cache [ object . _id ] = object return { created : created , val : object } }

post - save - memCacheCounterAdvanced pre - saveObject - memCacheCounterAdvanced


function(update, options) {
          var count = 0
          for (var id in this.cache) {
            count += 1
            if (update.$inc) {
              this.cache[id].count += update.$inc
            } else {
              this.cache[id].count -= update.$dec
            }
          }
          return count
        }

function ( update , options ) { var count = 0 for ( var id in this . cache ) { count += 1 if ( update . $inc ) { this . cache [ id ] . count += update . $inc } else { this . cache [ id ] . count -= update . $dec } } return count }

post - updateConfig - memCacheCounterAdvanced pre - update - memCacheCounterAdvanced


function(options) {
          var objects = []
          for (var id in this.cache) {
            objects.push(this.cache[id])
          }
          this.cache = {}
          return objects
        }

function ( options ) { var objects = [ ] for ( var id in this . cache ) { objects . push ( this . cache [ id ] ) } this . cache = { } return objects }

post - removeConfig - memCacheCounterAdvanced pre - remove - memCacheCounterAdvanced


function(update, options) {
          var count = 0
          for (var id in this.cache) {
            this.cache[id].count += update.n
            count += 1
          }
          // demonstrate full return type
          return {val: count, created: false}
        }

function
(
update
,
options
)
{
var
count
=
0
for
(
var
id
in
this
.
cache
)
{
this
.
cache
[
id
]
.
count
+=
update
.
n
count
+=
1
}
// demonstrate full return type
return
{
val
:
count
,
created
:
false
}
}

post - updateConfig - memCacheCounterBasic pre - update - memCacheCounterBasic


function(object, options) {
          return this.collection.findOneAndReplace(
            {_id: object._id}, object, {returnOriginal: false}).value
        }

function ( object , options ) { return this . collection . findOneAndReplace ( { _id : object . _id } , object , { returnOriginal : false } ) . value }

post - save - mongoCounterBasic pre - saveObject - mongoCounterBasic


function addHandler(cls, replacer, reviver) {
	if (typeof cls !== "function") {
		throw new TypeError("'cls' must be class/function");
	}
	if (typeof replacer !== "function") {
		throw new TypeError("'replacer' must be function");
	}
	if (typeof reviver !== "function") {
		throw new TypeError("'reviver' must be function");
	}
	__handlers[cls.name] = {
		cls: cls,
		replacer: replacer,
		reviver: reviver
	};
}

function
addHandler
(
cls
,
replacer
,
reviver
)
{
if
(
typeof
cls
!==
"function"
)
{
throw
new
TypeError
(
"'cls' must be class/function"
)
;
}
if
(
typeof
replacer
!==
"function"
)
{
throw
new
TypeError
(
"'replacer' must be function"
)
;
}
if
(
typeof
reviver
!==
"function"
)
{
throw
new
TypeError
(
"'reviver' must be function"
)
;
}
__handlers
[
cls
.
name
]
=
{
cls
:
cls
,
replacer
:
replacer
,
reviver
:
reviver
}
;
}

Adds type handler
@param {*} cls
@param {Function} replacer
@param {Function} reviver


function ifStatusOk(response, fulfill, reject) {
    var responseCode = response.code;
    if (isClientError(responseCode)) {
        reject({name : "ClientErrorException", message : response.body});
    } else if (isServerError(responseCode)) {
        reject({name : "ServerErrorException", message : response.error});
    } else if (isOtherErrorResponse(responseCode)) {
        reject({name : "OtherCommunicationException", message : response.error});
    } else {
        fulfill(response.body)
    }
}

function ifStatusOk ( response , fulfill , reject ) { var responseCode = response . code ; if ( isClientError ( responseCode ) ) { reject ( { name : "ClientErrorException" , message : response . body } ) ; } else if ( isServerError ( responseCode ) ) { reject ( { name : "ServerErrorException" , message : response . error } ) ; } else if ( isOtherErrorResponse ( responseCode ) ) { reject ( { name : "OtherCommunicationException" , message : response . error } ) ; } else { fulfill ( response . body ) } }


function(endpoint, all) {
      if (!_.isNil(endpoint)) {
        all = _.assignIn(
          _.clone(allEndpointParameters(endpoint.parent, endpoint.parameters)),
          all || {})
      }
      return all
    }

function ( endpoint , all ) { if ( ! _ . isNil ( endpoint ) ) { all = _ . assignIn ( _ . clone ( allEndpointParameters ( endpoint . parent , endpoint . parameters ) ) , all || { } ) } return all }

First gather all Endpoint parameters, post-order walk

First gather all Endpoint parameters post - order walk


function AposGroups(options) {
  var self = this;

  aposSchemas.addFieldType({
    name: 'a2Permissions',
    displayer: function(snippet, name, $field, $el, field, callback) {
      _.each(apos.data.aposGroups.permissions, function(permission) {
        $el.findByName(permission.value).val(_.contains(snippet.permissions || [], permission.value) ? '1' : '0');
      });

      return callback();
    },
    converter: function(data, name, $field, $el, field, callback) {
      _.each(apos.data.aposGroups.permissions, function(permission) {
        data[permission.value] = $el.findByName(permission.value).val();
      });
      return callback();
    }
  });

  aposSchemas.addFieldType({
    name: 'a2People',
    displayer: function(snippet, name, $field, $el, field, callback) {
      var source = aposPages.getType('people')._action + '/autocomplete';
      $.jsonCall(source, {
        values: _.map(snippet.people || [], function(person) {
          return person._id;
        })
      }, function(results) {
        var labelMap = {};
        _.each(results, function(result) {
          labelMap[result.value] = result.label;
        });
        $el.find('[data-name="people"]').selective({
          sortable: options.peopleSortable,
          extras: field.extras,
          source: source,
          data: _.map(snippet._people || [], function(person) {
            var label = labelMap[person._id];
            var data = { label: label, value: person._id };
            if (person.groupExtras && person.groupExtras[snippet._id]) {
              $.extend(true, data, person.groupExtras[snippet._id]);
            }
            return data;
          })
        });
        return callback();
      });
    },
    converter: function(data, name, $field, $el, field, callback) {
      data._peopleInfo = $el.find('[data-name="people"]').selective('get', { incomplete: true });
      return callback();
    }
  });

  AposSnippets.call(self, options);

  self.addingToManager = function($el, $snippet, snippet) {
    $snippet.find('[data-published]').val(snippet.published ? 'Yes' : 'No');
  };
}

function AposGroups ( options ) { var self = this ; aposSchemas . addFieldType ( { name : 'a2Permissions' , displayer : function ( snippet , name , $field , $el , field , callback ) { _ . each ( apos . data . aposGroups . permissions , function ( permission ) { $el . findByName ( permission . value ) . val ( _ . contains ( snippet . permissions || [ ] , permission . value ) ? '1' : '0' ) ; } ) ; return callback ( ) ; } , converter : function ( data , name , $field , $el , field , callback ) { _ . each ( apos . data . aposGroups . permissions , function ( permission ) { data [ permission . value ] = $el . findByName ( permission . value ) . val ( ) ; } ) ; return callback ( ) ; } } ) ; aposSchemas . addFieldType ( { name : 'a2People' , displayer : function ( snippet , name , $field , $el , field , callback ) { var source = aposPages . getType ( 'people' ) . _action + '/autocomplete' ; $ . jsonCall ( source , { values : _ . map ( snippet . people || [ ] , function ( person ) { return person . _id ; } ) } , function ( results ) { var labelMap = { } ; _ . each ( results , function ( result ) { labelMap [ result . value ] = result . label ; } ) ; $el . find ( '[data-name="people"]' ) . selective ( { sortable : options . peopleSortable , extras : field . extras , source : source , data : _ . map ( snippet . _people || [ ] , function ( person ) { var label = labelMap [ person . _id ] ; var data = { label : label , value : person . _id } ; if ( person . groupExtras && person . groupExtras [ snippet . _id ] ) { $ . extend ( true , data , person . groupExtras [ snippet . _id ] ) ; } return data ; } ) } ) ; return callback ( ) ; } ) ; } , converter : function ( data , name , $field , $el , field , callback ) { data . _peopleInfo = $el . find ( '[data-name="people"]' ) . selective ( 'get' , { incomplete : true } ) ; return callback ( ) ; } } ) ; AposSnippets . call ( self , options ) ; self . addingToManager = function ( $el , $snippet , snippet ) { $snippet . find ( '[data-published]' ) . val ( snippet . published ? 'Yes' : 'No' ) ; } ; }

JavaScript which enables editing of this module's content belongs here.

JavaScript which enables editing of this module s content belongs here .


function(p){
          var isRollLeft = roll==null || roll.getDepth()>=1

          if(roll){
            roll.up()
          }

          if(isRollLeft){
            next()
          }else{
            callback(null, null, resultStatus)//could not be found
            //fail()
          }
        }

function
(
p
)
{
var
isRollLeft
=
roll
==
||
roll
.
getDepth
(
)
>=
1
if
(
roll
)
{
roll
.
up
(
)
}
if
(
isRollLeft
)
{
next
(
)
}
else
{
callback
(
,
,
resultStatus
)
//could not be found
//fail()
}
}


function figureOutWhoUserIs(req) {
      // just stubbing this out here
      var username = req.query.username
      if (username === 'skroob') {
        return {
          username: username,
          email: 'pres@skroob.com'
        }
      }
      throw new HttpErrors.Unauthorized()
    }

function
figureOutWhoUserIs
(
req
)
{
// just stubbing this out here
var
username
=
req
.
query
.
username
if
(
username
===
'skroob'
)
{
return
{
username
:
username
,
email
:
'pres@skroob.com'
}
}
throw
new
HttpErrors
.
Unauthorized
(
)
}

post - authentication - customAuthHeader


function tryApplyUpdates(onHotUpdateSuccess) {
  if (!module.hot) {
    // HotModuleReplacementPlugin is not in Webpack configuration.
    window.location.reload();
    return;
  }

  if (!isUpdateAvailable() || !canApplyUpdates()) {
    return;
  }

  function handleApplyUpdates(err, updatedModules) {
    if (err || !updatedModules) {
      window.location.reload();
      return;
    }

    if (typeof onHotUpdateSuccess === 'function') {
      // Maybe we want to do something.
      onHotUpdateSuccess();
    }

    if (isUpdateAvailable()) {
      // While we were updating, there was a new update! Do it again.
      tryApplyUpdates();
    }
  }

  // https://webpack.github.io/docs/hot-module-replacement.html#check
  var result = module.hot.check(/* autoApply */true, handleApplyUpdates);

  // // Webpack 2 returns a Promise instead of invoking a callback
  if (result && result.then) {
    result.then(
      function(updatedModules) {
        handleApplyUpdates(null, updatedModules);
      },
      function(err) {
        handleApplyUpdates(err, null);
      }
    );
  }
}

Attempt to update code on the fly, fall back to a hard reload.

Attempt to update code on the fly fall back to a hard reload .


function logMessage (message, data) {
  if (!message) return
  render(message, data, function (err, res) {
    if (err) {
      console.error('\n   Error when rendering template complete message: ' + err.message.trim())
    } else {
      console.log(`\nTo get started:`)
      console.log('')
      console.log(`${chalk.gray('  ------------------')}`)
      console.log('  ' + res.split(/\r?\n/g).map(function (line) {
        return `${chalk.blue(line)}`
      }).join('\n'))
      console.log(`${chalk.gray('  ------------------')}`)
      console.log('')
      console.log(`More infomation: ${chalk.blue.underline('fe -h')}`)
    }
  })
}

Display template complete message.

@param {String} message
@param {Object} data


function interceptWriteStream(writeStream) {
	return new Promise((resolve, reject) => {
		let response = "";
		let writeBkp = writeStream.write;
		let sendBkp = writeStream.send; // For express response streams
		let endBkp = writeStream.end;

		writeStream.write = function(chunk, encoding, callback) {
			response += chunk;

			if(typeof encoding == "function") {
				encoding();
			} else if(callback) {
				callback();
			}
			return true;
		};

		writeStream.send = function(body) {
			writeStream.end(body);
		};

		writeStream.end = function(chunk, encoding, callback) {
			if(chunk) {
				response += chunk;
			}

			writeStream.write = writeBkp;
			writeStream.send = sendBkp;
			writeStream.end = endBkp;

			if(typeof encoding == "function") {
				writeStream.once("finish", encoding);
			} else if(callback) {
				writeStream.once("finish", encoding);
			}

			resolve(response);
		};
	});
}

function
interceptWriteStream
(
writeStream
)
{
return
new
Promise
(
(
resolve
,
reject
)
=>
{
let
response
=
""
;
let
writeBkp
=
writeStream
.
write
;
let
sendBkp
=
writeStream
.
send
;
// For express response streams
let
endBkp
=
writeStream
.
end
;
writeStream
.
write
=
function
(
chunk
,
encoding
,
callback
)
{
response
+=
chunk
;
if
(
typeof
encoding
==
"function"
)
{
encoding
(
)
;
}
else
if
(
callback
)
{
callback
(
)
;
}
return
true
;
}
;
writeStream
.
send
=
function
(
body
)
{
writeStream
.
end
(
body
)
;
}
;
writeStream
.
end
=
function
(
chunk
,
encoding
,
callback
)
{
if
(
chunk
)
{
response
+=
chunk
;
}
writeStream
.
write
=
writeBkp
;
writeStream
.
send
=
sendBkp
;
writeStream
.
end
=
endBkp
;
if
(
typeof
encoding
==
"function"
)
{
writeStream
.
once
(
"finish"
,
encoding
)
;
}
else
if
(
callback
)
{
writeStream
.
once
(
"finish"
,
encoding
)
;
}
resolve
(
response
)
;
}
;
}
)
;
}

Intercepts the "write" and "end" methods of the given writable stream and buffers the values written to them instead.
When the stream ends, the buffered value is returned and the original "write" and "end" methods are restored.
@param writeStream {stream.Writable}
@returns {Promise.<string>}

Intercepts the write and end methods of the given writable stream and buffers the values written to them instead . When the stream ends the buffered value is returned and the original write and end methods are restored .


function getRandomMusic(queue, msg) {
    fs.readFile('./data/autoplaylist.txt', 'utf8', function(err, data) {
        if (err) throw err;
        con('OK: autoplaylist.txt');
        var random = data.split('\n');
        var num = getRandomInt(random.length);
        con(random[num])
        var url = random[num];
        msg.author.username = "AUTOPLAYLIST";
        play(msg, queue, url)
    });
}

function
getRandomMusic
(
queue
,
msg
)
{
fs
.
readFile
(
'./data/autoplaylist.txt'
,
'utf8'
,
function
(
err
,
data
)
{
if
(
err
)
throw
err
;
con
(
'OK: autoplaylist.txt'
)
;
var
random
=
data
.
split
(
'\n'
)
;
var
num
=
getRandomInt
(
random
.
length
)
;
con
(
random
[
num
]
)
var
url
=
random
[
num
]
;
msg
.
author
.
username
=
"AUTOPLAYLIST"
;
play
(
msg
,
queue
,
url
)
}
)
;
}


function formatMessage(message) {
  var lines = message.split('\n');

  // line #0 is filename
  // line #1 is the main error message
  if (!lines[0] || !lines[1]) {
    return message;
  }

  // Remove webpack-specific loader notation from filename.
  // Before:
  // ./~/css-loader!./~/postcss-loader!./src/App.css
  // After:
  // ./src/App.css
  if (lines[0].lastIndexOf('!') !== -1) {
    lines[0] = lines[0].substr(lines[0].lastIndexOf('!') + 1);
  }

  // Cleans up verbose "module not found" messages for files and packages.
  if (lines[1].indexOf('Module not found: ') === 0) {
    lines = [
      lines[0],
      // Clean up message because "Module not found: " is descriptive enough.
      lines[1].replace(
        'Cannot resolve \'file\' or \'directory\' ', ''
      ).replace(
        'Cannot resolve module ', ''
      ).replace(
        'Error: ', ''
      ),
      // Skip all irrelevant lines.
      // (For some reason they only appear on the client in browser.)
      '',
      lines[lines.length - 1] // error location is the last line
    ]
  }

  // Cleans up syntax error messages.
  if (lines[1].indexOf('Module build failed: ') === 0) {
    // For some reason, on the client messages appear duplicated:
    // https://github.com/webpack/webpack/issues/3008
    // This won't happen in Node but since we share this helpers,
    // we will dedupe them right here. We will ignore all lines
    // after the original error message text is repeated the second time.
    var errorText = lines[1].substr('Module build failed: '.length);
    var cleanedLines = [];
    var hasReachedDuplicateMessage = false;
    // Gather lines until we reach the beginning of duplicate message.
    lines.forEach(function(line, index) {
      if (
        // First time it occurs is fine.
        index !== 1 &&
        // line.endsWith(errorText)
        line.length >= errorText.length &&
        line.indexOf(errorText) === line.length - errorText.length
      ) {
        // We see the same error message for the second time!
        // Filter out repeated error message and everything after it.
        hasReachedDuplicateMessage = true;
      }
      if (
        !hasReachedDuplicateMessage ||
        // Print last line anyway because it contains the source location
        index === lines.length - 1
      ) {
        // This line is OK to appear in the output.
        cleanedLines.push(line);
      }
    });
    // We are clean now!
    lines = cleanedLines;
    // Finally, brush up the error message a little.
    lines[1] = lines[1].replace(
      'Module build failed: SyntaxError:',
      friendlySyntaxErrorLabel
    );
  }

  // Reassemble the message.
  message = lines.join('\n');
  // Internal stacks are generally useless so we strip them
  message = message.replace(
    /^\s*at\s.*:\d+:\d+[\s\)]*\n/gm, ''
  ); // at ... ...:x:y

  return message;
}


function resolveBot(bot) {
  let isWaterfall = ("function" == typeof bot) || Array.isArray(bot);
  if (isWaterfall) {
    let dialog = bot;
    let connector = new TestConnector();
    bot = new builder.UniversalBot(connector);
    bot.dialog('/', dialog);
  } else if (bot instanceof builder.UniversalBot) {
    if ( !bot.connector()) {
      bot.connector('console', new TestConnector());
    }
  } else {
    throw new Error(`Unknown type of bot/dialog. Error: ${JSON.stringify(bot)}`);
  }
  return bot;
}

function resolveBot ( bot ) { let isWaterfall = ( "function" == typeof bot ) || Array . isArray ( bot ) ; if ( isWaterfall ) { let dialog = bot ; let connector = new TestConnector ( ) ; bot = new builder . UniversalBot ( connector ) ; bot . dialog ( '/' , dialog ) ; } else if ( bot instanceof builder . UniversalBot ) { if ( ! bot . connector ( ) ) { bot . connector ( 'console' , new TestConnector ( ) ) ; } } else { throw new Error ( ` ${ JSON . stringify ( bot ) } ` ) ; } return bot ; }

Wraps arrays and functions into instance of UniversalBot
Ensure that given bot has connector, otherwise inject TestConnector

@param bot
@returns {*}

Wraps arrays and functions into instance of UniversalBot Ensure that given bot has connector otherwise inject TestConnector


function BlockSerializer(props) {
    const {node, serializers, options, isInline, children} = props
    const blockType = node._type
    const serializer = serializers.types[blockType]
    if (!serializer) {
      throw new Error(
        `Unknown block type "${blockType}", please specify a serializer for it in the \`serializers.types\` prop`
      )
    }

    return h(serializer, {node, options, isInline}, children)
  }

function BlockSerializer ( props ) { const { node , serializers , options , isInline , children } = props const blockType = node . _type const serializer = serializers . types [ blockType ] if ( ! serializer ) { throw new Error ( ` ${ blockType } \` \` ` ) } return h ( serializer , { node , options , isInline } , children ) }


function SpanSerializer(props) {
    const {mark, children} = props.node
    const isPlain = typeof mark === 'string'
    const markType = isPlain ? mark : mark._type
    const serializer = props.serializers.marks[markType]
    if (!serializer) {
      // @todo Revert back to throwing errors?
      // eslint-disable-next-line no-console
      console.warn(
        `Unknown mark type "${markType}", please specify a serializer for it in the \`serializers.marks\` prop`
      )
      return h(props.serializers.markFallback, null, children)
    }

    return h(serializer, props.node, children)
  }


function ListSerializer(props) {
    const tag = props.type === 'bullet' ? 'ul' : 'ol'
    return h(tag, null, props.children)
  }

function ListSerializer ( props ) { const tag = props . type === 'bullet' ? 'ul' : 'ol' return h ( tag , null , props . children ) }


function ListItemSerializer(props) {
    const children =
      !props.node.style || props.node.style === 'normal'
        ? // Don't wrap plain text in paragraphs inside of a list item
          props.children
        : // But wrap any other style in whatever the block serializer says to use
          h(props.serializers.types.block, props, props.children)

    return h('li', null, children)
  }


function BlockTypeSerializer(props) {
    const style = props.node.style || 'normal'

    if (/^h\d/.test(style)) {
      return h(style, null, props.children)
    }

    return style === 'blockquote'
      ? h('blockquote', null, props.children)
      : h('p', null, props.children)
  }

function BlockTypeSerializer ( props ) { const style = props . node . style || 'normal' if ( / ^h\d / . test ( style ) ) { return h ( style , null , props . children ) } return style === 'blockquote' ? h ( 'blockquote' , null , props . children ) : h ( 'p' , null , props . children ) }

Renderer of an actual block of type `block`. Confusing, we know.

Renderer of an actual block of type block . Confusing we know .


function serializeSpan(span, serializers, index, options) {
    if (span === '\n' && serializers.hardBreak) {
      return h(serializers.hardBreak, {key: `hb-${index}`})
    }

    if (typeof span === 'string') {
      return serializers.text ? h(serializers.text, {key: `text-${index}`}, span) : span
    }

    let children
    if (span.children) {
      children = {
        children: span.children.map((child, i) =>
          options.serializeNode(child, i, span.children, true)
        )
      }
    }

    const serializedNode = objectAssign({}, span, children)

    return h(serializers.span, {
      key: span._key || `span-${index}`,
      node: serializedNode,
      serializers
    })
  }

function serializeSpan ( span , serializers , index , options ) { if ( span === '\n' && serializers . hardBreak ) { return h ( serializers . hardBreak , { key : ` ${ index } ` } ) } if ( typeof span === 'string' ) { return serializers . text ? h ( serializers . text , { key : ` ${ index } ` } , span ) : span } let children if ( span . children ) { children = { children : span . children . map ( ( child , i ) => options . serializeNode ( child , i , span . children , true ) ) } } const serializedNode = objectAssign ( { } , span , children ) return h ( serializers . span , { key : span . _key || ` ${ index } ` , node : serializedNode , serializers } ) }

Serializer that recursively calls itself, producing a hyperscript tree of spans

Serializer that recursively calls itself producing a hyperscript tree of spans


function () {
    var el = this.el;
    this.lastPosition = el.getAttribute('position');
    this.lastRotation = el.getAttribute('rotation');
    this.lastScale = el.getAttribute('scale');

    this.lerpingPosition = false;
    this.lerpingRotation = false;
    this.lerpingScale = false;

    this.timeOfLastUpdate = 0;
  }

function ( ) { var el = this . el ; this . lastPosition = el . getAttribute ( 'position' ) ; this . lastRotation = el . getAttribute ( 'rotation' ) ; this . lastScale = el . getAttribute ( 'scale' ) ; this . lerpingPosition = false ; this . lerpingRotation = false ; this . lerpingScale = false ; this . timeOfLastUpdate = 0 ; }

Called once when component is attached. Generally for initial setup.

Called once when component is attached . Generally for initial setup .


function (time, deltaTime) {
    var progress;
    var now = this.now();
    var obj3d = this.el.object3D;

    this.checkForComponentChanged();

    // Lerp position
    if (this.lerpingPosition) {
      progress = (now - this.startLerpTimePosition) / this.duration;
      obj3d.position.lerpVectors(this.startPosition, this.targetPosition, progress);
      // console.log("new position", obj3d.position);
      if (progress >= 1) {
        this.lerpingPosition = false;
      }
    }

    // Slerp rotation
    if (this.lerpingRotation) {
      progress = (now - this.startLerpTimeRotation) / this.duration;
      THREE.Quaternion.slerp(this.startRotation, this.targetRotation, obj3d.quaternion, progress);
      if (progress >= 1) {
        this.lerpingRotation = false;
      }
    }

    // Lerp scale
    if (this.lerpingScale) {
      progress = (now - this.startLerpTimeScale) / this.duration;
      obj3d.scale.lerpVectors(this.startScale, this.targetScale, progress);
      if (progress >= 1) {
        this.lerpingScale = false;
      }
    }
  }


function(datamodel, variables) {
		traverse(datamodel).forEach(function(path) {
			//console.log(path);
			if (this.isLeaf && objectPath.has(variables, path)) {
				this.update(objectPath.get(variables, path));
			}
		});
		return datamodel;
	}

function ( datamodel , variables ) { traverse ( datamodel ) . forEach ( function ( path ) { //console.log(path); if ( this . isLeaf && objectPath . has ( variables , path ) ) { this . update ( objectPath . get ( variables , path ) ) ; } } ) ; return datamodel ; }

Resolve object paths in variables
and assigns the returned result
from datamodel path
@param data {Object}
@param variables {Object}
return {Object}


function(element) {

    this.el = element;

    this.core = window.lgData[this.el.getAttribute('lg-uid')];

    // Execute only if items are above 1
    if (this.core.items.length < 2) {
        return false;
    }

    this.core.s = Object.assign({}, autoplayDefaults, this.core.s);
    this.interval = false;

    // Identify if slide happened from autoplay
    this.fromAuto = true;

    // Identify if autoplay canceled from touch/drag
    this.canceledOnTouch = false;

    // save fourceautoplay value
    this.fourceAutoplayTemp = this.core.s.fourceAutoplay;

    // do not allow progress bar if browser does not support css3 transitions
    if (!this.core.doCss()) {
        this.core.s.progressBar = false;
    }

    this.init();

    return this;
}

Creates the autoplay plugin.
@param {object} element - lightGallery element


function bufferContents(file, enc, cb) {
    // ignore empty files
    if (file.isNull()) {
      return cb();
    }

    // no streams
    if (file.isStream()) {
      this.emit('error', new PluginError('gulp-livingcss', 'Streaming not supported'));
      return cb();
    }

    files.push(file.path);

    cb();
  }

function
bufferContents
(
file
,
enc
,
cb
)
{
// ignore empty files
if
(
file
.
isNull
(
)
)
{
return
cb
(
)
;
}
// no streams
if
(
file
.
isStream
(
)
)
{
this
.
emit
(
'error'
,
new
PluginError
(
'gulp-livingcss'
,
'Streaming not supported'
)
)
;
return
cb
(
)
;
}
files
.
push
(
file
.
path
)
;
cb
(
)
;
}

Buffer all files before parsing them to livingcss.

Buffer all files before parsing them to livingcss .


function two(context, next) {
  setTimeout(function() {
    context.two = 'Hello';
    console.log('Hello from two', context);
    return next();
  }, 1000);
}

function
two
(
context
,
next
)
{
setTimeout
(
function
(
)
{
context
.
two
=
'Hello'
;
console
.
log
(
'Hello from two'
,
context
)
;
return
next
(
)
;
}
,
1000
)
;
}

Function Two.
Example function, logs 'hello' and currect context.

@param {Object} context Current context object.
@param {Function} next Next middleware in chain.

Function Two . Example function logs hello and currect context .


function next() {
    var middleware = chain.shift();

    if (middleware && typeof middleware === 'function') {
      middleware.call(this, context, next);
    }

    return this;
  }

function next ( ) { var middleware = chain . shift ( ) ; if ( middleware && typeof middleware === 'function' ) { middleware . call ( this , context , next ) ; } return this ; }

Next function.
Calls the next middleware in chain.

Next function . Calls the next middleware in chain .


function one(context, next) {
  setTimeout(function() {
    context.one = 'Hello';
    console.log('Hello from one', context);
    return next();
  }, 1000);
  console.log('Hi from one', context);
}

function
one
(
context
,
next
)
{
setTimeout
(
function
(
)
{
context
.
one
=
'Hello'
;
console
.
log
(
'Hello from one'
,
context
)
;
return
next
(
)
;
}
,
1000
)
;
console
.
log
(
'Hi from one'
,
context
)
;
}

Function One.
Example function, logs 'hello' and currect context.
Contains some syncronous code that will execute seperately.

@param {Object} context Current context object.
@param {Function} next Next middleware in chain.

Function One . Example function logs hello and currect context . Contains some syncronous code that will execute seperately .


function two(context, next) {
  context.two = 'Hello';
  console.log('Hello from two', context);
  console.log('Hi from two', context);
  return next();
}

function
two
(
context
,
next
)
{
context
.
two
=
'Hello'
;
console
.
log
(
'Hello from two'
,
context
)
;
console
.
log
(
'Hi from two'
,
context
)
;
return
next
(
)
;
}

Function Two.
Example function, logs 'hello' and currect context.
This function is syncronous.

@param {Object} context Current context object.
@param {Function} next Next middleware in chain.

Function Two . Example function logs hello and currect context . This function is syncronous .


function three(context, next) {
  console.log('Hi from three', context);
  setTimeout(function() {
    context.three = 'Hello';
    console.log('Hello from three', context);
  }, 1000);
}

function
three
(
context
,
next
)
{
console
.
log
(
'Hi from three'
,
context
)
;
setTimeout
(
function
(
)
{
context
.
three
=
'Hello'
;
console
.
log
(
'Hello from three'
,
context
)
;
}
,
1000
)
;
}

Function Three.
Example function, logs 'hello' and currect context.

@param {Object} context Current context object.
@param {Function} next Next middleware in chain.

Function Three . Example function logs hello and currect context .


function two(context, next) {
  setTimeout(function() {
    context.two = 'Hello';
    console.log('Hello from two', context);
    chain({ nested: 'Hello' }, [ one, three ]);
    return next();
  }, 1000);
}

function
two
(
context
,
next
)
{
setTimeout
(
function
(
)
{
context
.
two
=
'Hello'
;
console
.
log
(
'Hello from two'
,
context
)
;
chain
(
{
nested
:
'Hello'
}
,
[
one
,
three
]
)
;
return
next
(
)
;
}
,
1000
)
;
}

Function Two.
Example function, logs 'hello' and currect context.
Calls a new nested chain.

@param {Object} context Current context object.
@param {Function} next Next middleware in chain.

Function Two . Example function logs hello and currect context . Calls a new nested chain .


function ExpressView(view) {
  this.render = (options, callback) => {
    const variables = { ...options._locals, ...options };
    callback(null, view(variables));
  };
  this.path = view.id;
}

function ExpressView ( view ) { this . render = ( options , callback ) => { const variables = { ... options . _locals , ... options } ; callback ( null , view ( variables ) ) ; } ; this . path = view . id ; }


function tryMatchSequence(key) {
    seq.keys.push(key.name);

    // remember when last key was entered so we can decide if it counts as sequence or not
    var m = vim.map.matchInsert(seq.keys)
      // assume we'll match no complete sequence and therefore will want to print keyed char
      , passThru = true;

    if (!m) {
      // in case we buffered some keys hoping for a complete sequence, loose hope now
      self.clearSequence();
    } else if (m === true) {
      // we hope for a future match
    } else if (matchSequence(m)) {
      // we matched our sequence and therefore will not print the char
      passThru = false;
    }

    if (passThru) seq.last = new Date();
    return passThru;
  }

returns true if we are to write to terminal


gets upper-left of a 4x4 matrix into a 3x3 of vectors

gets upper - left of a 4x4 matrix into a 3x3 of vectors


function filter(fn, ctx) {
  assert.equal(typeof fn, 'function')
  return function(val) {
    val = Array.isArray(val) ? val : [val]
    return Promise.resolve(val.filter(fn, ctx))
  }
}

function filter ( fn , ctx ) { assert . equal ( typeof fn , 'function' ) return function ( val ) { val = Array . isArray ( val ) ? val : [ val ] return Promise . resolve ( val . filter ( fn , ctx ) ) } }

Apply a function to all values. @param {Mixed|Mixed[]} val @param {Mixed} ctx @return {Function}


function(rawValue) {
        const value = stringifyInput(rawValue);

        if (!value.match(FORMAT)) {
            throw new Error('Invalid data format; expecting: \'' + FORMAT + '\', found: \'' + value + '\'');
        }

        return mod97(value);
    }

function
(
rawValue
)
{
const
value
=
stringifyInput
(
rawValue
)
;
if
(
!
value
.
match
(
FORMAT
)
)
{
throw
new
Error
(
'Invalid data format; expecting: \''
+
FORMAT
+
'\', found: \''
+
value
+
'\''
)
;
}
return
mod97
(
value
)
;
}

Check requirements.
Returns result of modulo 97 applied to the String input rawValue.

Requirements:
- rawValue must be not `Null`
- rawValue must be of type `String`
- rawValue must respect format `^[0-9A-Z]{1,}$`

@param {*} rawValue

Check requirements . Returns result of modulo 97 applied to the String input rawValue .


async function sendMessage(
  app,
  context,
  title,
  message,
  {update = '', updateAfterDays = 7, owner, repo} = {}
) {
  if (!app || !context || !title || !message) {
    throw new Error('Required parameter missing');
  }

  if (!owner || !repo) {
    ({owner, repo} = context.repo());
  }

  const appGh = await app.auth();
  const {name: appName, html_url: appUrl} = (await appGh.apps.get({})).data;

  const {data: issues} = await context.github.issues.getForRepo({
    owner,
    repo,
    state: 'open',
    creator: `app/${appName}`,
    per_page: 100
  });

  message = message.replace(/{appName}/, appName).replace(/{appUrl}/, appUrl);
  const messageHash = crypto
    .createHash('sha256')
    .update(message)
    .digest('hex');
  const messageHashRx = new RegExp(`<!--${messageHash}-->`);

  for (const issue of issues) {
    if (!messageHashRx.test(issue.body)) {
      continue;
    }

    let commentId = null;
    if (
      update &&
      !issue.locked &&
      Date.now() - Date.parse(issue.updated_at) >=
        updateAfterDays * 24 * 60 * 60 * 1000
    ) {
      update = update.replace(/{appName}/, appName).replace(/{appUrl}/, appUrl);

      const {data: commentData} = await context.github.issues.createComment({
        owner,
        repo,
        number: issue.number,
        body: update
      });
      commentId = commentData.id;
    }

    return new Message(owner, repo, issue.number, commentId, false);
  }

  title = title.replace(/{appName}/, appName).replace(/{appUrl}/, appUrl);

  const {data: issueData} = await context.github.issues.create({
    owner,
    repo,
    title,
    body: `${message}\n<!--${messageHash}-->`
  });

  return new Message(owner, repo, issueData.number, null, true);
}

async
function
sendMessage
(
app
,
context
,
title
,
message
,
{
update
=
''
,
updateAfterDays
=
7
,
owner
,
repo
}
=
{
}
)
{
if
(
!
app
||
!
context
||
!
title
||
!
message
)
{
throw
new
Error
(
'Required parameter missing'
)
;
}
if
(
!
owner
||
!
repo
)
{
(
{
owner
,
repo
}
=
context
.
repo
(
)
)
;
}
const
appGh
=
await
app
.
auth
(
)
;
const
{
name
:
appName
,
html_url
:
appUrl
}
=
(
await
appGh
.
apps
.
get
(
{
}
)
)
.
data
;
const
{
data
:
issues
}
=
await
context
.
github
.
issues
.
getForRepo
(
{
owner
,
repo
,
state
:
'open'
,
creator
:
`
${
appName
}
`
,
per_page
:
100
}
)
;
message
=
message
.
replace
(
/
{appName}
/
,
appName
)
.
replace
(
/
{appUrl}
/
,
appUrl
)
;
const
messageHash
=
crypto
.
createHash
(
'sha256'
)
.
update
(
message
)
.
digest
(
'hex'
)
;
const
messageHashRx
=
new
RegExp
(
`
${
messageHash
}
`
)
;
for
(
const
issue
of
issues
)
{
if
(
!
messageHashRx
.
test
(
issue
.
body
)
)
{
continue
;
}
let
commentId
=
;
if
(
update
&&
!
issue
.
locked
&&
Date
.
now
(
)
Date
.
parse
(
issue
.
updated_at
)
>=
updateAfterDays
*
24
*
60
*
60
*
1000
)
{
update
=
update
.
replace
(
/
{appName}
/
,
appName
)
.
replace
(
/
{appUrl}
/
,
appUrl
)
;
const
{
data
:
commentData
}
=
await
context
.
github
.
issues
.
createComment
(
{
owner
,
repo
,
number
:
issue
.
number
,
body
:
update
}
)
;
commentId
=
commentData
.
id
;
}
return
new
Message
(
owner
,
repo
,
issue
.
number
,
commentId
,
false
)
;
}
title
=
title
.
replace
(
/
{appName}
/
,
appName
)
.
replace
(
/
{appUrl}
/
,
appUrl
)
;
const
{
data
:
issueData
}
=
await
context
.
github
.
issues
.
create
(
{
owner
,
repo
,
title
,
body
:
`
${
message
}
\n
${
messageHash
}
`
}
)
;
return
new
Message
(
owner
,
repo
,
issueData
.
number
,
,
true
)
;
}

Messages repository maintainers by submitting an issue.

@param {Object} app app instance
@param {Object} context event context
@param {string} title issue title, `{appName}` and `{appUrl}`
are optional placeholders
@param {string} message issue content, `{appName}` and `{appUrl}`
are optional placeholders
@param {Object} [options] options
@param {string} [options.update] update to post as a comment, `{appName}`
and `{appUrl}` are optional placeholders, no update is posted if the value
is {@link https://developer.mozilla.org/en-US/docs/Glossary/Falsy|falsy}
or the issue is locked
@param {number} [options.updateAfterDays] post update only if the issue
had no activity in this many days
@param {string} [options.owner] owner of the repository
(optional, default value inferred from `context`)
@param {string} [options.repo] repository
(optional, default value inferred from `context`)

@returns {Promise<Message>} {@link Promise}
that will be fulfilled with a {@link Message} object

@example
const sendMessage = require('probot-messages');

module.exports = app => {
app.on('issue_comment.created', async context => {
await sendMessage(app, context, 'Title', 'Message');
});
};

Messages repository maintainers by submitting an issue .


function packageStatesSerialize () {
  if (atom.packages.serialize != null) {
    return atom.packages.serialize()
  }

  atom.packages.getActivePackages().forEach((pack) => {
    var state
    if (pack.serialize != null) state = pack.serialize()
    if (state) {
      atom.packages.setPackageState(pack.name, state)
    }
  })

  return atom.packages.packageStates
}

function packageStatesSerialize ( ) { if ( atom . packages . serialize != null ) { return atom . packages . serialize ( ) } atom . packages . getActivePackages ( ) . forEach ( ( pack ) => { var state if ( pack . serialize != null ) state = pack . serialize ( ) if ( state ) { atom . packages . setPackageState ( pack . name , state ) } } ) return atom . packages . packageStates }

shim atom . packages . serialize in < = 1 . 6


function atomSerialize () {
  var options = {isUnloading: true}
  if (atom.serialize != null) return atom.serialize(options)

  // Atom <= 1.6
  return {
    version: atom.constructor.version,
    project: atom.project.serialize(options),
    workspace: atom.workspace.serialize(),
    packageStates: packageStatesSerialize(),
    grammars: {grammarOverridesByPath: atom.grammars.grammarOverridesByPath},
    fullScreen: atom.isFullScreen(),
    windowDimensions: atom.windowDimensions
  }
}

function
atomSerialize
(
)
{
var
options
=
{
isUnloading
:
true
}
if
(
atom
.
serialize
!=
)
return
atom
.
serialize
(
options
)
// Atom <= 1.6
return
{
version
:
atom
.
constructor
.
version
,
project
:
atom
.
project
.
serialize
(
options
)
,
workspace
:
atom
.
workspace
.
serialize
(
)
,
packageStates
:
packageStatesSerialize
(
)
,
grammars
:
{
grammarOverridesByPath
:
atom
.
grammars
.
grammarOverridesByPath
}
,
fullScreen
:
atom
.
isFullScreen
(
)
,
windowDimensions
:
atom
.
windowDimensions
}
}


function splitUnique (string) {
  string = string && string.trim();
  if (string) {
    return unique(string.split(/\s+/));
  } else {
    return undefined;
  }
}

function splitUnique ( string ) { string = string && string . trim ( ) ; if ( string ) { return unique ( string . split ( / \s+ / ) ) ; } else { return undefined ; } }

splits a string on whitespaces and removes duplicate values


function walkNodes ($nodes, currentItem) {
    $nodes.each(function (i, node) {
      var $node = $(node);
      var props = splitUnique($node.attr('itemprop'));

      if (props && currentItem) {
        var value = null;
        if ($node.is('[itemscope]')) {
          value = parseItem(node, currentItem);
        } else {
          value = parsePropertyValue(node);
          walkNodes($node.children(), currentItem);
        }
        currentItem.addProperties(props, value);
      } else if ($node.is('[itemscope]') && !$node.is('[itemprop]')) {
        var newItem = parseItem(node, currentItem);
        if (newItem !== Item.ERROR) {
          items.push(newItem);
        }
      } else {
        walkNodes($node.children(), currentItem);
      }
    });
  }

function walkNodes ( $nodes , currentItem ) { $nodes . each ( function ( i , node ) { var $node = $ ( node ) ; var props = splitUnique ( $node . attr ( 'itemprop' ) ) ; if ( props && currentItem ) { var value = null ; if ( $node . is ( '[itemscope]' ) ) { value = parseItem ( node , currentItem ) ; } else { value = parsePropertyValue ( node ) ; walkNodes ( $node . children ( ) , currentItem ) ; } currentItem . addProperties ( props , value ) ; } else if ( $node . is ( '[itemscope]' ) && ! $node . is ( '[itemprop]' ) ) { var newItem = parseItem ( node , currentItem ) ; if ( newItem !== Item . ERROR ) { items . push ( newItem ) ; } } else { walkNodes ( $node . children ( ) , currentItem ) ; } } ) ; }

visits a set of nodes to be parsed and recursively visits its children currentItem, if provided, contains the current microdata context

visits a set of nodes to be parsed and recursively visits its children currentItem if provided contains the current microdata context


function parseItem (node, currentItem) {
    // REMARK: note the raw dom node instead of $node to guarantee uniqueness
    if (currentItem && currentItem.hasMemoryOf(node)) {
      return Item.ERROR;
    }

    var $node = $(node);
    var type = splitUnique($node.attr('itemtype'));
    type = type && type.filter(isAbsoluteUrl);

    var item = new Item({
      type: type,
      id: $node.attr('itemid'),
      node: node,
      parent: currentItem
    });

    walkNodes($node.children(), item);

    // visit all nodes referenced by the current one
    var refs = splitUnique($node.attr('itemref'));
    if (refs) {
      var refsSelector = refs
        .map(function makeIdSelector (id) {
          return '#' + id;
        })
        .join(',');

      walkNodes($(refsSelector), item);
    }

    return item;
  }

parses a microdata item out of an itemscope DOM node


function resolveUrlAttribute ($node, attr) {
    var url = $node.attr(attr);
    if (url === undefined) return '';
    if (isAbsoluteUrl(url)) {
      return url;
    } else {
      return urlUtil.resolve(base, url);
    }
  }

function resolveUrlAttribute ( $node , attr ) { var url = $node . attr ( attr ) ; if ( url === undefined ) return '' ; if ( isAbsoluteUrl ( url ) ) { return url ; } else { return urlUtil . resolve ( base , url ) ; } }

extracts, and normalizes a url attribute value of a node

extracts and normalizes a url attribute value of a node


function parsePropertyValue (node) {
    var $node = $(node);

    if ($node.is('meta')) {
      return resolveAttribute($node, 'content');
    } else if ($node.is('audio,embed,iframe,img,source,track,video')) {
      return resolveUrlAttribute($node, 'src');
    } else if ($node.is('a,area,link')) {
      return resolveUrlAttribute($node, 'href');
    } else if ($node.is('object')) {
      return resolveUrlAttribute($node, 'data');
    } else if ($node.is('data,meter')) {
      return resolveAttribute($node, 'value');
    } else if ($node.is('time')) {
      return resolveAttribute($node, 'datetime');
    } else {
      var text = $node.text();
      return text || '';
    }
  }

extracts the property value out of an itemprop DOM node


function processPatterns(patterns, fn) {

  // Filepaths to return.
  var result = [];
  // Iterate over flattened patterns array.
  _.flattenDeep(patterns).forEach(function(pattern) {
    // If the first character is ! it should be omitted
    var exclusion = pattern.indexOf('!') === 0;
    // If the pattern is an exclusion, remove the !
    if (exclusion) {
      pattern = pattern.slice(1);
    }
    // Find all matching files for this pattern.
    var matches = fn(pattern);

    if (exclusion) {
      // If an exclusion, remove matching files.
      result = _.difference(result, matches);
    } else {
      // Otherwise add matching files.
      result = _.union(result, matches);
    }
  });

  return result;
}

Process specified wildcard glob patterns or filenames against a callback, excluding and uniquing files in the result set.

Process specified wildcard glob patterns or filenames against a callback excluding and uniquing files in the result set .


function sendMessage( args ){
    last = new Date();
    fs.write( tmpfile, JSON.stringify( args ) + '\n', 'a' );
    // Exit when all done.
    if( /^done/.test( args[0] ) ){
        phantom.exit();
    }
}

function
sendMessage
(
args
)
{
last
=
new
Date
(
)
;
fs
.
write
(
tmpfile
,
JSON
.
stringify
(
args
)
+
'\n'
,
'a'
)
;
// Exit when all done.
if
(
/
^done
/
.
test
(
args
[
0
]
)
)
{
phantom
.
exit
(
)
;
}
}

Messages are sent to the parent by appending them to the tempfile.

Messages are sent to the parent by appending them to the tempfile .


function( url ){
            grunt.verbose.write( 'Running PhantomJS...' ).or.write( '...' );
            grunt.log.error();
            grunt.warn( 'PhantomJS unable to load "' + url + '" URI.', 90 );
        }

function
(
url
)
{
grunt
.
verbose
.
write
(
'Running PhantomJS...'
)
.
or
.
write
(
'...'
)
;
grunt
.
log
.
error
(
)
;
grunt
.
warn
(
'PhantomJS unable to load "'
+
url
+
'" URI.'
,
90
)
;
}


function F(type, term) {
  let original = term;
  if (term && !term.__meta) {
    term = type.wrap ? type.wrap(term) : term;
    term.__meta = {};
    term.__name = function(name) {
      term.__meta.name = name;
      return term;
    };
    term.__desc = function(desc) {
      term.__meta.desc = desc;
      return term;
    };
    if (term.__meta) {
      term.__meta.term = original;
      term.__meta.name = "anon";
      term.__meta.desc = "no description";
    };
  };
  F.check(type, term);
  return term;
}

function
F
(
type
,
term
)
{
let
original
=
term
;
if
(
term
&&
!
term
.
__meta
)
{
term
=
type
.
wrap
type
.
wrap
(
term
)
:
term
;
term
.
__meta
=
{
}
;
term
.
__name
=
function
(
name
)
{
term
.
__meta
.
name
=
name
;
return
term
;
}
;
term
.
__desc
=
function
(
desc
)
{
term
.
__meta
.
desc
=
desc
;
return
term
;
}
;
if
(
term
.
__meta
)
{
term
.
__meta
.
term
=
original
;
term
.
__meta
.
name
=
"anon"
;
term
.
__meta
.
desc
=
"no description"
;
}
;
}
;
F
.
check
(
type
,
term
)
;
return
term
;
}

Performs static type checking, enables dynamic type checks.

Performs static type checking enables dynamic type checks .


function (json, delimiter) {
  var result = [];
  var recurse = function (cur, prop) {
    for (var key in cur) {
      if (cur.hasOwnProperty(key)) {
        var item = cur[key];
        result.push({
          match: prop ? prop + delimiter + key : key,
          replacement: item,
          expression: false
        });
        // deep scan
        if (typeof item === 'object') {
          recurse(item, prop ? prop + delimiter + key : key);
        }
      }
    }
  };
  recurse(json);
  return result;
}

function
(
json
,
delimiter
)
{
var
result
=
[
]
;
var
recurse
=
function
(
cur
,
prop
)
{
for
(
var
key
in
cur
)
{
if
(
cur
.
hasOwnProperty
(
key
)
)
{
var
item
=
cur
[
key
]
;
result
.
push
(
{
match
:
prop
prop
+
delimiter
+
key
:
key
,
replacement
:
item
,
expression
:
false
}
)
;
// deep scan
if
(
typeof
item
===
'object'
)
{
recurse
(
item
,
prop
prop
+
delimiter
+
key
:
key
)
;
}
}
}
}
;
recurse
(
json
)
;
return
result
;
}


function ld(date, long = true, options = null) {
	return Localizer.Singleton.formatDate(date, long, options)
}

function ld ( date , long = true , options = null ) { return Localizer . Singleton . formatDate ( date , long , options ) }

A shorthand function for getting a localized date

@param {Date} date
@param {bool} [long=true]
@param {options} [options=null]
@return {string} a localized string representing the date


function ldt(date, long = true, options = null) {
	return Localizer.Singleton.formatDateTime(date, long, options)
}

function ldt ( date , long = true , options = null ) { return Localizer . Singleton . formatDateTime ( date , long , options ) }

A shorthand function for getting a localized date and time

@param {Date} date
@param {bool} [long=true]
@param {options} [options=null]
@return {string} a localized string representing the date and time


function getStyle (element, property) {
  if (window.getComputedStyle) {
    return getStyleProperty(element, property).original;
  } else if (element.currentStyle) {
    return element.currentStyle[property];
  }
  return null;
}

function getStyle ( element , property ) { if ( window . getComputedStyle ) { return getStyleProperty ( element , property ) . original ; } else if ( element . currentStyle ) { return element . currentStyle [ property ] ; } return null ; }

cross-browser way of getting element's style property

cross - browser way of getting element s style property


function hasChanged(newData, oldData) {
    var changed = false
    for (var i = 0; i < scope.length; i++) {
      var k = scope[i],
        newVal = _.get(newData, k),
        oldVal = _.get(oldData, k)
      if (!_.isEqual(newVal, oldVal)) {
        changed = true
        break
      }
    }

    return changed
  }

function hasChanged ( newData , oldData ) { var changed = false for ( var i = 0 ; i < scope . length ; i ++ ) { var k = scope [ i ] , newVal = _ . get ( newData , k ) , oldVal = _ . get ( oldData , k ) if ( ! _ . isEqual ( newVal , oldVal ) ) { changed = true break } } return changed }

Determine is the slug field value changed


function(initValues, element, notCreate) {
            if (element === undefined) {
                if (notCreate) {
                    item.values(initValues, notCreate);
                } else {
                    item.values(initValues);
                }
            } else {
                item.elm = element;
                var values = templater.get(item, initValues);
                item.values(values);
            }
        }

function ( initValues , element , notCreate ) { if ( element === undefined ) { if ( notCreate ) { item . values ( initValues , notCreate ) ; } else { item . values ( initValues ) ; } } else { item . elm = element ; var values = templater . get ( item , initValues ) ; item . values ( values ) ; } }

Show if list.filtered == true and this.filtered == true

Show if list . filtered == true and this . filtered == true


function checkUrl(url, method, routes){
    method=method.toLowerCase();
    for (var i=0; i<routes.length; i++){
        var route=routes[i];
        if ((matchPath(route.url,url)) && (method==route.method)) return route;
    }
    return false;
}

function checkUrl ( url , method , routes ) { method = method . toLowerCase ( ) ; for ( var i = 0 ; i < routes . length ; i ++ ) { var route = routes [ i ] ; if ( ( matchPath ( route . url , url ) ) && ( method == route . method ) ) return route ; } return false ; }

Check if route should be authorized and return route setting


function eatBraces(stream, root) {
	if (stream.eat(LBRACE)) {
		let stack = 1, token;

		while (!stream.eof()) {
			if (stream.eat(RBRACE)) {
				stack--;
				if (!stack) {
					break;
				}
			} else if (stream.eat(LBRACE)) {
				stack++;
			} else if (eatUrl(stream) || eatString(stream)) {
				continue;
			} else if (token = comment(stream)) {
				root.addComment(token);
				continue;
			} else {
				stream.next();
			}
		}

		return true;
	}

	return false;
}

function eatBraces ( stream , root ) { if ( stream . eat ( LBRACE ) ) { let stack = 1 , token ; while ( ! stream . eof ( ) ) { if ( stream . eat ( RBRACE ) ) { stack -- ; if ( ! stack ) { break ; } } else if ( stream . eat ( LBRACE ) ) { stack ++ ; } else if ( eatUrl ( stream ) || eatString ( stream ) ) { continue ; } else if ( token = comment ( stream ) ) { root . addComment ( token ) ; continue ; } else { stream . next ( ) ; } } return true ; } return false ; }

Consumes content inside round braces. Mostly used to skip `;` token inside
expressions since in LESS it is also used to separate function arguments
@param  {StringReader} stream
@param  {Stylesheet}   root   A stylesheet root. Used to accumulate comments
@return {Boolean}

Consumes content inside round braces . Mostly used to skip ; token inside expressions since in LESS it is also used to separate function arguments


function underscore(baseQuery) {
  return _.mapKeys(baseQuery, function(v, k) {
    return tableColumnRenamer.underscore(k)
  })
}

function underscore ( baseQuery ) { return _ . mapKeys ( baseQuery , function ( v , k ) { return tableColumnRenamer . underscore ( k ) } ) }

Returns a map with baseQuery's keys converted to underscore_case.

Returns a map with baseQuery s keys converted to underscore_case .


function filterQueryParams (baseClause, request) {
	_.forEach(request.query, function(v, k) {
		addWhereClause(baseClause, k, v)
	})
    return baseClause
}

function filterQueryParams ( baseClause , request ) { _ . forEach ( request . query , function ( v , k ) { addWhereClause ( baseClause , k , v ) } ) return baseClause }

Builds the "find all" WHERE clause query param map by taking into consideration request.query parameters.

Builds the find all WHERE clause query param map by taking into consideration request . query parameters .


function addWhereClause(baseClause, k, v) {
	if (v.startsWith('>')) {
		baseClause.where(k, '>=', v.substring(1)); return
	}
	if (v.startsWith('<')) {
		baseClause.where(k, '<=', v.substring(1)); return
	}
	if (v.startsWith('~')) {
		baseClause.where(k, 'LIKE', v.substring(1)); return
	}
	if (k.endsWith('Id')) {
		baseClause.where(k.substring(0, k.length - 2) + '_id', '=', v); return
	}
	baseClause.where(k, '=', v); return
}

function addWhereClause ( baseClause , k , v ) { if ( v . startsWith ( '>' ) ) { baseClause . where ( k , '>=' , v . substring ( 1 ) ) ; return } if ( v . startsWith ( '<' ) ) { baseClause . where ( k , '<=' , v . substring ( 1 ) ) ; return } if ( v . startsWith ( '~' ) ) { baseClause . where ( k , 'LIKE' , v . substring ( 1 ) ) ; return } if ( k . endsWith ( 'Id' ) ) { baseClause . where ( k . substring ( 0 , k . length - 2 ) + '_id' , '=' , v ) ; return } baseClause . where ( k , '=' , v ) ; return }

Adds a single WHERE clause to an existing base clause for a single request.query parameter.

Adds a single WHERE clause to an existing base clause for a single request . query parameter .


function findByIdQueryParams (request, config) {
    return typeof config.baseQuery === 'undefined' ? {'id': request.params.id} : _.merge({'id': request.params.id}, underscore(config.baseQuery(request)))
}

function findByIdQueryParams ( request , config ) { return typeof config . baseQuery === 'undefined' ? { 'id' : request . params . id } : _ . merge ( { 'id' : request . params . id } , underscore ( config . baseQuery ( request ) ) ) }

Builds the "find by id" WHERE clause query param map by taking into consideration config.baseQuery.

Builds the find by id WHERE clause query param map by taking into consideration config . baseQuery .


function empty (entity, schema, Empty) {
  if (typeof entity === 'undefined' || entity === null) {
    return
  }
  _.forEach(schema, function(v, k) {
    if (v === Empty) {
      delete entity[k]
    }
  })
}

function empty ( entity , schema , Empty ) { if ( typeof entity === 'undefined' || entity === null ) { return } _ . forEach ( schema , function ( v , k ) { if ( v === Empty ) { delete entity [ k ] } } ) }

Deletes any properties from the entity which in the schema are marked as Empty.

Deletes any properties from the entity which in the schema are marked as Empty .


function initModel (config) {
  if (typeof config.bookshelfModel.prototype.schema === 'undefined') {
    config.bookshelfModel.prototype.schema = {}
  }
  addConstraintsForForeignKeys(config.bookshelfModel, config.baseQuery)
  config.bookshelfModel.prototype.format = tableColumnRenamer.renameOnFormat
  config.bookshelfModel.prototype.parse = tableColumnRenamer.renameOnParse
  initJsonDateFormat(config.bookshelfModel)
}

function initModel ( config ) { if ( typeof config . bookshelfModel . prototype . schema === 'undefined' ) { config . bookshelfModel . prototype . schema = { } } addConstraintsForForeignKeys ( config . bookshelfModel , config . baseQuery ) config . bookshelfModel . prototype . format = tableColumnRenamer . renameOnFormat config . bookshelfModel . prototype . parse = tableColumnRenamer . renameOnParse initJsonDateFormat ( config . bookshelfModel ) }

Initializes the models from the config provided to make them usable with the exported crud function.

Initializes the models from the config provided to make them usable with the exported crud function .


function initJsonDateFormat (bookshelfModel) {
  const schema = bookshelfModel.prototype.schema
  const originalFunction = bookshelfModel.prototype.toJSON
  // read from MySQL date, based on https://github.com/tgriesser/bookshelf/issues/246#issuecomment-35498066
  bookshelfModel.prototype.toJSON = function () {
    const attrs = originalFunction.apply(this, arguments)
    _.forEach(attrs, function(v, k) {
      if (v !== null && typeof schema[k] !== 'undefined' && schema[k]._type === 'date') {
        attrs[k] = moment(v).format(schema[k]._flags.format)
      }
    })
    return attrs
  }
}

Initializes bookshelfModel's toJSON functionality to convert all date properties, as defined in bookshelfModel.schema.

Initializes bookshelfModel s toJSON functionality to convert all date properties as defined in bookshelfModel . schema .


function formatNumber (payload, schema) {
  _.forEach(schema, function(v, k) {
    if (v !== null && v._type === 'number') {
      if (typeof payload[k] === 'undefined' || payload[k] === null) {
        payload[k] = 0
      }
    }
  })
}

function formatNumber ( payload , schema ) { _ . forEach ( schema , function ( v , k ) { if ( v !== null && v . _type === 'number' ) { if ( typeof payload [ k ] === 'undefined' || payload [ k ] === null ) { payload [ k ] = 0 } } } ) }

Initializes every empty number property of a payload, as defined in the schema provided, with 0.

Initializes every empty number property of a payload as defined in the schema provided with 0 .


function formatDate (payload, schema) {
  _.forEach(schema, function(v, k) {
    if (v !== null && v._type === 'date') {
      if (payload[k] !== null) {
        payload[k] = new Date(payload[k])
      }
    }
  })
}

function formatDate ( payload , schema ) { _ . forEach ( schema , function ( v , k ) { if ( v !== null && v . _type === 'date' ) { if ( payload [ k ] !== null ) { payload [ k ] = new Date ( payload [ k ] ) } } } ) }

Applies simple to-date conversion for every date property of a payload, as defined in the schema provided.

Applies simple to - date conversion for every date property of a payload as defined in the schema provided .


function setForeignKeys (request, baseQuery) {
  if (typeof baseQuery === 'undefined') {
    return
  }

  _.forEach(baseQuery(request), function(v, k) {
    request.payload[k] = request.params[k]
  })
}

function setForeignKeys ( request , baseQuery ) { if ( typeof baseQuery === 'undefined' ) { return } _ . forEach ( baseQuery ( request ) , function ( v , k ) { request . payload [ k ] = request . params [ k ] } ) }

Copies the value of the foreign keys, as defined in baseQuery, provided by request.params, to the request.payload model.

Copies the value of the foreign keys as defined in baseQuery provided by request . params to the request . payload model .


function transformConstraintViolationMessages (input) {
    return {
        validationErrors: _.chain(input.details)
    .mapKeys(function(v, k) {
	  // Use '.' as the key if the entire object is erroneous
      return (input.details.length == 1 && input.details[0].path === 'value' && input.details[0].type === 'object.base') ? '.' : v.path
    })
    .mapValues(function (v) {
            return {
        attributes: _.chain(v.context)
        .pickBy(function(v, k) {
          return typeof v !== 'undefined' && v !== null && k !== 'key'
        })
        .mapValues(function(i) {
          return i.toString()
        }),
        constraintClassName: v.type,
        invalidValue: v.context.value,
                messageTemplate: v.type,
            }
        })
    }
}

Converts the error object provided into the specified validation constraint violation error message format.

Converts the error object provided into the specified validation constraint violation error message format .


function lazyConsForce() {
  /* jshint validthis:true */
  var val = this.tailFn();
  /* eslint-disable no-use-before-define */
  this.tailValue = Array.isArray(val) ? fromArray(val) : val;
  /* eslint-enable no-use-before-define */

  delete this.tail;
  delete this.force;

  return this;
}

But when cons is created, it's overloaded with lazy ones Force tail to whnf.

But when cons is created it s overloaded with lazy ones Force tail to whnf .


function isEmptyTag(node) {
    if(node.constructor === Element && !node.hasChildNodes()) return true
    return Boolean(EMPTY_TAG_SET[node.tagName])
}

function isEmptyTag ( node ) { if ( node . constructor === Element && ! node . hasChildNodes ( ) ) return true return Boolean ( EMPTY_TAG_SET [ node . tagName ] ) }

Check if the specified element has no end tag
@param node
@returns {boolean}


function LogWatcher(dirpath, maxfiles, ignoreInitial) {
		_classCallCheck(this, LogWatcher);

		var _this = _possibleConstructorReturn(this, (LogWatcher.__proto__ || Object.getPrototypeOf(LogWatcher)).call(this));

		_this._dirpath = dirpath || DEFAULT_SAVE_DIR;
		_this._filter = isCommanderLog;
		_this._maxfiles = maxfiles || 3;
		_this._logDetailMap = {};
		_this._ops = [];
		_this._op = null;
		_this._startTime = new Date();
		_this._timer = null;
		_this._die = false;
		_this._ignoreInitial = ignoreInitial || false;
		_this.stopped = false;
		_this._loop();
		_this.emit('Started');
		return _this;
	}

function LogWatcher ( dirpath , maxfiles , ignoreInitial ) { _classCallCheck ( this , LogWatcher ) ; var _this = _possibleConstructorReturn ( this , ( LogWatcher . __proto__ || Object . getPrototypeOf ( LogWatcher ) ) . call ( this ) ) ; _this . _dirpath = dirpath || DEFAULT_SAVE_DIR ; _this . _filter = isCommanderLog ; _this . _maxfiles = maxfiles || 3 ; _this . _logDetailMap = { } ; _this . _ops = [ ] ; _this . _op = null ; _this . _startTime = new Date ( ) ; _this . _timer = null ; _this . _die = false ; _this . _ignoreInitial = ignoreInitial || false ; _this . stopped = false ; _this . _loop ( ) ; _this . emit ( 'Started' ) ; return _this ; }

Construct the log watcher.
@param dirpath {string} The directory to watch.
@param maxfiles {number} Maximum amount of files to process.
@param ignoreInitial {boolean} Ignore initial read or not.


function loadImage(image) {
				$scope.$applyAsync(function () {
					if ($scope.reversed) $scope.flipContext();
					$scope.signatureReady = true;

					ctxBackground.clearRect(0, 0, canvas.width, canvas.height);
					ctxBackground.drawImage(image, 0, 0, canvasBackground.width, canvasBackground.height);
				});
			}

function loadImage ( image ) { $scope . $applyAsync ( function ( ) { if ( $scope . reversed ) $scope . flipContext ( ) ; $scope . signatureReady = true ; ctxBackground . clearRect ( 0 , 0 , canvas . width , canvas . height ) ; ctxBackground . drawImage ( image , 0 , 0 , canvasBackground . width , canvasBackground . height ) ; } ) ; }


function() {
		if(this.read) {
			// 1. parse value
			this.computed_observable = new Observer(this.createFunction("return ("+this.value+");", ["m", "p"], [this.context.model, this.context.parent], this.context.domElement), {
				/* for debugging only */
				domElement: this.context.domElement,
				attribute: this.name,
				value: this.value
			});

			// 2. add subscribers
			this.read_binded = this.read.bind(this);
			this.computed_observable.subscribe(this.read_binded);

			// 3. initial element update
			this.read(this.computed_observable.currentValue);
		}
		if(this.event) {
			this.event(this.createEventFunction());
		}
		/*if(registeredAttributes[i].event) {
			// It is a data handler's job
			this.event(name, eventFunctionFactory(value, context), context);
		}*/
	}


function(functionBody, argNames, argValues, context) {
		// store context
		var functionArgs = argNames.concat(functionBody);
		var fn = Function.apply(null, functionArgs);

		// return function
		return function() {
			// mix predefined arguments with passed
			var args = argValues.concat(Array.prototype.slice.call(arguments));
			return fn.apply(context, args);
		}
	}


function( expected, actual, optionsOrMsg ) {
			var options = optionsOrMsg instanceof Object ? optionsOrMsg : { message: optionsOrMsg },
				msg = options.message,
				compatHtml = bender.tools && bender.tools.compatHtml;

			if ( !options.skipCompatHtml ) {
				var sortAttributes = ( 'sortAttributes' in options ) ? options.sortAttributes : true,
					fixZWS = ( 'fixZWS' in options ) ? options.fixZWS : true,
					fixNbsp = ( 'fixNbsp' in options ) ? options.fixNbsp : true;

				if ( !compatHtml ) {
					throw new Error( 'Missing bender.tools.compatHtml' );
				}

				expected = compatHtml( expected, options.noInterWS, sortAttributes, fixZWS, options.fixStyles, fixNbsp, options.noTempElements, options.customFilters );
				actual = compatHtml( actual, options.noInterWS, sortAttributes, fixZWS, options.fixStyles, fixNbsp, options.noTempElements, options.customFilters );
			}

			bender.assert.areSame( html_beautify( expected, this._config ), html_beautify( actual, this._config ), msg );
		}

function
(
expected
,
actual
,
optionsOrMsg
)
{
var
options
=
optionsOrMsg
instanceof
Object
optionsOrMsg
:
{
message
:
optionsOrMsg
}
,
msg
=
options
.
message
,
compatHtml
=
bender
.
tools
&&
bender
.
tools
.
compatHtml
;
if
(
!
options
.
skipCompatHtml
)
{
var
sortAttributes
=
(
'sortAttributes'
in
options
)
options
.
sortAttributes
:
true
,
fixZWS
=
(
'fixZWS'
in
options
)
options
.
fixZWS
:
true
,
fixNbsp
=
(
'fixNbsp'
in
options
)
options
.
fixNbsp
:
true
;
if
(
!
compatHtml
)
{
throw
new
Error
(
'Missing bender.tools.compatHtml'
)
;
}
expected
=
compatHtml
(
expected
,
options
.
noInterWS
,
sortAttributes
,
fixZWS
,
options
.
fixStyles
,
fixNbsp
,
options
.
noTempElements
,
options
.
customFilters
)
;
actual
=
compatHtml
(
actual
,
options
.
noInterWS
,
sortAttributes
,
fixZWS
,
options
.
fixStyles
,
fixNbsp
,
options
.
noTempElements
,
options
.
customFilters
)
;
}
bender
.
assert
.
areSame
(
html_beautify
(
expected
,
this
.
_config
)
,
html_beautify
(
actual
,
this
.
_config
)
,
msg
)
;
}

Compares HTML code, but beautifies it before the comparison.

@param {mixed} expected
@param {mixed} actual
@param {String/Object} optionsOrMsg Assertion message if string, otherwise an options object like following:

{
message: 'Fail message',
sortAttributes: true,
fixZWS: false
}

If you don't want to format `expected` and `actual` with `compatHtml` you can set `options.skipCompatHtml` to `true`.

Compares HTML code but beautifies it before the comparison .


function( expected, actual, msg ) {
			bender.assert.areSame( js_beautify( expected, this._config ), js_beautify( actual, this._config ), msg );
		}

function ( expected , actual , msg ) { bender . assert . areSame ( js_beautify ( expected , this . _config ) , js_beautify ( actual , this . _config ) , msg ) ; }

Compares JavaScript code, but beautifies it before the comparison.

@param {mixed} expected
@param {mixed} actual
@param {String} [msg] Assertion message.

Compares JavaScript code but beautifies it before the comparison .


function( expected, actual, msg ) {
			var assert = bender.assert;

			assert.isTypeOf( 'object', expected, 'Expected is not an object' );
			assert.isTypeOf( 'object', actual, 'Actual is not an object' );

			// Simply convert to JSON strings for a good diff in case of fails.
			expected = JSON.stringify( objectHelpers.sortObjectProperties( expected ) );
			actual = JSON.stringify( objectHelpers.sortObjectProperties( actual ) );

			this.js( expected, actual, msg );
		}

Compares two objects.

@param {mixed} expected
@param {mixed} actual
@param {String} [msg] Assertion message.


function checkIfShouldStick() {
				if (mediaQuery && !matchMedia('(' + mediaQuery + ')').matches) return;
				var scrollTop = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0);
				var shouldStick = scrollTop >= stickyLine;
				// Switch the sticky modes if the element has crossed the sticky line
				if (shouldStick && !isSticking) stickElement();else if (!shouldStick && isSticking) unstickElement();
			}

checks if the window has passed the sticky line


function buildServicesInternal() {
        if (_.isFunction(subdivision.buildServices)) {
            subdivision.vent.trigger('before:buildServices');
            return subdivision.buildServices().then(function () {
                subdivision.vent.trigger('after:buildServices');
            });
        } else {
            return Promise.resolve();
        }
    }

function buildServicesInternal ( ) { if ( _ . isFunction ( subdivision . buildServices ) ) { subdivision . vent . trigger ( 'before:buildServices' ) ; return subdivision . buildServices ( ) . then ( function ( ) { subdivision . vent . trigger ( 'after:buildServices' ) ; } ) ; } else { return Promise . resolve ( ) ; } }


function(path) {
            var node = this.$getNode(path, false);
            if (node !== null){
                return _.keys(node.nodes);
            } else {
                return null;
            }
        }

function ( path ) { var node = this . $getNode ( path , false ) ; if ( node !== null ) { return _ . keys ( node . nodes ) ; } else { return null ; } }

Returns all the paths that exist under the given path


function(obj) {
	if(obj == null || typeof obj != 'object' || Object.isFrozen(obj) || obj._keepHot) return;

	Object.freeze(obj); // First freeze the object.

	for (var key in obj) {
		if(obj.hasOwnProperty(key)) deepFreeze(obj[key]); // Recursively call deepFreeze.
	}
}

function
(
obj
)
{
if
(
obj
==
||
typeof
obj
!=
'object'
||
Object
.
isFrozen
(
obj
)
||
obj
.
_keepHot
)
return
;
Object
.
freeze
(
obj
)
;
// First freeze the object.
for
(
var
key
in
obj
)
{
if
(
obj
.
hasOwnProperty
(
key
)
)
deepFreeze
(
obj
[
key
]
)
;
// Recursively call deepFreeze.
}
}

deeply freeze an object to make it fully immutable


function(parentClass, constructor) {
	// inherits methods from parent class
	constructor.prototype = Object.create(parentClass.prototype);

	// inherits methods from Subscribable class
	for(var key in Subscribable.prototype) {
		constructor.prototype[key] = Subscribable.prototype[key];
	}

	constructor.prototype.constructor = constructor;
	constructor.prototype._keepHot = true;

	return constructor;
}

Create model class with a subscribable interface.

Create model class with a subscribable interface .


function BinarySearchTreeIterator(tree, type) {
    type = type || 'v';

    if (type !== 'k' && type !== 'v' && type !== 'e') {
        throw new Error('Incorrect binary search tree iterator type "' + type + '"!');
    }

    this._type = type;
    this._tree = tree;
    this._last = null;
    this._done = false;
}

Binary search tree iterator

@param tree Binary Search tree
@param type Type of iteration result
@constructor


function (xhr, options, promise) {
            var instance = this,
                url = options.url,
                method = options.method || GET,
                headers = options.headers ? options.headers.itsa_deepClone() : {}, // all request will get some headers
                async = !options.sync,
                data = options.data,
                reject = promise.reject,
                sendPayload, additionalData;
            // xhr will be null in case of a CORS-request when no CORS is possible
            if (!xhr) {
                console.error(NAME, "_initXHR fails: "+ERROR_NO_XHR);
                reject(ERROR_NO_XHR);
                return;
            }
            // adding default headers (when set):
            headers.itsa_merge(instance._standardHeaders);

            // method-name should be in uppercase:
            method = method.toUpperCase();
            // in case of BODY-method: eliminate any data behind querystring:
            // else: append data-object behind querystring
            if (BODY_METHODS[method]) {
                url = url.split("?"); // now url is an array
                url[1] && (additionalData=instance._queryStringToDataObject(url[1]));
                if (additionalData && !additionalData.itsa_isEmpty()) {
                    data || (data={});
                    data.itsa_merge(additionalData);
                }
                url = url[0]; // now url is a String again
            }
            else if (data && (headers[CONTENT_TYPE]!==MIME_BLOB)) {
                url += (url.itsa_contains("?") ? "&" : "?") + instance._toQueryString(data);
            }

            xhr.open(method, url, async);
            options.responseType && (xhr.responseType=options.responseType);
            options.withCredentials && (xhr.withCredentials=true);

            // more initialisation might be needed by extended modules:
            instance._xhrInitList.forEach(
                function(fn) {
                    fn(xhr, promise, headers, method);
                }
            );

            if (BODY_METHODS[method] && data) {
                if (headers[CONTENT_TYPE]===MIME_BLOB) {
                    if (!xhr._isXDR) {
                        sendPayload = data;
                    }
                }
                else {
                    sendPayload = ((headers[CONTENT_TYPE]===MIME_JSON) || xhr._isXDR) ? JSON.stringify(data) : instance._toQueryString(data);
                }
            }
            // send the request:
            xhr.send(sendPayload);

            // now add xhr.abort() to the promise, so we can call from within the returned promise-instance
            promise.abort = function() {
                reject(ABORTED);
                xhr._aborted = true; // must be set: IE9 won"t allow to read anything on xhr after being aborted
                xhr.abort();
            };

            // in case synchronous transfer: force an xhr.onreadystatechange:
            async || xhr.onreadystatechange();
        }

Initializes the xhr-instance, based on the config-params.
This method is the standard way of doing xhr-requests without processing streams.

@method _initXHR
@param xhr {Object} xhr-instance
@param options {Object}
@param [options.url] {String} The url to which the request is sent.
@param [options.method="GET"] {String} The HTTP method to use.
can be ignored, even if streams are used --> the returned Promise will always hold all data
@param [options.sync=false] {boolean} By default, all requests are sent asynchronously. To send synchronous requests, set to true.
This feature only works in the browser: nodejs will always perform asynchronous requests.
@param [options.data] {Object} Data to be sent to the server, either to be used by `query-params` or `body`.
@param [options.headers] {Object} HTTP request headers.
@param [options.responseType] {String} Force the response type.
@param [options.timeout=3000] {number} to timeout the request, leading into a rejected Promise.
@param [options.withCredentials=false] {boolean} Whether or not to send credentials on the request.
@param fulfill {Function} reference to xhr-promise"s fulfill-function
@param reject {Function} reference to xhr-promise"s reject-function
@param promise {Promise} the xhr-promise which will be extended with the `abort()`-method
@private

Initializes the xhr - instance based on the config - params . This method is the standard way of doing xhr - requests without processing streams .


function(xhr, promise, headers, method) {
            // XDR cannot set requestheaders, only XHR:
            if (!xhr._isXDR) {
                var name;
                if ((method!=="POST") && (method!=="PUT")) {
                    // force GET-request to make a request instead of using cache (like IE does):
                    headers["If-Modified-Since"] = "Wed, 15 Nov 1995 01:00:00 GMT";
                    // header "Content-Type" should only be set with POST or PUT requests:
                    delete headers[CONTENT_TYPE];
                }
                // set all headers
                for (name in headers) {
                    xhr.setRequestHeader(name, headers[name]);
                }

                // in case of POST or PUT method: always make sure "Content-Type" is specified
                !BODY_METHODS[method] || (headers && (CONTENT_TYPE in headers)) || xhr.setRequestHeader(CONTENT_TYPE, DEF_CONTENT_TYPE_POST);
            }
        }

Adds the `headers`-object to `xhr`-headers.

@method _setHeaders
@param xhr {Object} containing the xhr-instance
@param headers {Object} containing all headers
@param method {String} the request-method used
@private

Adds the headers - object to xhr - headers .