Input: Options for { @link travisStatus } . [CODESPLIT] function travisStatus ( options , callback ) { if ( ! callback && typeof options === 'function' ) { callback = options ; options = null ; } if ( callback && typeof callback !== 'function' ) { throw new TypeError ( 'callback must be a function' ) ; } let agent , gitChecker , travisChecker ; try { if ( options && typeof options !== 'object' ) { throw new TypeError ( 'options must be an object' ) ; } options = options || { } ; if ( options . repo ) { GitStatusChecker . checkSlugFormat ( options . repo ) ; } if ( options . storeRepo ) { GitStatusChecker . checkSlugFormat ( options . storeRepo ) ; } // If the caller didn't request an agent behavior, control it ourselves. // Each function call will use HTTP keep-alive for the duration of the // function, but not after completion, which callers may not expect. let { requestOpts } = options ; if ( ! requestOpts || ( requestOpts . agent === undefined && requestOpts . agentClass === undefined && requestOpts . agentOptions === undefined && requestOpts . forever === undefined && requestOpts . pool === undefined ) ) { const apiUrl = url . parse ( options . apiEndpoint || TravisStatusChecker . ORG_URI ) ; const Agent = apiUrl . protocol === 'https:' ? https . Agent : apiUrl . protocol === 'http:' ? http . Agent : null ; if ( Agent ) { agent = new Agent ( { keepAlive : true } ) ; // .destroy() and keepAlive added to Agent in 0.11.4, nodejs@9fc9b874 // If Agent doesn't support keepAlive/destroy, we don't need/want it. if ( typeof agent . destroy === 'function' ) { requestOpts = Object . assign ( { } , requestOpts ) ; requestOpts . agent = agent ; options = Object . assign ( { } , options ) ; options . requestOpts = requestOpts ; } else { agent = undefined ; } } } gitChecker = new GitStatusChecker ( options ) ; travisChecker = new TravisStatusChecker ( options ) ; } catch ( errOptions ) { const errResult = Promise . reject ( errOptions ) ; return nodeify ( errResult , callback ) ; } let repoSlugP ; if ( options . storeRepo ) { const storedSlugP = gitChecker . tryStoreSlug ( options . storeRepo ) ; // If both .repo and .storeRepo are present, store .storeRepo and use .repo repoSlugP = options . repo ? storedSlugP . then ( ( ) => options . repo ) : storedSlugP ; } else if ( options . repo ) { repoSlugP = Promise . resolve ( options . repo ) ; } else { const foundSlugP = gitChecker . findSlug ( ) . then ( GitStatusChecker . checkSlugFormat ) ; if ( options . interactive ) { repoSlugP = foundSlugP . then ( ( slug ) => gitChecker . tryStoreSlug ( slug ) ) ; } else { repoSlugP = foundSlugP ; } } let localCommitP ; if ( options . commit ) { localCommitP = gitChecker . resolveHash ( options . commit ) . then ( ( resolved ) => { const localCommit = { sha : resolved } ; if ( resolved !== options . commit ) { localCommit . name = options . commit ; } return localCommit ; } ) ; } // Before doing remote queries, ensure that there are no errors locally const slugForQueryP = Promise . all ( [ repoSlugP , localCommitP ] ) . then ( ( slugAndHash ) => slugAndHash [ 0 ] ) ; let resultP ; if ( options . branch ) { const branchP = options . branch === true ? gitChecker . detectBranch ( ) : Promise . resolve ( options . branch ) ; resultP = Promise . all ( [ slugForQueryP , branchP ] ) . then ( ( results ) => { const slug = results [ 0 ] ; const branch = results [ 1 ] ; return travisChecker . getBranch ( slug , branch , options ) ; } ) ; } else { const repoP = slugForQueryP . then ( ( slug ) => travisChecker . getRepo ( slug , options ) ) ; if ( localCommitP ) { // Add build information to result resultP = repoP . then ( ( repo ) => travisChecker . getBuild ( repo . repo . slug , repo . repo . last_build_id ) . then ( ( build ) => Object . assign ( { } , repo , build ) ) ) ; } else { resultP = repoP ; } } let checkedResultP = resultP ; if ( localCommitP ) { checkedResultP = Promise . all ( [ resultP , localCommitP ] ) . then ( ( all ) => { const result = all [ 0 ] ; const localCommit = all [ 1 ] ; checkBuildCommit ( result , localCommit ) ; return result ; } ) ; } let cleanupP ; if ( agent ) { cleanupP = checkedResultP . then ( ( result ) => { agent . destroy ( ) ; return result ; } , ( err ) => { agent . destroy ( ) ; return Promise . reject ( err ) ; } ) ; } else { cleanupP = checkedResultP ; } return nodeify ( cleanupP , callback ) ; }


Input: Trims a single slash from the end of a string if present . [CODESPLIT] function trimSlash ( string ) { if ( typeof string !== 'string' ) { return string ; } if ( string . length > 0 && string . charAt ( string . length - 1 ) === '/' ) { return string . slice ( 0 , string . length - 1 ) ; } return string ; }


Input: Allows any option to be passed as a function which gets webpack s context as its first argument in case some info from the loader context is necessary [CODESPLIT] function parseOptions ( opts ) { return removeEmpty ( { plugins : convertFn . call ( this , opts . plugins ) , locals : convertFn . call ( this , opts . locals ) , filename : convertFn . call ( this , opts . filename ) , parserOptions : convertFn . call ( this , opts . parserOptions ) , generatorOptions : convertFn . call ( this , opts . generatorOptions ) , runtime : convertFn . call ( this , opts . runtime ) , parser : convertFnSpecial . call ( this , opts . parser ) , multi : convertFn . call ( this , opts . multi ) } ) }


Input: The runtime contains functions which must be converted into strings without any escaping at all . Yes this method of doing so is insane . But it works! [CODESPLIT] function serializeVerbatim ( obj ) { let i = 0 const fns = [ ] let res = JSON . stringify ( obj , ( k , v ) => { if ( typeof v === 'function' ) { fns . push ( v . toString ( ) ) return ` ${ i ++ } ` } else { return v } } ) res = res . replace ( / "__REPLACE(\d{1})" / g , ( m , v ) => { return fns [ v ] } ) return res }


Input: Renders all given pages as static HTML into the destination folder . [CODESPLIT] function renderPages ( filepaths , dest , { templates , vars , statics , disableValidation , cssVariables , host } ) { console . log ( ` \n ` ) ; return Promise . all ( filepaths . map ( filepath => { return sander . readFile ( filepath ) . then ( content => renderPage ( content , filepath , { templates , vars , dest , cssVariables } ) ) . then ( ( [ html , destinationPath , cssParts ] ) => sander . writeFile ( destinationPath , html ) . then ( ( ) => [ destinationPath , cssParts ] ) ) . then ( ( [ destinationPath , cssParts ] ) => { console . log ( ` ${ chalk . bold . green ( figures . tick ) } ${ filepath } ${ destinationPath } ` ) ; return [ destinationPath , cssParts ] ; } ) ; } ) ) . then ( pageResults => disableValidation || validatePages ( host , dest , pageResults . map ( result => result [ 0 ] ) , statics ) . then ( ( ) => pageResults . map ( result => result [ 1 ] ) ) ) ; }


Input: Options for { @link TravisStatusChecker } . [CODESPLIT] function TravisStatusChecker ( options ) { if ( options && typeof options !== 'object' ) { throw new TypeError ( 'options must be an object' ) ; } options = options || { } ; const apiEndpoint = options . apiEndpoint && trimSlash ( options . apiEndpoint ) ; this . _travis = new Travis ( { pro : apiEndpoint === constants . PRO_URI , version : '2.0.0' } ) ; this . _travis . agent = new TravisStatusHttp ( apiEndpoint , options . requestOpts ) ; if ( options . token ) { this . _travis . agent . setAccessToken ( options . token ) ; } }


Input: Options for { @link TravisStatusQueryOptions } . [CODESPLIT] function queryWithWait ( query , valueIsPending , options ) { const maxWaitMs = options && options . wait ? Number ( options . wait ) : 0 ; if ( Number . isNaN ( maxWaitMs ) ) { return Promise . reject ( new TypeError ( 'wait must be a number' ) ) ; } if ( maxWaitMs < 0 ) { return Promise . reject ( new RangeError ( 'wait must be non-negative' ) ) ; } const startMs = Date . now ( ) ; // Note:  Divide by 2 so we can double unconditionally below let nextWaitMs = POLL_TIME_START_MS / 2 ; function doQuery ( cb ) { query . get ( cb ) ; } return new Promise ( ( resolve , reject ) => { function checkBuild ( err , result ) { if ( err ) { reject ( err ) ; return ; } if ( maxWaitMs ) { let isPending ; try { isPending = valueIsPending ( result ) ; } catch ( errPending ) { reject ( errPending ) ; return ; } if ( isPending ) { const nowMs = Date . now ( ) ; const totalWaitMs = nowMs - startMs ; if ( totalWaitMs < maxWaitMs ) { nextWaitMs = Math . min ( nextWaitMs * 2 , POLL_TIME_MAX_MS , maxWaitMs - totalWaitMs ) ; setTimeout ( doQuery , nextWaitMs , checkBuild ) ; return ; } } } resolve ( result ) ; } doQuery ( checkBuild ) ; } ) ; }


Input: analyze [CODESPLIT] function ( input ) { var result = / @charset\s+['|"](\w*)["|']; / . exec ( input ) , charset = 'UTF-8' ; if ( result && result [ 1 ] ) { charset = result [ 1 ] ; } //        else{ //            var detect = jschardet.detect(input); //            if(detect && detect.confidence > 0.9){ //                charset = detect.encoding; //            } //        } return charset ; }


Input: 中文转unicode [CODESPLIT] function ( text ) { text = escape ( text . toString ( ) ) . replace ( / \+ / g , "%2B" ) ; var matches = text . match ( / (%([0-9A-F]{2})) / gi ) ; if ( matches ) { for ( var matchid = 0 ; matchid < matches . length ; matchid ++ ) { var code = matches [ matchid ] . substring ( 1 , 3 ) ; if ( parseInt ( code , 16 ) >= 128 ) { text = text . replace ( matches [ matchid ] , '%u00' + code ) ; } } } text = text . replace ( '%25' , '%u0025' ) ; return text ; }


Input: 从内容中提取import列表 [CODESPLIT] function ( content ) { var reg = / @import\s*(url)?\s*[\('"]+([^'"]+)\.css(\?[^\s]*)?\s*['"\)]+\s*[^;]*; / ig ; var result = reg . exec ( content ) ; if ( result && result [ 2 ] ) { return { match : result [ 0 ] , filePath : result [ 2 ] + '.css' } ; } return null ; }


Input: 修改子文件import的相对路径 子文件夹中所有的相对路径都要进行转换 先看一下什么形式的地址需要转换 [CODESPLIT] function ( content , filePath ) { 'use strict' ; var self = this ; var regImport = / @import\s*(url)?\(?['"]([^'"%]+)\.css['"]\)?[^;]*; / ig , regImageOrFont = / (url)?\(['"]?([^:\)]+\.(png|jpg|gif|jpeg|ttf|eot|woff|svg))([^\)]*)['"]?\) / ig , importResult , picAndFontResult ; var importFilePath = path . dirname ( path . resolve ( self . config . sourceDir , filePath ) ) ; // 替换import importResult = regImport . exec ( content ) ; if ( typeof importResult !== 'undefined' && importResult && importResult [ 2 ] ) { var importAbsoluteUrl = path . resolve ( importFilePath , importResult [ 2 ] ) ; // 用%号表示已经替换好的import路径，后续会再去掉百分号,这里替换的时 // 候要注意全局的替换 var regimportReplace = new RegExp ( importResult [ 2 ] , 'g' ) ; content = content . replace ( regimportReplace , "%" + path . relative ( self . config . sourceDir , importAbsoluteUrl ) ) ; return self . modifySubImportsPath ( content , filePath ) ; } // 替换图片和font的路径 picAndFontResult = regImageOrFont . exec ( content ) ; if ( typeof picAndFontResult !== 'undefined' && picAndFontResult && picAndFontResult [ 2 ] && ! / ^\/\/[^\/]+ / . test ( picAndFontResult [ 2 ] ) ) { var regpicReplace = new RegExp ( picAndFontResult [ 2 ] , 'g' ) ; var picAbsolutePath = path . resolve ( importFilePath , picAndFontResult [ 2 ] ) ; //解决win平台下路径的斜杠问题 var isWin = ( process . platform === 'win32' ) ; var _path = path . relative ( self . config . sourceDir , picAbsolutePath ) ; if ( isWin ) { _path = path . relative ( self . config . sourceDir , picAbsolutePath ) . split ( path . sep ) . join ( "\/" ) ; } // 用：号表示已经替换好的import路径，后续会再去掉冒号 content = content . replace ( regpicReplace , ":" + _path ) ; return self . modifySubImportsPath ( content , filePath ) ; } return content ; }


Input: Options for { @link GitStatusChecker } . [CODESPLIT] function GitStatusChecker ( options ) { if ( options && typeof options !== 'object' ) { throw new TypeError ( 'options must be an object' ) ; } options = Object . assign ( { in : process . stdin , out : process . stdout , err : process . stderr } , options ) ; if ( ! options . in || typeof options . in . read !== 'function' ) { throw new TypeError ( 'options.in must be a stream.Readable' ) ; } if ( ! options . out || typeof options . out . write !== 'function' ) { throw new TypeError ( 'options.out must be a stream.Writable' ) ; } if ( ! options . err || typeof options . err . write !== 'function' ) { throw new TypeError ( 'options.err must be a stream.Writable' ) ; } this . _options = options ; this . _chalk = new Chalk ( { enabled : Boolean ( options . interactive !== undefined ? options . interactive : options . out . isTTY ) } ) ; }


Input: Gets the path portion of a git URL . [CODESPLIT] function gitUrlPath ( gitUrl ) { // Foreign URL for remote helper // See transport_get in transport.c // Note:  url.parse considers second : as part of path.  So check this first. const foreignParts = / ^([A-Za-z0-9][A-Za-z0-9+.-]*)::(.*)$ / . exec ( gitUrl ) ; if ( foreignParts ) { return foreignParts [ 2 ] ; } // Typical URL const gitUrlObj = url . parse ( gitUrl ) ; if ( gitUrlObj . protocol ) { return gitUrlObj . path ; } // SCP-like syntax.  Host can be wrapped in [] to disambiguate path. // See parse_connect_url and host_end in connect.c const scpParts = / ^([^@/]+)@(\[[^]\/]+\]|[^:/]+):(.*)$ / . exec ( gitUrl ) ; if ( scpParts ) { return scpParts [ 3 ] ; } // Assume URL is a local path return gitUrl ; }


Input: Pick env specific robots . txt [CODESPLIT] function ( ) { var appEnv = this . app . env ; if ( process . env . DEPLOY_TARGET ) { appEnv = process . env . DEPLOY_TARGET ; } var publicFiles = new Funnel ( this . app . trees . public ) ; this . _requireBuildPackages ( ) ; fs . stat ( path . join ( this . project . root , 'public' , 'robots.txt' ) , function ( err , stats ) { if ( stats && stats . isFile ( ) ) { console . log ( chalk . yellow ( 'There is a robots.txt in /public and ENV specific robots.txt are ignored!' ) ) ; } } ) ; publicFiles = stew . rename ( publicFiles , 'robots-' + appEnv + '.txt' , 'robots.txt' ) ; return new Funnel ( publicFiles , { srcDir : '/' , destDir : '/' } ) ; }


Input:
## BalanceSheet constructor [CODESPLIT] function BalanceSheet ( options ) { // ## Public properties this . sheets = { } ; this . sheet = null ; log = options . log || log ; /**
 * ### BalanceSheet.options
 *
 * Reference to current configuration
 *
 */ this . options = options || { } ; // ## BalanceSheet methods /**
 * ### BalanceSheet.init
 *
 * Configures the BalanceSheet instance
 *
 * Takes the configuration as an input parameter or
 * recycles the settings in `this.options`.
 *
 * The configuration object is of the type
 *
 * 	var options = {
 * 		returnAt: 'first', // or 'last'
 * 		triggers: [ myFunc,
 * 					myFunc2
 * 		],
 * 	}
 *
 * @param {object} options Optional. Configuration object
 *
 */ BalanceSheet . prototype . init = function ( options ) { this . options = options || this . options ; if ( this . options . returnAt === BalanceSheet . first || this . options . returnAt === BalanceSheet . last ) { this . returnAt = this . options . returnAt ; } this . resetTriggers ( ) ; } ; /**
 * ### BalanceSheet.addSheet
 *
 * Adds a new sheet and sets it as default
 *
 * @param {string} sheet The sheet name
 * @param {object} options. Optional. Configuration options for the sheet
 * @param {array} items. Optional. An initial set of items for the sheet
 * @return {boolean} TRUE, if the sheet is added successfully
 */ //BalanceSheet.prototype.addSheet = function (sheet, pl, options) { //	if (!isValidSheet(sheet)) return false; //	pl = pl || new PlayerList(); // //	this.sheets[sheet] = pl; // //	if (!this.initSheet(sheet, options)) { //		return false; //	} // //	this.sheet = sheet; //	return true; //}; //BalanceSheet.prototype.initSheet = function (sheet, options) { //	if  (!isValidSheet(sheet)) return false; //	this.sheets[sheet].each(function(p){ //		if (!p.__balance) { //			p.__balance = 0; //		} //	}); //}; BalanceSheet . prototype . updateBalance = function ( player , amount ) { if ( ! player || ! amount ) return ; if ( ! this . sheet ) { log ( 'No balance sheet selected' ) ; return ; } if ( ! this . sheet . player ) return } this . sheet . players [ player ] . __balance += amount ; }


Input: //////////////// GROUP [CODESPLIT] function Group ( ) { this . elements = [ ] ; this . matched = [ ] ; this . leftOver = [ ] ; this . pointer = 0 ; this . matches = { } ; this . matches . total = 0 ; this . matches . requested = 0 ; this . matches . done = false ; this . rowLimit = 3 ; this . noSelf = true ; this . pool = [ ] ; this . shuffle = true ; this . stretch = true ; }


Input:
## Group constructor [CODESPLIT] function Group ( options ) { /**
         * ## Group.name
         *
         * The name of the group
         *
         * Must be unique amongst groups
         */ this . name = null ; /**
         * ## Group.elements
         *
         * The elements belonging to this group
         *
         * They can be matched with other elements contained in the _pool_.
         *
         * @see Group.pool
         * @see Group.matched
         */ this . elements = [ ] ; /**
         * ## Group.pool
         *
         * Sets of elements that to match with the group members sequentially
         *
         * It is an array of arrays, and elements in ealier sets are more
         * likely to be matched than subsequent ones.
         *
         * @see Group.elements
         * @see Group.matched
         */ this . pool = [ ] ; /**
         * ## Group.matched
         *
         * Array of arrays of matched elements
         *
         * Each index in the parent array corresponds to a group member,
         * and each array are the matched element for such a member.
         *
         * @see Group.elements
         * @see Group.pool
         */ this . matched = [ ] ; /**
         * ## Group.leftOver
         *
         * Array of elements from the pool that could not be matched
         */ this . leftOver = [ ] ; /**
         * ## Group.pointer
         *
         * Index of the row we are trying to complete currently
         */ this . pointer = 0 ; /**
         * ## Group.matches
         *
         * Summary of matching results
         *
         */ this . matches = { total : 0 , requested : 0 , done : false } ; /**
         * ## Group.rowLimit
         *
         * Number of elements necessary to a row
         *
         * Each group member will be matched with _rowLimit_ elements from
         * the _pool_ elements.
         */ this . rowLimit = 1 ; /**
         * ## Group.noSelf
         *
         * If TRUE, a group member cannot be matched with himself.
         */ this . noSelf = true ; /**
         * ## Group.shuffle
         *
         * If TRUE, all elements of the pool will be randomly shuffled.
         */ this . shuffle = true ; /**
         * ## Group.stretch
         *
         * If TRUE,  each element in the pool will be replicated
         * as many times as the _rowLimit_ variable.
         */ this . stretch = true ; // Init user options. this . init ( options ) ; }


Input: console . log ( getElements () ) console . log ( getPools () ) [CODESPLIT] function simulateMatch ( N ) { for ( var i = 0 ; i < N ; i ++ ) { var rm = new RMatcher ( ) , elements = getElements ( ) , pools = getPools ( ) ; //          console.log('NN ' , numbers); //          console.log(elements); //          console.log(pools) rm . init ( elements , pools ) ; var matched = rm . match ( ) ; if ( ! rm . allGroupsDone ( ) ) { console . log ( 'ERROR' ) ; console . log ( rm . options . elements ) ; console . log ( rm . options . pools ) ; console . log ( matched ) ; } for ( var j = 0 ; j < rm . groups . length ; j ++ ) { var g = rm . groups [ j ] ; for ( var h = 0 ; h < g . elements . length ; h ++ ) { if ( g . matched [ h ] . length !== g . rowLimit ) { console . log ( 'Wrong match: ' + h ) ; console . log ( rm . options . elements ) ; console . log ( rm . options . pools ) ; console . log ( matched ) ; } } } } }


Input:
## SocketDirect constructor [CODESPLIT] function SocketDirect ( node , options ) { options = options || { } ; // ## Private properties /**
         * ### SocketDirect.node
         *
         * Reference to the node object.
         */ this . node = node ; /**
         * ## SocketDirect.socket
         *
         * The SocketDirect object shared with the server
         */ this . socket = options . socket ; /**
         * ## SocketDirect.connected
         *
         * TRUE, if a connection is established
         */ this . connected = false ; }


Input: ## Example object All configuration options are listed below with their default value . [CODESPLIT] function myGame ( ) { this . solo_mode = false ; this . auto_wait = false ; this . auto_step = false ; this . observer = false ; this . minPlayers = 1 ; this . maxPlayers = 1000 ; }


Input:
## GameSession constructor [CODESPLIT] function GameSession ( node ) { SessionManager . call ( this ) ; /**
         * ### GameSession.node
         *
         * The reference to the node object.
         */ this . node = node ; // Register default variables in the session. this . register ( 'player' , { set : function ( p ) { node . createPlayer ( p ) ; } , get : function ( ) { return node . player ; } } ) ; this . register ( 'game.memory' , { set : function ( value ) { node . game . memory . clear ( true ) ; node . game . memory . importDB ( value ) ; } , get : function ( ) { return ( node . game . memory ) ? node . game . memory . fetch ( ) : null ; } } ) ; this . register ( 'events.history' , { set : function ( value ) { node . events . history . history . clear ( true ) ; node . events . history . history . importDB ( value ) ; } , get : function ( ) { return node . events . history ? node . events . history . history . fetch ( ) : null ; } } ) ; this . register ( 'stage' , { set : function ( ) { // GameSession.restoreStage } , get : function ( ) { return node . player . stage ; } } ) ; this . register ( 'node.env' ) ; }


Input: compile hogan template and open index . html [CODESPLIT] function compileIndex ( ) { fs . readFile ( path . join ( __dirname , 'templates' , 'index.hogan' ) , function ( err , data ) { if ( err ) throw err ; // write rendered result to index.html fs . writeFile ( path . join ( __dirname , 'index.html' ) , hogan . compile ( data . toString ( ) ) . render ( { 'schemes' : schemes , 'variations' : variations , 'colors' : colors , 'variants' : variants , } ) , function ( err ) { if ( err ) throw err } ) ; // open index.html in browser open ( path . join ( __dirname , 'index.html' ) ) ; } ) ; }


Input: Sort users by username length . Longest usernames first . [CODESPLIT] function sortMentions ( mentions ) { return mentions . slice ( ) . sort ( ( a , b ) => b . length - a . length ) ; }


Input: Case - insensitively get the correct emoji name from the possible emoji for an input string . [CODESPLIT] function findEmoji ( names , match ) { const compare = match . toLowerCase ( ) ; for ( let i = 0 ; i < names . length ; i += 1 ) { const name = names [ i ] . toLowerCase ( ) ; if ( name === compare ) { return names [ i ] ; } } return null ; }


Input: Create set up and send an asynchronous request to the given path / URL with the given method and parameters . [CODESPLIT] function _request ( path , method , headers , body , withCredentials , callback ) { const xhr = new XMLHttpRequest ( { } ) ; // Set up the event handlers. const handler = evt => { if ( callback ) { callback ( evt ) ; } // The request has been completed: detach all the handlers. xhr . removeEventListener ( 'error' , handler ) ; xhr . removeEventListener ( 'load' , handler ) ; } ; xhr . addEventListener ( 'error' , handler , false ) ; xhr . addEventListener ( 'load' , handler , false ) ; // Set up the request. xhr . open ( method , path , true ) ; Object . keys ( headers || { } ) . forEach ( key => { xhr . setRequestHeader ( key , headers [ key ] ) ; } ) ; if ( withCredentials ) { xhr . withCredentials = withCredentials ; } xhr . send ( body || undefined ) ; return xhr ; }


Input: / --- API [CODESPLIT] function RpcMessage ( opts ) { assert . object ( opts , 'options' ) ; assert . bool ( opts . incoming , 'options.incoming' ) ; assert . optionalNumber ( opts . type , 'options.type' ) ; assert . optionalNumber ( opts . xid , 'options.xid' ) ; stream . Transform . call ( this , opts ) ; this . type = opts . type ; this . xid = opts . xid ; this . incoming = opts . incoming ; this . _rpc_wrote_head = false ; this . _rpc_message = true ; // MDB }


Input: / --- API [CODESPLIT] function parseAuth ( xdr ) { assert . object ( xdr , 'xdr' ) ; var msg = { } ; var type = xdr . readInt ( ) ; var len = xdr . readInt ( ) ; switch ( type ) { case 0 : // null auth msg . type = 'null' ; // length is normally 0 for null auth, but that's not required xdr . xdr_offset += len ; break ; case 1 : // unix msg . type = 'unix' ; msg . stamp = xdr . readInt ( ) ; msg . machinename = xdr . readString ( ) ; msg . uid = xdr . readInt ( ) ; msg . gid = xdr . readInt ( ) ; msg . gids = xdr . readIntArray ( ) ; break ; case 2 : // TODO case 3 : // TODO default : throw new Error ( 'invalid auth type: ' + type ) ; } return ( msg ) ; }


Input: / --- API [CODESPLIT] function PortmapGetPortCall ( opts ) { RpcCall . call ( this , opts ) ; this . mapping = { prog : 0 , vers : 0 , prot : 0 } ; this . _rpc_portmap_get_port_call = true ; // MDB }


Input: / --- API [CODESPLIT] function RpcClient ( opts ) { assert . object ( opts , 'options' ) ; assert . object ( opts . log , 'options.log' ) ; assert . number ( opts . program , 'options.program' ) ; assert . number ( opts . version , 'options.version' ) ; assert . string ( opts . url , 'options.url' ) ; EventEmitter . call ( this , opts ) ; var self = this ; this . conn = null ; this . log = opts . log . child ( { component : 'RpcClient' , serializers : require ( './bunyan' ) . serializers } ) ; this . messages = { } ; this . program = opts . program ; this . url = mod_url . parse ( opts . url ) ; this . version = opts . version ; var ID = 0 ; this . _next_xid = function ( ) { if ( ++ ID === ( Math . pow ( 2 , 32 ) - 1 ) ) ID = 0 ; return ( ID ) ; } ; this . _rpc_client = true ; // MDB ::findjsobjects flag this . conn = net . createConnection ( { port : this . url . port , host : this . url . hostname } ) ; this . conn . once ( 'error' , function onErr ( e ) { self . emit ( 'error' , e ) ; return ; } ) ; this . conn . once ( 'connect' , function onConnect ( ) { var parser = new RpcParser ( { log : self . log } ) ; parser . on ( 'message' , function onRpcMessage ( msg ) { var cfg = self . messages [ msg . xid ] ; var res ; if ( ! cfg ) { self . emit ( 'error' , new Error ( 'unsolicited RPC message' ) , msg ) ; return ; } if ( cfg . reply ) { res = new cfg . reply ( msg ) ; msg . pipe ( res ) ; } else { res = msg ; } msg . once ( 'end' , function cleanupMessageTable ( ) { if ( self . messages [ msg . xid ] ) delete self . messages [ msg . xid ] ; } ) ; var _cb = cfg . cb ; var _err = null ; if ( msg . reply_stat === 0 ) { switch ( msg . accept_stat ) { case 0 : break ; case 1 : _err = new errors . RpcProgramUnavailableError ( ) ; break ; case 2 : _err = new errors . RpcProgramMismatchError ( ) ; _err . mismatch_info = msg . mismatch_info ; break ; case 3 : _err = new errors . RpcProcedureUnavailableError ( ) ; break ; case 4 : _err = new errors . RpcGarbageArgumentsError ( ) ; break ; default : _err = new errors . RpcError ( 'invalid rpc.accept_stat: ' + msg . accept_stat ) ; break ; } } else if ( msg . reply_stat === 1 ) { if ( msg . reject_stat === 0 ) { _err = new errors . RpcMismatchError ( ) ; _err . mismatch_info = msg . mismatch_info ; } else { _err = new errors . RpcAuthError ( ) ; _err . auth_stat = msg . auth_stat ; } } process . nextTick ( function emitRpcReply ( ) { if ( _err ) { _cb ( _err , msg ) ; } else { _cb ( null , res , msg ) ; } } ) ; } ) ; self . conn . pipe ( parser ) ; self . emit ( 'connect' ) ; } ) ; this . _rpc_client = true ; // MDB }


Input: / --- API [CODESPLIT] function RpcCall ( opts ) { assert . object ( opts , 'options' ) ; RpcMessage . call ( this , opts ) ; this . rpcvers = opts . rpcvers || 2 ; this . prog = opts . prog ; this . vers = opts . vers ; this . proc = opts . proc ; this . auth = opts . auth || { } ; this . verifier = opts . verifier ; this . type = 0 ; this . _buffer = null ; this . _rpc_call = true ; // MDB }


Input: / --- API [CODESPLIT] function PortmapSetCall ( opts ) { RpcCall . call ( this , opts ) ; this . mapping = { prog : 0 , vers : 0 , prot : 0 , port : 0 } ; this . _rpc_portmap_set_call = true ; // MDB }


Input: / --- API [CODESPLIT] function RpcError ( cause , msg ) { var off = 0 ; if ( cause instanceof Error ) off = 1 ; var args = Array . prototype . slice . call ( arguments , off ) ; args . unshift ( { cause : off ? cause : undefined , ctor : RpcError } ) ; WError . apply ( this , args ) ; this . type = 1 ; // reply }


Input: / --- API [CODESPLIT] function PortmapClient ( opts ) { assert . object ( opts , 'options' ) ; if ( opts . log ) { var l = opts . log ; delete opts . log ; } var _opts = clone ( opts ) ; _opts . log = opts . log = l ; _opts . name = 'portmap' ; _opts . program = 100000 ; _opts . version = 2 ; RpcClient . call ( this , _opts ) ; }


Input: / --- Private Methods this is bound to an RpcServer [CODESPLIT] function ifError ( n ) { function _ifError ( err ) { if ( err ) { err . _rpc_next = n ; throw err ; } } return ( _ifError ) ; }


Input: An RPC service is identified by its RPC program number version number and the transport address where it may be reached . The transport address in turn consists of a network address and a transport selector . In the case of a service available over TCP / IP or UDP / IP the network address will be an IP address and the transport selector will be a TCP or UDP port number . [CODESPLIT] function RpcServer ( opts ) { assert . object ( opts , 'options' ) ; assert . object ( opts . log , 'options.log' ) ; assert . number ( opts . program , 'options.program' ) ; var v = opts . version ; if ( typeof ( v ) === 'number' ) v = [ v ] ; assert . arrayOfNumber ( v , 'options.version' ) ; net . Server . call ( this , opts ) ; this . log = opts . log . child ( { component : 'RpcServer' } , true ) ; this . name = opts . name || 'RpcServer' ; this . program = opts . program ; this . rpc_table = { } ; this . saved_handlers = [ ] ; this . version = v . slice ( ) ; this . on ( 'connection' , onConnection . bind ( this ) ) ; }


Input: / --- API RpcParser [CODESPLIT] function RpcParser ( opts ) { assert . optionalObject ( opts , 'options' ) ; stream . Writable . call ( this , opts ) ; this . _buffer = null ; this . rpc_table = { } ; // TODO - use this when fragments are supported this . _rpc_parser = true ; // MDB flag }


Input: / --- API [CODESPLIT] function RpcReply ( opts ) { RpcMessage . call ( this , opts ) ; this . _buffer = null ; this . rpc_reply_header_sent = false ; this . type = 1 ; }


Input: / --- API [CODESPLIT] function PortmapUnsetCall ( opts ) { RpcCall . call ( this , opts ) ; this . mapping = { prog : 0 , vers : 0 , prot : 0 , port : 0 } ; this . _rpc_portmap_unset_call = true ; // MDB }


Input: / --- API [CODESPLIT] function PortmapServer ( opts ) { assert . object ( opts , 'options' ) ; if ( opts . log ) { var l = opts . log ; delete opts . log ; } var _opts = clone ( opts ) ; _opts . log = opts . log = l ; _opts . name = 'portmap' ; _opts . program = 100000 ; _opts . version = 2 ; RpcServer . call ( this , _opts ) ; }


Input: / --- API A set of helper functions for serdes on XDR datatypes . [CODESPLIT] function XDR ( buf ) { if ( buf ) assert . ok ( Buffer . isBuffer ( buf ) , 'buffer is required' ) ; this . xdr_buffer = buf || null ; this . xdr_offset = 0 ; }


Input: / * :: type BoxenOptions = { [ id : string ] : any } see : https : // github . com / sindresorhus / boxen#boxeninput - options [CODESPLIT] function notify ( opts /* : BoxenNotifyOptions */ ) { const isNpm = require ( 'is-npm' ) ; if ( ! process . stdout . isTTY || isNpm ) { return ; } const boxen = require ( 'boxen' ) ; opts = opts || { } ; opts . defer = typeof opts . defer === 'boolean' ? opts . defer : false ; opts . message = opts . message || '' ; opts . boxenOpts = opts . boxenOpts || { padding : 1 , margin : 1 , align : 'center' , borderColor : 'yellow' , borderStyle : 'round' , } ; const message = '\n' + boxen ( opts . message , opts . boxenOpts ) ; if ( opts . defer === false ) { console . error ( message ) ; } else { process . on ( 'exit' , function ( ) { console . error ( message ) ; } ) ; process . on ( 'SIGINT' , function ( ) { console . error ( '\n' + message ) ; } ) ; } }


Input: ------------------------------------------------------------------------ Validate and add in templates directory source . ------------------------------------------------------------------------ [CODESPLIT] function ( cb ) { var templatesDir = self . data . _templatesDir ; var templatesPath = path . join ( self . src , "extracted" , templatesDir ) ; fs . stat ( templatesPath , function ( err , stats ) { if ( err ) { if ( err . code === "ENOENT" ) { return void cb ( new Error ( "Templates path '" + templatesPath + "' directory not found" ) ) ; } return void cb ( err ) ; } if ( ! stats . isDirectory ( ) ) { return void cb ( new Error ( "Templates path '" + templatesPath + "' exists, but is not a directory" ) ) ; } cb ( null , templatesPath ) ; } ) ; }


Input: ------------------------------------------------------------------------ Require empty target destination . ------------------------------------------------------------------------ [CODESPLIT] function ( cb ) { fs . stat ( self . dest , function ( err ) { if ( err ) { // Proxy all errors except not found. return void cb ( err . code === "ENOENT" ? null : err ) ; } // Otherwise exists. cb ( new Error ( "Path: " + self . dest + " already exists" ) ) ; } ) ; }


Input: Install an npm package ( [ str ] |str obj obj fn ) - > null [CODESPLIT] function npmInstallPackage ( deps , opts , cb ) { if ( ! cb ) { cb = opts opts = { } } deps = Array . isArray ( deps ) ? deps : [ deps ] opts = opts || opts cb = cb || noop var args = [ ] if ( opts . save ) args . push ( '-S' ) if ( opts . saveDev ) args . push ( '-D' ) if ( opts . global ) args . push ( '-g' ) if ( opts . cache ) args . push ( '--cache-min Infinity' ) if ( opts . silent === false ) { deps . forEach ( function ( dep ) { process . stdout . write ( 'pkg: ' + dep + '\n' ) } ) } var cliArgs = [ 'npm i' ] . concat ( args , deps ) . join ( ' ' ) exec ( cliArgs , function ( err , name ) { if ( err ) return cb ( err ) cb ( ) } ) }


Input: Wrap a function in a fiber . Correctly handles expected presence of done callback [CODESPLIT] function fiberize ( fn ) { return function ( done ) { var self = this ; Fiber ( function ( ) { try { if ( fn . length == 1 ) { fn . call ( self , done ) ; } else { fn . call ( self ) ; done ( ) ; } } catch ( e ) { process . nextTick ( function ( ) { throw ( e ) ; } ) ; } } ) . run ( ) ; } ; }


Input: Find matches for a regular expression in a string and push their details to parts Type is a for IDs b for classes attributes and pseudo - classes and c for elements and pseudo - elements [CODESPLIT] function ( regex , type , types , selector ) { var matches = selector . match ( regex ) ; if ( matches ) { for ( var i = 0 ; i < matches . length ; i ++ ) { types [ type ] ++ ; // Replace this simple selector with whitespace so it won't be counted in further simple selectors selector = selector . replace ( matches [ i ] , ' ' ) ; } } return selector ; }


Input: Calculate the specificity for a selector by dividing it into simple selectors and counting them [CODESPLIT] function ( selector ) { var commaIndex = selector . indexOf ( ',' ) ; if ( commaIndex !== - 1 ) { selector = selector . substring ( 0 , commaIndex ) ; } var types = { a : 0 , b : 0 , c : 0 } ; // Remove the negation psuedo-class (:not) but leave its argument because specificity is calculated on its argument selector = selector . replace ( notRegex , ' $1 ' ) ; // Remove anything after a left brace in case a user has pasted in a rule, not just a selector selector = selector . replace ( ruleRegex , ' ' ) ; // Add attribute selectors to parts collection (type b) selector = findMatch ( attributeRegex , 'b' , types , selector ) ; // Add ID selectors to parts collection (type a) selector = findMatch ( idRegex , 'a' , types , selector ) ; // Add class selectors to parts collection (type b) selector = findMatch ( classRegex , 'b' , types , selector ) ; // Add pseudo-element selectors to parts collection (type c) selector = findMatch ( pseudoElementRegex , 'c' , types , selector ) ; // Add pseudo-class selectors to parts collection (type b) selector = findMatch ( pseudoClassRegex , 'b' , types , selector ) ; // Remove universal selector and separator characters selector = selector . replace ( separatorRegex , ' ' ) ; // Remove any stray dots or hashes which aren't attached to words // These may be present if the user is live-editing this selector selector = selector . replace ( straysRegex , ' ' ) ; // The only things left should be element selectors (type c) findMatch ( elementRegex , 'c' , types , selector ) ; return ( types . a * 100 ) + ( types . b * 10 ) + ( types . c * 1 ) ; }


Input: @function can - log / dev . stringify stringify @parent can - log @description @hide [CODESPLIT] function ( value ) { var flagUndefined = function flagUndefined ( key , value ) { return value === undefined ? "/* void(undefined) */" : value ; } ; return JSON . stringify ( value , flagUndefined , "  " ) . replace ( / "\/\* void\(undefined\) \*\/" / g , "undefined" ) ; }


Input: Adds an index to a collection [CODESPLIT] function ( collectionName , indexName , columns , unique , callback ) { var options = { indexName : indexName , columns : columns , unique : unique } ; return this . _run ( 'createIndex' , collectionName , options ) . nodeify ( callback ) ; }


Input: Inserts a migration record into the migration collection [CODESPLIT] function ( name , callback ) { return this . _run ( 'insert' , this . internals . migrationTable , { name : name , run_on : new Date ( ) } ) . nodeify ( callback ) ; }


Input: Inserts a seeder record into the seeder collection [CODESPLIT] function ( name , callback ) { return this . _run ( 'insert' , this . internals . seedTable , { name : name , run_on : new Date ( ) } ) . nodeify ( callback ) ; }


Input: Gets a connection and runs a mongo command and returns the results [CODESPLIT] function ( command , collection , options , callback ) { var args = this . _makeParamArgs ( arguments ) , sort = null , callback = args [ 2 ] ; log . sql . apply ( null , arguments ) ; if ( options && typeof ( options ) === 'object' ) { if ( options . sort ) sort = options . sort ; } if ( this . internals . dryRun ) { return Promise . resolve ( ) . nodeify ( callback ) ; } return new Promise ( function ( resolve , reject ) { var prCB = function ( err , data ) { return ( err ? reject ( err ) : resolve ( data ) ) ; } ; // Get a connection to mongo this . connection . connect ( this . connectionString , function ( err , db ) { if ( err ) { prCB ( err ) ; } // Callback function to return mongo records var callbackFunction = function ( err , data ) { if ( err ) { prCB ( err ) ; } prCB ( null , data ) ; db . close ( ) ; } ; // Depending on the command, we need to use different mongo methods switch ( command ) { case 'find' : if ( sort ) { db . collection ( collection ) [ command ] ( options . query ) . sort ( sort ) . toArray ( callbackFunction ) ; } else { db . collection ( collection ) [ command ] ( options ) . toArray ( callbackFunction ) ; } break ; case 'renameCollection' : db [ command ] ( collection , options . newCollection , callbackFunction ) ; break ; case 'createIndex' : db [ command ] ( collection , options . columns , { name : options . indexName , unique : options . unique } , callbackFunction ) ; break ; case 'dropIndex' : db . collection ( collection ) [ command ] ( options . indexName , callbackFunction ) ; break ; case 'insert' : // options is the records to insert in this case if ( util . isArray ( options ) ) db . collection ( collection ) . insertMany ( options , { } , callbackFunction ) ; else db . collection ( collection ) . insertOne ( options , { } , callbackFunction ) ; break ; case 'remove' : // options is the records to insert in this case if ( util . isArray ( options ) ) db . collection ( collection ) . deleteMany ( options , callbackFunction ) ; else db . collection ( collection ) . deleteOne ( options , callbackFunction ) ; break ; case 'collections' : db . collections ( callbackFunction ) ; break ; case 'indexInformation' : db . indexInformation ( collection , callbackFunction ) ; break ; case 'dropDatabase' : db . dropDatabase ( callbackFunction ) ; break ; case 'update' : db . collection ( collection ) [ command ] ( options . query , options . update , options . options , callbackFunction ) ; break ; case 'updateMany' : db . collection ( collection ) [ command ] ( options . query , options . update , options . options , callbackFunction ) ; break ; case 'getDbInstance' : prCB ( null , db ) ; // When the user wants to get the DB instance we need to return the promise callback, so the DB connection is not automatically closed break ; default : db [ command ] ( collection , callbackFunction ) ; break ; } } ) ; } . bind ( this ) ) . nodeify ( callback ) ; }


Input: Callback function to return mongo records [CODESPLIT] function ( err , data ) { if ( err ) { prCB ( err ) ; } prCB ( null , data ) ; db . close ( ) ; }


Input: Returns default params overrides if provided with values [CODESPLIT] function parseParameters ( options ) { var opt = { maximumAge : 0 , enableHighAccuracy : true , timeout : Infinity , interval : 6000 , fastInterval : 1000 , priority : PRIORITY_HIGH_ACCURACY } ; if ( options ) { if ( options . maximumAge !== undefined && ! isNaN ( options . maximumAge ) && options . maximumAge > 0 ) { opt . maximumAge = options . maximumAge ; } if ( options . enableHighAccuracy !== undefined ) { opt . enableHighAccuracy = options . enableHighAccuracy ; } if ( options . timeout !== undefined && ! isNaN ( options . timeout ) ) { if ( options . timeout < 0 ) { opt . timeout = 0 ; } else { opt . timeout = options . timeout ; } } if ( options . interval !== undefined && ! isNaN ( options . interval ) && options . interval > 0 ) { opt . interval = options . interval ; } if ( options . fastInterval !== undefined && ! isNaN ( options . fastInterval ) && options . fastInterval > 0 ) { opt . fastInterval = options . fastInterval ; } if ( options . priority !== undefined && ! isNaN ( options . priority ) && options . priority >= PRIORITY_NO_POWER && options . priority <= PRIORITY_HIGH_ACCURACY ) { if ( options . priority === PRIORITY_NO_POWER ) { opt . priority = PRIORITY_NO_POWER ; } if ( options . priority === PRIORITY_LOW_POWER ) { opt . priority = PRIORITY_LOW_POWER ; } if ( options . priority === PRIORITY_BALANCED_POWER_ACCURACY ) { opt . priority = PRIORITY_BALANCED_POWER_ACCURACY ; } if ( options . priority === PRIORITY_HIGH_ACCURACY ) { opt . priority = PRIORITY_HIGH_ACCURACY ; } } } return opt ; }


Input: Tests whether the given props object contains a property with the name of propNameOrFunction . [CODESPLIT] function noProp ( props , propNameOrFunction ) { if ( ! props ) { throw new Error ( 'Headful: You must pass all declared props when you use headful.props.x() calls.' ) ; } const propName = typeof propNameOrFunction === 'function' ? propNameOrFunction . name : propNameOrFunction ; return ! props . hasOwnProperty ( propName ) ; }


Input: GifCli Converts the gif file into ASCII frames . [CODESPLIT] function GifCli ( path , callback ) { var frames = [ ] ; OneByOne ( [ Tmp . dir , function ( next , tmpDir ) { var str = Fs . createReadStream ( path ) , isFinished = false , complete = [ ] , i = 0 ; str . on ( "end" , function ( ) { isFinished = true ; } ) ; str . pipe ( GifExplode ( function ( frame ) { Tmp . file ( { postfix : ".gif" , } , function ( err , cImg ) { ( function ( i , cImg ) { if ( err ) { return next ( err ) ; } var wStr = Fs . createWriteStream ( cImg ) ; frame . pipe ( wStr ) ; complete [ i ] = false ; wStr . on ( "close" , function ( ) { // TODO Allow passing options ImageToAscii ( cImg , function ( err , asciified ) { complete [ i ] = true ; frames [ i ] = asciified || "" ; // TODO https://github.com/hughsk/gif-explode/issues/4 //if (err) { return next(err); } if ( ! isFinished ) { return ; } if ( ! complete . filter ( function ( c ) { return c !== true } ) . length ) { next ( ) ; } } ) ; } ) ; } ) ( i ++ , cImg ) ; } ) ; } ) ) ; } , function ( next ) { frames = frames . filter ( Boolean ) ; next ( ) ; } ] , function ( err ) { if ( err ) { return callback ( err ) ; } callback ( null , frames ) ; } ) ; }


Input: assert ( test? : boolean message? : string optionalParams : any [] ) : void ; [CODESPLIT] function ( test , message , optionalParams ) { return invoke ( 'CONSOLE' , { type : 'assert' , test : test , message : message , optionalParams : optionalParams || [ ] } ) ; }


Input: Test functional [CODESPLIT] function operationDataBase ( webview , db ) { console . log ( 'open then' ) ; db . executeSql ( 'SELECT 1 FROM Version LIMIT 1' ) . then ( function ( result ) { console . log ( 'executeSql then' ) ; console . log ( result ) ; function queryEmployees ( tx ) { console . log ( "Executing employee query" ) ; tx . executeSql ( 'SELECT a.name, b.name as deptName FROM Employees a, Departments b WHERE a.department = b.department_id' ) . then ( ( [ tx , results ] ) => { var payload = { } payload . result = [ ] payload . type = 'OPERATION_DATABASEE_DONE_QUERY_DB' ; var len = results . rows . length ; for ( let i = 0 ; i < len ; i ++ ) { let row = results . rows . item ( i ) ; payload . result . push ( row ) } webview . postMessage ( JSON . stringify ( payload ) ) ; } ) . catch ( ( error ) => { console . log ( error ) ; } ) ; } db . transaction ( queryEmployees ) . then ( ( ) => { console . log ( 'query done.' ) } ) ; } ) . catch ( function ( err ) { console . log ( 'executeSql catch' ) ; console . log ( err ) ; db . transaction ( function ( tx ) { tx . executeSql ( 'DROP TABLE IF EXISTS Employees;' ) ; tx . executeSql ( 'DROP TABLE IF EXISTS Offices;' ) ; tx . executeSql ( 'DROP TABLE IF EXISTS Departments;' ) ; tx . executeSql ( 'CREATE TABLE IF NOT EXISTS Version( ' + 'version_id INTEGER PRIMARY KEY NOT NULL); ' ) . catch ( ( error ) => { console . log ( error ) ; } ) ; tx . executeSql ( 'CREATE TABLE IF NOT EXISTS Departments( ' + 'department_id INTEGER PRIMARY KEY NOT NULL, ' + 'name VARCHAR(30) ); ' ) . catch ( ( error ) => { console . log ( error ) } ) ; tx . executeSql ( 'CREATE TABLE IF NOT EXISTS Offices( ' + 'office_id INTEGER PRIMARY KEY NOT NULL, ' + 'name VARCHAR(20), ' + 'longtitude FLOAT, ' + 'latitude FLOAT ) ; ' ) . catch ( ( error ) => { console . log ( error ) } ) ; tx . executeSql ( 'CREATE TABLE IF NOT EXISTS Employees( ' + 'employe_id INTEGER PRIMARY KEY NOT NULL, ' + 'name VARCHAR(55), ' + 'office INTEGER, ' + 'department INTEGER, ' + 'FOREIGN KEY ( office ) REFERENCES Offices ( office_id ) ' + 'FOREIGN KEY ( department ) REFERENCES Departments ( department_id ));' ) . catch ( ( error ) => { console . log ( error ) } ) ; tx . executeSql ( 'INSERT INTO Departments (name) VALUES ("Client Services");' ) ; tx . executeSql ( 'INSERT INTO Departments (name) VALUES ("Investor Services");' ) ; tx . executeSql ( 'INSERT INTO Departments (name) VALUES ("Shipping");' ) ; tx . executeSql ( 'INSERT INTO Departments (name) VALUES ("Direct Sales");' ) ; tx . executeSql ( 'INSERT INTO Offices (name, longtitude, latitude) VALUES ("Denver", 59.8,  34.1);' ) ; tx . executeSql ( 'INSERT INTO Offices (name, longtitude, latitude) VALUES ("Warsaw", 15.7, 54.1);' ) ; tx . executeSql ( 'INSERT INTO Offices (name, longtitude, latitude) VALUES ("Berlin", 35.3, 12.1);' ) ; tx . executeSql ( 'INSERT INTO Offices (name, longtitude, latitude) VALUES ("Paris", 10.7, 14.1);' ) ; tx . executeSql ( 'INSERT INTO Employees (name, office, department) VALUES ("Sylvester Stallone", 2,  4);' ) ; tx . executeSql ( 'INSERT INTO Employees (name, office, department) VALUES ("Elvis Presley", 2, 4);' ) ; tx . executeSql ( 'INSERT INTO Employees (name, office, department) VALUES ("Leslie Nelson", 3,  4);' ) ; tx . executeSql ( 'INSERT INTO Employees (name, office, department) VALUES ("Fidel Castro", 3, 3);' ) ; tx . executeSql ( 'INSERT INTO Employees (name, office, department) VALUES ("Bill Clinton", 1, 3);' ) ; tx . executeSql ( 'INSERT INTO Employees (name, office, department) VALUES ("Margaret Thatcher", 1, 3);' ) ; tx . executeSql ( 'INSERT INTO Employees (name, office, department) VALUES ("Donald Trump", 1, 3);' ) ; tx . executeSql ( 'INSERT INTO Employees (name, office, department) VALUES ("Dr DRE", 2, 2);' ) ; tx . executeSql ( 'INSERT INTO Employees (name, office, department) VALUES ("Samantha Fox", 2, 1);' ) ; console . log ( "all executed SQL done" ) ; webview . postMessage ( JSON . stringify ( { type : "OPERATION_DATABASEE_DONE_CREATE_TABLE_AND_INSERT_DATA" , result : 'init table done.' } ) ) ; } ) } ) }


Input: Delegate function for each log level [CODESPLIT] function delegate ( method , _args ) { var callPosition = metalogger . callposition ( ) , file , line ; if ( ! metalogger . shouldLog ( method , _level ) ) { return ; } var args = Array . prototype . slice . call ( _args ) ; var message = [ ] ; if ( args . length === 1 ) { message . push ( util . inspect ( args [ 0 ] , { showHidden : true , depth : null } ) ) ; } if ( args . length === 2 ) { message . push ( args . shift ( ) ) ; message . push ( util . inspect ( args [ 0 ] , { showHidden : true , depth : null } ) ) ; } if ( args . length > 2 ) { message . push ( args . shift ( ) ) ; message . push ( util . format . apply ( null , args ) ) ; } try { file = callPosition . split ( ':' ) [ 0 ] . replace ( ' [' , '' ) ; line = callPosition . split ( ':' ) [ 1 ] . replace ( '] ' , '' ) ; } catch ( e ) { // something went wrong with stack trace } var jsonFormat = { timestamp : ( new Date ( ) ) . toISOString ( ) , hostname : os . hostname ( ) , level : method , file : file , line : line , message : message . join ( ' ' ) } ; if ( options . token ) { client . log ( jsonFormat , function ( err ) { if ( err ) { console . error ( 'error occured while logging to loggly' , err ) ; } } ) ; } else { console . error ( 'Loggly auth token not provided' ) ; } }


Input: Delegate function for each log level [CODESPLIT] function delegate ( method , _args ) { var callPosition = metalogger . callposition ( ) , file , line ; if ( ! metalogger . shouldLog ( method , _level ) ) { return ; } var args = Array . prototype . slice . call ( _args ) ; var message = '' , inspect = null ; message = util . inspect ( args . shift ( ) , { showHidden : true , depth : null } ) . replace ( / \n / g , ' ' ) ; inspect = args [ 0 ] ; if ( args . length > 2 ) { inspect = util . format . apply ( null , args ) ; } try { file = callPosition . split ( ':' ) [ 0 ] . replace ( ' [' , '' ) ; line = callPosition . split ( ':' ) [ 1 ] . replace ( '] ' , '' ) ; } catch ( e ) { // something went wrong with stack trace } var jsonFormat = { timestamp : ( new Date ( ) ) . toISOString ( ) , hostname : os . hostname ( ) , level : method , file : file , line : line , debug : inspect } ; if ( bucketDetails . bucket . length !== 0 && bucketDetails . access_key_id . length !== 0 && bucketDetails . secret_access_key . length !== 0 ) { client . write ( util . format ( "%s %s [host=%s] [message=%s] [message.stream] %s\n" , jsonFormat . timestamp , method . toUpperCase ( ) , jsonFormat . hostname , message , JSON . stringify ( jsonFormat ) ) ) ; } else { console . error ( 'Configuration: Sumologic is not configured correctly, please provide `NODE_LOGGER_S3_BUCKET`, `NODE_LOGGER_S3_KEY_ID`, and `NODE_LOGGER_S3_KEY_SECRET` environment variables.' ) ; } }


Input: Should I log? [CODESPLIT] function shouldLog ( testlevel , thresholdLevel ) { var allowed = logLevelAllowedGranular ( testlevel ) ; if ( allowed ) { return true ; } return logLevelAllowed ( testlevel , thresholdLevel ) ; }


Input: As opposed to logLevelAllowed () this one doesn t take testlevel since that needs to be figured out in - function . [CODESPLIT] function logLevelAllowedGranular ( testlevel ) { if ( ! _granularlevels ) { return ; } var pos = callpositionObj ( ) ; if ( pos ) { var key = 'NODE_LOGGER_LEVEL_' + pos . filename . replace ( / [\.\/] / gi , '_' ) ; if ( key in process . env && process . env [ key ] ) { var thresholdLevel = process . env [ key ] . toLowerCase ( ) ; return logLevelsObj [ testlevel ] <= logLevelsObj [ thresholdLevel ] ; } } }


Input: Return the true value for this specific checkbox . [CODESPLIT] function ( ) { if ( attrs . type === 'radio' ) { return attrs . value || $parse ( attrs . ngValue ) ( scope ) || true ; } var trueValue = ( $parse ( attrs . ngTrueValue ) ( scope ) ) ; if ( angular . isUndefined ( trueValue ) ) { trueValue = true ; } return trueValue ; }


Input: Get the value of the angular - bound attribute given its name . The returned value may or may not equal the attribute value as it may be transformed by a function . [CODESPLIT] function ( attrName ) { var map = { 'switchRadioOff' : getBooleanFromStringDefTrue , 'switchActive' : function ( value ) { return ! getBooleanFromStringDefTrue ( value ) ; } , 'switchAnimate' : getBooleanFromStringDefTrue , 'switchLabel' : function ( value ) { return value ? value : ' ' ; } , 'switchIcon' : function ( value ) { if ( value ) { return '' ; } } , 'switchWrapper' : function ( value ) { return value || 'wrapper' ; } , 'switchInverse' : getBooleanFromString , 'switchReadonly' : getBooleanFromString , 'switchChange' : getExprFromString } ; var transFn = map [ attrName ] || getValueOrUndefined ; return transFn ( attrs [ attrName ] ) ; }


Input: Set a bootstrapSwitch parameter according to the angular - bound attribute . The parameter will be changed only if the switch has already been initialized ( to avoid creating it before the model is ready ) . [CODESPLIT] function ( element , attr , modelAttr ) { if ( ! isInit ) { return ; } var newValue = getSwitchAttrValue ( modelAttr ) ; element . bootstrapSwitch ( attr , newValue ) ; }


Input: If the directive has not been initialized yet do so . [CODESPLIT] function ( ) { // if it's the first initialization if ( ! isInit ) { var viewValue = ( controller . $modelValue === getTrueValue ( ) ) ; isInit = ! isInit ; // Bootstrap the switch plugin element . bootstrapSwitch ( { radioAllOff : getSwitchAttrValue ( 'switchRadioOff' ) , disabled : getSwitchAttrValue ( 'switchActive' ) , state : viewValue , onText : getSwitchAttrValue ( 'switchOnText' ) , offText : getSwitchAttrValue ( 'switchOffText' ) , onColor : getSwitchAttrValue ( 'switchOnColor' ) , offColor : getSwitchAttrValue ( 'switchOffColor' ) , animate : getSwitchAttrValue ( 'switchAnimate' ) , size : getSwitchAttrValue ( 'switchSize' ) , labelText : attrs . switchLabel ? getSwitchAttrValue ( 'switchLabel' ) : getSwitchAttrValue ( 'switchIcon' ) , wrapperClass : getSwitchAttrValue ( 'switchWrapper' ) , handleWidth : getSwitchAttrValue ( 'switchHandleWidth' ) , labelWidth : getSwitchAttrValue ( 'switchLabelWidth' ) , inverse : getSwitchAttrValue ( 'switchInverse' ) , readonly : getSwitchAttrValue ( 'switchReadonly' ) } ) ; if ( attrs . type === 'radio' ) { controller . $setViewValue ( controller . $modelValue ) ; } else { controller . $setViewValue ( viewValue ) ; } } }


Input: Listen to model changes . [CODESPLIT] function ( ) { attrs . $observe ( 'switchActive' , function ( newValue ) { var active = getBooleanFromStringDefTrue ( newValue ) ; // if we are disabling the switch, delay the deactivation so that the toggle can be switched if ( ! active ) { $timeout ( setActive ) ; } else { // if we are enabling the switch, set active right away setActive ( ) ; } } ) ; // When the model changes controller . $render = function ( ) { initMaybe ( ) ; var newValue = controller . $modelValue ; if ( newValue !== undefined && newValue !== null ) { element . bootstrapSwitch ( 'state' , newValue === getTrueValue ( ) , true ) ; } else { element . bootstrapSwitch ( 'indeterminate' , true , true ) ; controller . $setViewValue ( undefined ) ; } switchChange ( ) ; } ; // angular attribute to switch property bindings var bindings = { 'switchRadioOff' : 'radioAllOff' , 'switchOnText' : 'onText' , 'switchOffText' : 'offText' , 'switchOnColor' : 'onColor' , 'switchOffColor' : 'offColor' , 'switchAnimate' : 'animate' , 'switchSize' : 'size' , 'switchLabel' : 'labelText' , 'switchIcon' : 'labelText' , 'switchWrapper' : 'wrapperClass' , 'switchHandleWidth' : 'handleWidth' , 'switchLabelWidth' : 'labelWidth' , 'switchInverse' : 'inverse' , 'switchReadonly' : 'readonly' } ; var observeProp = function ( prop , bindings ) { return function ( ) { attrs . $observe ( prop , function ( ) { setSwitchParamMaybe ( element , bindings [ prop ] , prop ) ; } ) ; } ; } ; // for every angular-bound attribute, observe it and trigger the appropriate switch function for ( var prop in bindings ) { attrs . $observe ( prop , observeProp ( prop , bindings ) ) ; } }


Input: Listen to view changes . [CODESPLIT] function ( ) { if ( attrs . type === 'radio' ) { // when the switch is clicked element . on ( 'change.bootstrapSwitch' , function ( e ) { // discard not real change events if ( ( controller . $modelValue === controller . $viewValue ) && ( e . target . checked !== $ ( e . target ) . bootstrapSwitch ( 'state' ) ) ) { // $setViewValue --> $viewValue --> $parsers --> $modelValue // if the switch is indeed selected if ( e . target . checked ) { // set its value into the view controller . $setViewValue ( getTrueValue ( ) ) ; } else if ( getTrueValue ( ) === controller . $viewValue ) { // otherwise if it's been deselected, delete the view value controller . $setViewValue ( undefined ) ; } switchChange ( ) ; } } ) ; } else { // When the checkbox switch is clicked, set its value into the ngModel element . on ( 'switchChange.bootstrapSwitch' , function ( e ) { // $setViewValue --> $viewValue --> $parsers --> $modelValue controller . $setViewValue ( e . target . checked ) ; switchChange ( ) ; } ) ; } }


Input: / * localize natives [CODESPLIT] function ( msg ) { if ( typeof scope . console === 'object' && scope . console !== null && typeof scope . console . warn === 'function' ) { warn = function ( msg ) { scope . console . warn ( msg ) ; } ; warn ( msg ) ; } }


Input:
/ * localize natives [CODESPLIT] function ( o ) { var r , e ; if ( typeof o !== 'object' || o === null ) { r = default_options ; } else { r = { expires : default_options . expires , path : default_options . path , domain : default_options . domain , secure : default_options . secure } ; /*
                     * I've been very finicky about the name and format of the expiration option over time,
                     * so I'm accounting for older styles to maintain backwards compatibility. Preferably it
                     * will be called "expires" and will be an instance of Date
                     */ if ( typeof o . expires === 'object' && o . expires instanceof Date ) { r . expires = o . expires ; } else if ( typeof o . expires_at === 'object' && o . expires_at instanceof Date ) { r . expires = o . expires_at ; warn ( 'Cookie option "expires_at" has been deprecated. Rename to "expires". Support for "expires_at" will be removed in a version to come.' ) ; } else if ( typeof o . expiresAt === 'object' && o . expiresAt instanceof Date ) { r . expires = o . expiresAt ; warn ( 'Cookie option "expiresAt" has been deprecated. Rename to "expires". Support for "expiresAt" will be removed in a version to come.' ) ; } else if ( typeof o . hoursToLive === 'number' && o . hoursToLive !== 0 ) { e = new Date ( ) ; e . setTime ( e . getTime ( ) + ( o . hoursToLive * 60 * 60 * 1000 ) ) ; r . expires = e ; warn ( 'Cookie option "hoursToLive" has been deprecated. Rename to "expires" and prodvide a Date instance (see documentation). Support for "hoursToLive" will be removed in a version to come.' ) ; } if ( typeof o . path === 'string' && o . path !== '' ) { r . path = o . path ; } if ( typeof o . domain === 'string' && o . domain !== '' ) { r . domain = o . domain ; } if ( o . secure === true ) { r . secure = o . secure ; } } return r ; }


Input: / * localize natives [CODESPLIT] function ( o ) { o = resolveOptions ( o ) ; return ( [ ( typeof o . expires === 'object' && o . expires instanceof Date ? '; expires=' + o . expires . toGMTString ( ) : '' ) , ( '; path=' + o . path ) , ( typeof o . domain === 'string' ? '; domain=' + o . domain : '' ) , ( o . secure === true ? '; secure' : '' ) ] . join ( '' ) ) ; }


Input: get - get one several or all cookies [CODESPLIT] function ( n ) { var r , i , c = parseCookies ( ) ; if ( typeof n === 'string' ) { r = ( c [ n ] !== undef ) ? c [ n ] : null ; } else if ( typeof n === 'object' && n !== null ) { r = { } ; for ( i in n ) { if ( Object . prototype . hasOwnProperty . call ( n , i ) ) { if ( c [ n [ i ] ] !== undef ) { r [ n [ i ] ] = c [ n [ i ] ] ; } else { r [ n [ i ] ] = null ; } } } } else { r = c ; } return r ; }


Input: filter - get array of cookies whose names match the provided RegExp [CODESPLIT] function ( p ) { var n , r = { } , c = parseCookies ( ) ; if ( typeof p === 'string' ) { p = new RegExp ( p ) ; } for ( n in c ) { if ( Object . prototype . hasOwnProperty . call ( c , n ) && n . match ( p ) ) { r [ n ] = c [ n ] ; } } return r ; }


Input: set - set or delete a cookie with desired options [CODESPLIT] function ( n , v , o ) { if ( typeof o !== 'object' || o === null ) { o = { } ; } if ( v === undef || v === null ) { v = '' ; o . expires = new Date ( ) ; o . expires . setFullYear ( 1978 ) ; } else { /* Logic borrowed from http://jquery.com/ dataAttr method and reversed */ v = ( v === true ) ? 'true' : ( v === false ) ? 'false' : ! isNaN ( v ) ? String ( v ) : v ; if ( typeof v !== 'string' ) { if ( typeof JSON === 'object' && JSON !== null && typeof JSON . stringify === 'function' ) { v = JSON . stringify ( v ) ; } else { throw new Error ( 'cookies.set() could not be serialize the value' ) ; } } } document . cookie = n + '=' + encodeURIComponent ( v ) + cookieOptions ( o ) ; }


Input: del - delete a cookie ( domain and path options must match those with which the cookie was set ; this is really an alias for set () with parameters simplified for this use ) [CODESPLIT] function ( n , o ) { var d = { } , i ; if ( typeof o !== 'object' || o === null ) { o = { } ; } if ( typeof n === 'boolean' && n === true ) { d = this . get ( ) ; } else if ( typeof n === 'string' ) { d [ n ] = true ; } for ( i in d ) { if ( Object . prototype . hasOwnProperty . call ( d , i ) && typeof i === 'string' && i !== '' ) { this . set ( i , null , o ) ; } } }


Input: test - test whether the browser is accepting cookies [CODESPLIT] function ( ) { var r = false , n = 'test_cookies_jaaulde_js' , v = 'data' ; this . set ( n , v ) ; if ( this . get ( n ) === v ) { this . del ( n ) ; r = true ; } return r ; }


Input: Shared functions Allow an error message to retain its color when split across multiple lines . [CODESPLIT] function formatMessage ( str ) { return String ( str ) . split ( '\n' ) . map ( function ( s ) { return s . magenta ; } ) . join ( '\n' ) ; }


Input: ////////// Apply earlier zoom [CODESPLIT] function applyZoom ( options , chart ) { if ( angular . isObject ( options . state ) && angular . isObject ( options . state ) && angular . isArray ( options . state . range ) ) { chart . zoom ( options . state . range ) ; } else { chart . unzoom ( ) ; } }


Input: Create nested options objects . [CODESPLIT] function createZoomRangePath ( options ) { if ( ! angular . isObject ( options . state ) ) { options . state = { } ; } if ( ! angular . isObject ( options . state . range ) ) { options . state . range = [ ] ; } }


Input: Setup zoom event listeners which update the state [CODESPLIT] function synchronizeZoom ( options , configuration , watcher ) { if ( angular . isObject ( options . chart ) && angular . isObject ( options . chart . zoom ) && options . chart . zoom . enabled === true ) { // setup onzoomend listener configuration . zoom . onzoomend = function ( domain ) { // update state AngularChartWatcher . updateState ( watcher , function ( ) { createZoomRangePath ( options ) ; options . state . range = domain ; } ) ; // call user defined callback if ( angular . isFunction ( options . chart . zoom . onzoomend ) ) { AngularChartWatcher . applyFunction ( watcher , function ( ) { options . chart . zoom . onzoomend ( domain ) ; } ) ; } } ; } if ( angular . isObject ( options . chart ) && angular . isObject ( options . chart . subchart ) && options . chart . subchart . show === true ) { // setup onbrush listener configuration . subchart . onbrush = function ( domain ) { // update state AngularChartWatcher . updateState ( watcher , function ( ) { createZoomRangePath ( options ) ; options . state . range = domain ; } ) ; // call user defined callback if ( angular . isFunction ( options . chart . subchart . onbrush ) ) { AngularChartWatcher . applyFunction ( watcher , function ( ) { options . chart . subchart . onbrush ( domain ) ; } ) ; } } ; } }


Input: Add passed selection to the chart . [CODESPLIT] function addSelections ( chart , selections ) { service . disableSelectionListener = true ; selections . forEach ( function ( selection ) { chart . select ( [ selection . id ] , [ selection . index ] ) ; } ) ; service . disableSelectionListener = false ; }


Input: Remove passed selections from the chart . function removeSelections ( chart selections ) { disableSelectionListener = true ; selections . forEach ( function ( selection ) { chart . unselect ( [ selection . id ] [ selection . index ] ) ; } ) ; disableSelectionListener = false ; } Remove all selections present in the chart . [CODESPLIT] function removeAllSelections ( chart ) { service . disableSelectionListener = true ; chart . unselect ( ) ; service . disableSelectionListener = false ; }


Input: Apply earlier selections . [CODESPLIT] function applySelection ( options , chart ) { if ( angular . isObject ( options . state ) && angular . isArray ( options . state . selected ) ) { // TODO: get new selections // TODO: get removed selections // var chartSelections = chart.selected(); //    // addedSelections //    var addedSelections = newSelections.filter(function (elm) { //      var isNew = true; //      oldSelections.forEach(function (old) { //        if (old.id === elm.id && old.index === elm.index) { //          isNew = false; //          return isNew; //        } //      }); //      return isNew; //    }); // //    // removedSelections //    var removedSelections = oldSelections.filter(function (elm) { //      var isOld = true; //      newSelections.forEach(function (old) { //        if (old.id === elm.id && old.index === elm.index) { //          isOld = false; //          return isOld; //        } //      }); //      return isOld; //    }); // alternative: deselect all and select again //removeAllSelections(chart); addSelections ( chart , options . state . selected ) ; } else { removeAllSelections ( chart ) ; } }


Input: Create nested options object . [CODESPLIT] function createSelectionsPath ( options ) { if ( ! angular . isObject ( options . state ) ) { options . state = { } ; } if ( ! angular . isArray ( options . state . selected ) ) { options . state . selected = [ ] ; } }


Input: Listen to chart events to save selections into to state object . [CODESPLIT] function synchronizeSelection ( options , configuration , watcher ) { if ( angular . isObject ( options . chart ) && angular . isObject ( options . chart . data ) && angular . isObject ( options . chart . data . selection ) && options . chart . data . selection . enabled === true ) { // add onselected listener configuration . data . onselected = function ( data , element ) { // check if listener is disabled currently if ( service . disableSelectionListener ) { return ; } // update state AngularChartWatcher . updateState ( watcher , function ( ) { createSelectionsPath ( options ) ; options . state . selected . push ( data ) ; } ) ; // call user defined callback if ( angular . isFunction ( options . chart . data . onselected ) ) { AngularChartWatcher . applyFunction ( watcher , function ( ) { options . chart . data . onselected ( data , element ) ; } ) ; } } ; // add onunselection listener configuration . data . onunselected = function ( data , element ) { // check if listener is disabled currently if ( service . disableSelectionListener ) { return ; } // update state AngularChartWatcher . updateState ( watcher , function ( ) { createSelectionsPath ( options ) ; options . state . selected = options . state . selected . filter ( function ( selected ) { return selected . id !== data . id || selected . index !== data . index ; } ) ; } ) ; // call user defined callback if ( angular . isFunction ( options . chart . data . onunselected ) ) { AngularChartWatcher . applyFunction ( watcher , function ( ) { options . chart . data . onunselected ( data , element ) ; } ) ; } } ; } }


Input: ////////// [CODESPLIT] function init ( scope ) { var watcher = { scope : scope , dimensionsCallback : null , dimensionsTypeCallback : null , chartCallback : null , stateCallback : null , dataCallback : null , dataSmallWatcher : null , dataBigWatcher : null , disableStateWatcher : false } ; setupDimensionsWatcher ( watcher ) ; setupDimensionsTypeWatcher ( watcher ) ; setupChartWatcher ( watcher ) ; setupStateWatcher ( watcher ) ; setupWatchLimitWatcher ( watcher ) ; setupDataWatcher ( watcher ) ; return watcher ; }


Input: // SETUP // [CODESPLIT] function setupDimensionsWatcher ( watcher ) { watcher . scope . $watch ( function ( ) { var check = watcher . scope . options && watcher . scope . options . dimensions ; // remove types from copy to check only other changes if ( angular . isObject ( check ) ) { check = angular . copy ( check ) ; angular . forEach ( check , function ( dimension ) { if ( dimension . type ) { delete dimension . type ; } } ) ; } return check ; } , function ( ) { if ( angular . isFunction ( watcher . dimensionsCallback ) ) { watcher . dimensionsCallback ( ) ; } } , true ) ; }


Input: start watcher changes in small datasets compares whole object [CODESPLIT] function setupDataSmallWatcher ( watcher ) { return watcher . scope . $watch ( 'options.data' , function ( ) { if ( angular . isFunction ( watcher . dataCallback ) ) { watcher . dataCallback ( ) ; } setupDataWatcher ( watcher ) ; } , true ) ; }


Input: start watcher changes in big datasets compares length of records [CODESPLIT] function setupDataBigWatcher ( watcher ) { return watcher . scope . $watch ( function ( ) { if ( watcher . scope . options . data && angular . isArray ( watcher . scope . options . data ) ) { return watcher . scope . options . data . length ; } else { return 0 ; } } , function ( ) { if ( angular . isFunction ( watcher . dataCallback ) ) { watcher . dataCallback ( ) ; } setupDataWatcher ( watcher ) ; } ) ; }


Input: // $apply // [CODESPLIT] function updateState ( watcher , func ) { watcher . disableStateWatcher = true ; watcher . scope . $apply ( func ) ; watcher . disableStateWatcher = false ; }


Input: ////////// [CODESPLIT] function convertData ( options , configuration ) { // TODO support different data formats if ( angular . isArray ( options . data ) ) { configuration . data . json = options . data ; } }


Input: Add unique identifier for each chart [CODESPLIT] function addIdentifier ( ) { $scope . dataAttributeChartID = 'chartid' + Math . floor ( Math . random ( ) * 1000000001 ) ; angular . element ( $element ) . attr ( 'id' , $scope . dataAttributeChartID ) ; configuration . bindto = '#' + $scope . dataAttributeChartID ; }


Input: Redux thunk action creator for performing asynchronous actions . [CODESPLIT] function loadEntity ( name , promise , options ) { if ( ! name || typeof name !== 'string' ) throw new Error ( 'Missing required entity name' ) ; if ( ! promise || ! promise . then ) throw new Error ( 'Missing required entity promise' ) ; try { ! ( 0 , _validateOptions . default ) ( options ) ; } catch ( error ) { throw error ; } var entityLifecycle = new _entityLifecycle . default ( name , options ) ; return function ( dispatch , getState ) { entityLifecycle . setDispatch ( dispatch ) ; entityLifecycle . setGetState ( getState ) ; entityLifecycle . onLoad ( ) ; return new Promise ( function ( resolve , reject ) { promise . then ( function ( data ) { resolve ( entityLifecycle . onSuccess ( data ) ) ; } ) . catch ( function ( error ) { reject ( entityLifecycle . onFailure ( error ) ) ; } ) ; } ) ; } ; }


Input: Generation a Redux action object [CODESPLIT] function generateAction ( action , keys , values ) { var generatedAction = Object . assign ( { } , action ) ; keys . forEach ( function ( arg , index ) { generatedAction [ keys [ index ] ] = values [ index ] ; } ) ; return generatedAction ; }


Input: Generate action creators based on input arguments . The first argument is always treated as the Redux action type ; all other passed arguments are treated as property on the action object itself . [CODESPLIT] function makeActionCreator ( type ) { for ( var _len = arguments . length , keys = new Array ( _len > 1 ? _len - 1 : 0 ) , _key = 1 ; _key < _len ; _key ++ ) { keys [ _key - 1 ] = arguments [ _key ] ; } if ( ! type ) throw new Error ( 'Type cannot be null/undefined' ) ; return function ( ) { for ( var _len2 = arguments . length , values = new Array ( _len2 ) , _key2 = 0 ; _key2 < _len2 ; _key2 ++ ) { values [ _key2 ] = arguments [ _key2 ] ; } return generateAction ( { type : type } , keys , values ) ; } ; }


Input: Identical to makeActionCreator () however this function expects the second argument to be the name of an entity . [CODESPLIT] function makeEntityActionCreator ( type , entity ) { for ( var _len3 = arguments . length , keys = new Array ( _len3 > 2 ? _len3 - 2 : 0 ) , _key3 = 2 ; _key3 < _len3 ; _key3 ++ ) { keys [ _key3 - 2 ] = arguments [ _key3 ] ; } if ( ! type ) throw new Error ( 'Type cannot be null/undefined' ) ; if ( ! entity ) throw new Error ( 'Entity cannot be null/undefined' ) ; return function ( ) { for ( var _len4 = arguments . length , values = new Array ( _len4 ) , _key4 = 0 ; _key4 < _len4 ; _key4 ++ ) { values [ _key4 ] = arguments [ _key4 ] ; } return generateAction ( { type : type , entity : entity } , keys , values ) ; } ; }


Input: Generate a random number in a given range and round to a given value [CODESPLIT] function _getRandomDelayBetween ( min , max , roundTo ) { return Number ( Math . random ( ) * ( max - min ) + min ) . toFixed ( roundTo ) ; }


Input: Log Redux actions [CODESPLIT] function _logDetails ( action ) { if ( action ) { console . log ( ` ${ chalk . white . bgRed ( '  Prev State:' ) } ${ __toString ( state ) } ` ) ; console . log ( ` ${ chalk . white . bgBlue ( '      Action:' ) } ${ __toString ( action ) } ` ) ; } else { console . log ( ` ${ chalk . white . bgGreen ( '  Next State:' ) } ${ __toString ( state ) } ` ) ; console . log ( '\n' ) ; } }


Input: to create a push parser pass in a callback function and omit the context parameter to create a pull parser pass in null for the callback function and initially provide an empty object as the context [CODESPLIT] function jgeParse ( s , callback , context ) { if ( context && context . newState ) { if ( ! context . keepToken ) context . token = '' ; context . state = context . newState ; } else { context = { } ; reset ( context ) ; } var c ; for ( var i = context . position ; i < s . length ; i ++ ) { c = s . charAt ( i ) ; if ( ( c . charCodeAt ( 0 ) < 32 ) && ( context . validControlChars . indexOf ( c ) < 0 ) ) { context . newState = context . state = sError ; } if ( context . state != sContent ) { if ( context . validControlChars . indexOf ( c ) >= 0 ) { //other unicode spaces are not treated as whitespace c = ' ' ; } } context . bIndex = - 1 ; for ( var b = 0 ; b < context . boundary . length ; b ++ ) { if ( s . substr ( i , context . boundary [ b ] . length ) == context . boundary [ b ] ) { context . bIndex = b ; if ( context . boundary [ context . bIndex ] . length > 1 ) { i = i + context . boundary [ context . bIndex ] . length - 1 ; } break ; } } if ( context . bIndex >= 0 ) { if ( ( context . state != sValue ) && ( context . state != sComment ) ) { // && (context.state != sContent) context . token = context . token . trim ( ) ; } context . keepToken = false ; if ( ( ( context . state & 1 ) == 1 ) && ( ( context . token . trim ( ) !== '' ) || context . state == sValue ) ) { // TODO test element names for validity (using regex?) if ( context . state != sCData ) { context . token = context . token . replaceAll ( '&' , '&' ) ; context . token = context . token . replaceAll ( '"' , '"' ) ; context . token = context . token . replaceAll ( ''' , "'" ) ; context . token = context . token . replaceAll ( '>' , '>' ) ; context . token = context . token . replaceAll ( '<' , '<' ) ; if ( context . token . indexOf ( '&#' ) >= 0 ) { context . token = context . token . replace ( / &(?:#([0-9]+)|#x([0-9a-fA-F]+)); / g , function ( match , group1 , group2 ) { var e ; if ( group2 ) { e = String . fromCharCode ( parseInt ( group2 , 16 ) ) ; if ( ( e . charCodeAt ( 0 ) < 32 ) && ( context . validControlChars . indexOf ( e ) < 0 ) ) { context . newState = context . state = sError ; } return e ; } else { e = String . fromCharCode ( group1 ) ; if ( ( e . charCodeAt ( 0 ) < 32 ) && ( context . validControlChars . indexOf ( e ) < 0 ) ) { context . newState = context . state = sError ; } return e ; } } ) ; } } if ( context . state == sElement ) context . depth ++ ; else if ( context . state == sEndElement ) { context . depth -- ; if ( context . depth < 0 ) { context . newState = context . state = sError ; } } if ( context . state == sError ) { context . error = true ; } if ( callback ) { callback ( context . state , context . token ) ; } if ( context . state == sError ) { context . boundary = [ ] ; } } if ( context . state == sInitial ) { if ( context . boundary [ context . bIndex ] == '<?' ) { context . newState = sDeclaration ; context . boundary = [ '?>' ] ; } else { context . newState = sElement ; context . boundary = [ '>' , ' ' , '/' , '!--' , '?' , '!DOCTYPE' , '![CDATA[' ] ; context . boundary = context . boundary . concat ( context . validControlChars ) ; } } else if ( context . state == sDeclaration ) { context . newState = sPreElement ; context . boundary = [ '<' ] ; if ( context . token . indexOf ( '1.1' ) > 0 ) { context . validControlChars . push ( '\u2028' , '\u0085' , '\u0015' ) ; } } else if ( context . state == sPreElement ) { context . newState = sElement ; context . boundary = [ '>' , ' ' , '/' , '!--' , '?' , '!DOCTYPE' , '![CDATA[' ] ; context . boundary = context . boundary . concat ( context . validControlChars ) ; } else if ( context . state == sElement ) { context . lastElement = context . token ; if ( c == '>' ) { context . newState = sContent ; context . boundary = [ '<!DOCTYPE' , '<' ] ; } else if ( c == ' ' ) { context . newState = sAttribute ; context . boundary = [ '/' , '=' , '>' ] ; } else if ( c == '/' ) { context . newState = sEndElement ; context . boundary = [ '>' ] ; context . keepToken = true ; } else if ( c == '?' ) { context . newState = sProcessingInstruction ; context . boundary = [ '?>' ] ; } else if ( context . boundary [ context . bIndex ] == '!--' ) { context . newState = sComment ; context . boundary = [ '-->' ] ; } else if ( context . boundary [ context . bIndex ] == '![CDATA[' ) { context . newState = sCData ; context . boundary = [ ']]>' ] ; } else if ( context . boundary [ context . bIndex ] == '!DOCTYPE' ) { context . newState = sDocType ; context . boundary = [ '>' , '[' ] ; } } else if ( context . state == sAttribute ) { if ( c == '=' ) { context . newState = sAttrNML ; context . boundary = [ '\'' , '"' ] ; } else if ( c == '>' ) { context . newState = sContent ; context . boundary = [ '<!DOCTYPE' , '<' ] ; } else if ( c == '/' ) { context . newState = sEndElement ; context . keepToken = true ; context . state = sAttributeSpacer ; // to stop dummy attributes being emitted to pullparser context . token = context . lastElement ; } } else if ( context . state == sAttrNML ) { context . newState = sValue ; context . boundary = [ c ] ; } else if ( context . state == sValue ) { context . newState = sAttribute ; context . boundary = [ '=' , '/' , '>' ] ; } else if ( context . state == sEndElement ) { if ( context . depth !== 0 ) context . newState = sContent ; context . boundary = [ '<' ] ; // don't allow DOCTYPE's after the first sEndElement } else if ( context . state == sContent ) { if ( context . boundary [ context . bIndex ] == '<!DOCTYPE' ) { context . newState = sDocType ; context . boundary = [ '>' , '[' ] ; } else { context . newState = sElement ; context . boundary = [ '>' , ' ' , '/' , '!--' , '?' , '![CDATA[' ] ; context . boundary = context . boundary . concat ( context . validControlChars ) ; } } else if ( context . state == sComment ) { context . newState = sContent ; context . boundary = [ '<!DOCTYPE' , '<' ] ; } else if ( context . state == sProcessingInstruction ) { context . newState = sContent ; context . boundary = [ '<!DOCTYPE' , '<' ] ; } else if ( context . state == sCData ) { context . newState = sContent ; context . boundary = [ '<!DOCTYPE' , '<' ] ; } else if ( context . state == sDocType ) { if ( context . boundary [ context . bIndex ] == '[' ) { context . newState = sDTD ; context . boundary = [ ']>' ] ; } else { context . newState = sPreElement ; context . boundary = [ '<' ] ; } } else if ( context . state == sDTD ) { context . newState = sPreElement ; context . boundary = [ '<' ] ; } if ( ! callback ) { if ( ( ( context . state & 1 ) == 1 ) && ( ( context . token . trim ( ) !== '' ) || context . state == sValue ) ) { context . position = i + 1 ; return context ; } } context . state = context . newState ; if ( ! context . keepToken ) context . token = '' ; } else { context . token += c ; } } if ( ( context . state == sEndElement ) && ( context . depth === 0 ) && ( context . token . trim ( ) === '' ) ) { context . wellFormed = true ; } if ( ( ! context . wellFormed ) && ( ! context . error ) ) { if ( callback ) { // generate a final error, only for pushparsers though callback ( sError , context . token ) ; } } context . state = sEndDocument ; if ( callback ) { callback ( context . state , context . token ) ; return context . wellFormed ; } else { return context ; } }


Input: JSON Pointer specification : http : // tools . ietf . org / html / rfc6901 [CODESPLIT] function jptr ( obj , prop , newValue ) { //property not found if ( typeof obj === 'undefined' ) return false ; if ( ( ! prop ) || ( prop == '#' ) ) return obj ; if ( prop . startsWith ( '#' ) ) prop = prop . slice ( 1 ) ; if ( prop . startsWith ( '/' ) ) prop = prop . slice ( 1 ) ; var props = prop . split ( '/' ) ; var current = props [ 0 ] ; current = current . replaceAll ( '~1' , '/' ) ; current = current . replaceAll ( '~0' , '~' ) ; var index = - 1 ; if ( ( props . length > 1 ) && ( Array . isArray ( obj [ current ] ) ) ) { var next = props [ 1 ] ; var value = parseInt ( next , 10 ) ; if ( next == '-' ) { index = obj [ current ] . length ; } else { if ( ! isNaN ( value ) ) index = value ; } if ( index >= 0 ) { props . splice ( 1 , 1 ) ; prop = props . join ( '/' ) ; } } //property split found; recursive call if ( props . length > 1 ) { var pos = prop . indexOf ( '/' ) ; //get object at property (before split), pass on remainder if ( index >= 0 ) { return jptr ( obj [ current ] [ index ] , prop . substr ( pos + 1 ) , newValue ) ; //was props } else { return jptr ( obj [ current ] , prop . substr ( pos + 1 ) , newValue ) ; } } //no split; get property[index] or property var source = obj ; if ( current ) source = obj [ current ] ; if ( index >= 0 ) { if ( index >= source . length ) { if ( typeof newValue != 'undefined' ) { source . push ( newValue ) ; return newValue ; } else { return null ; } } else { if ( typeof newValue != 'undefined' ) { source [ index ] = newValue ; } return source [ index ] ; } } else { if ( typeof newValue != 'undefined' ) { obj [ prop ] = newValue ; source = obj [ prop ] ; } return source ; } }


Input: simple object accessor using dotted notation and [] for array indices [CODESPLIT] function fetchFromObject ( obj , prop , newValue ) { //property not found if ( typeof obj === 'undefined' ) return false ; if ( ! prop ) { if ( typeof newValue != 'undefined' ) { obj = newValue ; } return obj ; } var props = prop . split ( '.' ) ; var arr = props [ 0 ] . split ( / [\[\]]+ / ) ; var index = - 1 ; if ( arr . length > 1 ) { index = parseInt ( arr [ 1 ] , 10 ) ; } //property split found; recursive call if ( props . length > 1 ) { var pos = prop . indexOf ( '.' ) ; //get object at property (before split), pass on remainder if ( index >= 0 ) { return fetchFromObject ( obj [ arr [ 0 ] ] [ index ] , prop . substr ( pos + 1 ) , newValue ) ; //was props } else { return fetchFromObject ( obj [ arr [ 0 ] ] , prop . substr ( pos + 1 ) , newValue ) ; } } //no split; get property[index] or property var source = obj ; if ( arr [ 0 ] ) source = obj [ prop ] ; if ( index >= 0 ) { if ( typeof newValue != 'undefined' ) source [ index ] = newValue ; return source [ index ] ; } else { if ( typeof newValue != 'undefined' ) obj [ prop ] = newValue ; return obj [ prop ] ; } }


Input: TODO convert this to an options object [CODESPLIT] function ( obj , attrPrefix , standalone , indent , indentStr , fragment ) { var attributePrefix = ( attrPrefix ? attrPrefix : '@' ) ; if ( fragment ) { xmlWrite . startFragment ( indent , indentStr ) ; } else { xmlWrite . startDocument ( 'UTF-8' , standalone , indent , indentStr ) ; } traverse ( obj , '' , attributePrefix ) ; return xmlWrite . endDocument ( ) ; }


Input: _removeSubscribers remove the subscribers to one channel and return the number of subscribers that have been unsubscribed . [CODESPLIT] function _removeSubscribers ( aSubscribers , oSubscriber ) { let nUnsubscribed = 0 ; if ( ! isTypeOf ( aSubscribers , sNotDefined ) ) { let nIndex = aSubscribers . length - 1 ; for ( ; nIndex >= 0 ; nIndex -- ) { if ( aSubscribers [ nIndex ] . subscriber === oSubscriber ) { nUnsubscribed ++ ; aSubscribers . splice ( nIndex , 1 ) ; } } } return nUnsubscribed ; }


Input: Loops per all the events to remove subscribers . [CODESPLIT] function _removeSubscribersPerEvent ( oEventsCallbacks , sChannelId , oSubscriber ) { let nUnsubscribed = 0 ; iterateObject ( oEventsCallbacks , function ( oItem , sEvent ) { const aEventsParts = sEvent . split ( ':' ) ; let sChannel = sChannelId ; let sEventType = sEvent ; if ( aEventsParts [ 0 ] === 'global' ) { sChannel = aEventsParts [ 0 ] ; sEventType = aEventsParts [ 1 ] ; } nUnsubscribed += _removeSubscribers ( oChannels [ sChannel ] [ sEventType ] , oSubscriber ) ; } ) ; return nUnsubscribed ; }


Input: _addSubscribers add all the events of one channel from the subscriber [CODESPLIT] function _addSubscribers ( oEventsCallbacks , sChannelId , oSubscriber ) { iterateObject ( oEventsCallbacks , function ( oItem , sEvent ) { subscribeTo ( sChannelId , sEvent , oItem , oSubscriber ) ; } ) ; }


Input: _getChannelEvents return the events array in channel . [CODESPLIT] function _getChannelEvents ( sChannelId , sEvent ) { if ( oChannels [ sChannelId ] === und ) { oChannels [ sChannelId ] = { } ; } if ( oChannels [ sChannelId ] [ sEvent ] === und ) { oChannels [ sChannelId ] [ sEvent ] = [ ] ; } return oChannels [ sChannelId ] [ sEvent ] ; }


Input: subscribersByEvent return all the subscribers of the event in the channel . [CODESPLIT] function subscribersByEvent ( oChannel , sEventName ) { let aSubscribers = [ ] ; if ( ! isTypeOf ( oChannel , sNotDefined ) ) { iterateObject ( oChannel , function ( oItem , sKey ) { if ( sKey === sEventName ) { aSubscribers = oItem ; } } ) ; } return aSubscribers ; }


Input: Method to add a single callback in one channel an in one event . [CODESPLIT] function subscribeTo ( sChannelId , sEventType , fpHandler , oSubscriber ) { const aChannelEvents = _getChannelEvents ( sChannelId , sEventType ) ; aChannelEvents . push ( { subscriber : oSubscriber , handler : fpHandler } ) ; }


Input: Method to unsubscribe a subscriber from a channel and event type . It iterates in reverse order to avoid messing with array length when removing items . [CODESPLIT] function unsubscribeFrom ( sChannelId , sEventType , oSubscriber ) { const aChannelEvents = _getChannelEvents ( sChannelId , sEventType ) ; for ( let nEvent = aChannelEvents . length - 1 ; nEvent >= 0 ; nEvent -- ) { const oItem = aChannelEvents [ nEvent ] ; if ( oItem . subscriber === oSubscriber ) { aChannelEvents . splice ( nEvent , 1 ) ; } } }


Input: subscribe method gets the oEventsCallbacks object with all the handlers and add these handlers to the channel . [CODESPLIT] function subscribe ( oSubscriber ) { const oEventsCallbacks = oSubscriber . events ; if ( ! oSubscriber || oEventsCallbacks === und ) { return false ; } iterateObject ( oEventsCallbacks , function ( oItem , sChannelId ) { if ( oChannels [ sChannelId ] === und ) { oChannels [ sChannelId ] = { } ; } _addSubscribers ( oItem , sChannelId , oSubscriber ) ; } ) ; return true ; }


Input: unsubscribe gets the oEventsCallbacks methods and removes the handlers of the channel . [CODESPLIT] function unsubscribe ( oSubscriber ) { let nUnsubscribed = 0 ; const oEventsCallbacks = oSubscriber . events ; if ( ! oSubscriber || oEventsCallbacks === und ) { return false ; } iterateObject ( oEventsCallbacks , function ( oItem , sChannelId ) { if ( oChannels [ sChannelId ] === und ) { oChannels [ sChannelId ] = { } ; } nUnsubscribed = _removeSubscribersPerEvent ( oItem , sChannelId , oSubscriber ) ; } ) ; return nUnsubscribed > 0 ; }


Input: Method to execute handlers [CODESPLIT] function _executeHandler ( oHandlerObject , oData , sChannelId , sEvent ) { oHandlerObject . handler . call ( oHandlerObject . subscriber , oData ) ; if ( getDebug ( ) ) { const ErrorHandler = errorHandler ( ) ; ErrorHandler . log ( sChannelId , sEvent , oHandlerObject ) ; } }


Input: Publish the event in one channel . [CODESPLIT] function publish ( sChannelId , sEvent , oData ) { const aSubscribers = copyArray ( this . subscribers ( sChannelId , sEvent ) ) ; let oSubscriber ; const nLenSubscribers = aSubscribers . length ; if ( nLenSubscribers === 0 ) { return false ; } oData = preprocessorsPublishData ( oData ) ; while ( ! ! ( oSubscriber = aSubscribers . shift ( ) ) ) { _executeHandler ( oSubscriber , oData , sChannelId , sEvent ) ; } return true ; }


Input: Create or get a namespace by a namespace defined as string [CODESPLIT] function resolveNamespace ( sNamespace ) { var oObj = root , aElements = sNamespace . split ( '.' ) , sElement ; while ( ! ! ( sElement = aElements . shift ( ) ) ) { oObj = oObj [ sElement ] !== und ? oObj [ sElement ] : oObj [ sElement ] = { } ; } return oObj ; }


Input: Resolve dependency injection by default . [CODESPLIT] function getResolveDICallback ( oMapping ) { return function ( sDependency ) { var oPromise = getPromise ( ) ; if ( ! oMapping . __map__ [ sDependency ] ) { return false ; } oPromise . resolve ( oMapping . __map__ [ sDependency ] ) ; return oPromise ; } ; }


Input: Traverse all the mapping systems to get a match . [CODESPLIT] function getDependencyThroughAllMaps ( sDependency ) { var oMap , oDependency , nIndexOrder , nLenOrder , aOrderDependency = oMappingMaps . ___order___ ; createMapping ( oMappingMaps , '__' , root , function ( sDependency ) { var oDependency , oPromise = getPromise ( ) ; oDependency = resolveNamespace ( sDependency ) ; oPromise . resolve ( oDependency ) ; return oPromise ; } ) ; for ( nIndexOrder = 0 , nLenOrder = aOrderDependency . length ; nIndexOrder < nLenOrder ; nIndexOrder ++ ) { oMap = oMappingMaps [ aOrderDependency [ nIndexOrder ] ] ; oDependency = oMap . __resolveDI__ ( sDependency ) ; if ( oDependency ) { delete oMappingMaps [ '__' ] ; return oDependency ; } } delete oMappingMaps [ '__' ] ; return false ; }


Input: Returns the promise callback by type [CODESPLIT] function getPromiseCallbacks ( oContext , sType ) { return function ( ) { var aCompleted , nLenPromises , oDeferred , aPromises , nPromise , oPromise , aResults = [ ] ; oContext . bCompleted = true ; oContext . sType = sType ; oContext . oResult = arguments ; while ( oContext . aPending [ 0 ] ) { oContext . aPending . shift ( ) [ sType ] . apply ( oContext , arguments ) ; } oDeferred = oContext . oDeferred ; if ( oDeferred ) { aCompleted = [ ] ; aPromises = oDeferred . aPromises ; nLenPromises = aPromises . length ; aResults = [ ] ; for ( nPromise = 0 ; nPromise < nLenPromises ; nPromise ++ ) { oPromise = aPromises [ nPromise ] ; aCompleted . push ( Number ( oPromise . bCompleted ) ) ; aResults . push ( oPromise . oResult ) ; } if ( aCompleted . join ( '' ) . indexOf ( '0' ) === - 1 ) { oDeferred [ sType ] . apply ( oDeferred , aResults ) ; } } } ; }


Input: Adds new callbacks to execute when the promise has been completed [CODESPLIT] function ( fpSuccess , fpFailure ) { var oResult = this . oResult ; if ( this . bCompleted ) { if ( this . sType === 'resolve' ) { fpSuccess . apply ( fpSuccess , oResult ) ; } else { fpFailure . apply ( fpFailure , oResult ) ; } } else { this . aPending . push ( { resolve : fpSuccess , reject : fpFailure } ) ; } return this ; }


Input: Module to be stored adds two methods to start and extend modules . [CODESPLIT] function FakeModule ( sModuleId , fpCreator ) { if ( isTypeOf ( fpCreator , sNotDefined ) ) { throw new Error ( 'Something goes wrong!' ) ; } this . creator = fpCreator ; this . instances = { } ; this . sModuleId = sModuleId ; }


Input: Use jQuery detection [CODESPLIT] function isJqueryObject ( oObj ) { var isJquery = false , $ = getRoot ( ) . jQuery ; if ( $ ) { isJquery = isInstanceOf ( oObj , $ ) ; } return isJquery ; }


Input: Use Event detection and if it fails it degrades to use duck typing detection to test if the supplied object is an Event [CODESPLIT] function isEvent ( oObj ) { try { return isInstanceOf ( oObj , Event ) ; } catch ( erError ) { // Duck typing detection (If it sounds like a duck and it moves like a duck, it's a duck) if ( oObj . altKey !== und && ( oObj . srcElement || oObj . target ) ) { return true ; } } return false ; }


Input: Add common properties and methods to avoid repeating code in modules [CODESPLIT] function addPropertiesAndMethodsToModule ( sModuleId , aDependencies , fpCallback ) { var oPromise ; function success ( mapping ) { const oModules = getModules ( ) ; var oModule , fpInitProxy ; oModule = oModules [ sModuleId ] . creator . apply ( oModules [ sModuleId ] , [ ] . slice . call ( arguments , 1 ) ) ; oModule . __children__ = [ ] ; oModule . dependencies = aDependencies || [ ] . slice . call ( arguments , 1 ) ; oModule . resolvedDependencies = mapping ; oModule . __module_id__ = sModuleId ; fpInitProxy = oModule . init || nullFunc ; // Provide compatibility with old versions of Hydra.js oModule . __action__ = oModule . __sandbox__ = Bus ; oModule . events = oModule . events || { } ; oModule . init = function ( ) { var aArgs = copyArray ( arguments ) . concat ( getVars ( ) ) ; if ( oModule . __children__ . length === 0 ) { // Only subscribe last element of inheritance. Bus . subscribe ( oModule ) ; } return fpInitProxy . apply ( this , aArgs ) ; } ; oModule . handleAction = function ( oNotifier ) { var fpCallback = this . events [ oNotifier . type ] ; if ( isTypeOf ( fpCallback , sNotDefined ) ) { return ; } fpCallback . call ( this , oNotifier ) ; } ; // Provide compatibility with old Hydra versions which used to use "destroy" as onDestroy hook. oModule . onDestroy = oModule . onDestroy || oModule . destroy || function ( ) { } ; oModule . destroy = function ( ) { this . onDestroy ( ) ; Bus . unsubscribe ( oModule ) ; delete oModules [ sModuleId ] . instances [ oModule . __instance_id__ ] ; } ; fpCallback ( oModule ) ; } oPromise = resolveDependencies ( sModuleId , aDependencies ) ; oPromise . then ( function ( ) { success . apply ( success , arguments ) ; } ) ; }


Input: wrapMethod is a method to wrap the original method to avoid failing code . This will be only called if bDebug flag is set to false . [CODESPLIT] function wrapMethod ( oInstance , sName , sModuleId , fpMethod ) { oInstance [ sName ] = ( function ( sName , fpMethod ) { return function ( ) { var aArgs = copyArray ( arguments ) ; try { return fpMethod . apply ( this , aArgs ) ; } catch ( erError ) { const ErrorHandler = errorHandler ( ) ; ErrorHandler . error ( sModuleId , sName , erError ) ; return false ; } } ; } ( sName , fpMethod ) ) ; }


Input: register is the method that will add the new module to the oModules object . sModuleId will be the key where it will be stored . [CODESPLIT] function register ( sModuleId , aDependencies , fpCreator ) { const oModules = getModules ( ) ; if ( isFunction ( aDependencies ) ) { fpCreator = aDependencies ; aDependencies = [ '$$_bus' , '$$_module' , '$$_log' , 'gl_Hydra' ] ; } oModules [ sModuleId ] = new FakeModule ( sModuleId , fpCreator ) ; oModules [ sModuleId ] . dependencies = aDependencies ; return oModules [ sModuleId ] ; }


Input: Method to set an instance of a module [CODESPLIT] function setInstance ( sModuleId , sIdInstance , oInstance ) { const oModules = getModules ( ) ; var oModule = oModules [ sModuleId ] ; if ( ! oModule ) { fpThrowErrorModuleNotRegistered ( sModuleId , true ) ; } oModule . instances [ sIdInstance ] = oInstance ; return oModule ; }


Input: start more than one module at the same time . [CODESPLIT] function _multiModuleStart ( oInstance , aModulesIds , sIdInstance , oData , bSingle ) { var aInstancesIds , aData , aSingle , nIndex , nLenModules , sModuleId ; if ( isArray ( sIdInstance ) ) { aInstancesIds = copyArray ( sIdInstance ) ; } if ( isArray ( oData ) ) { aData = copyArray ( oData ) ; } if ( isArray ( bSingle ) ) { aSingle = copyArray ( bSingle ) ; } for ( nIndex = 0 , nLenModules = aModulesIds . length ; nIndex < nLenModules ; nIndex ++ ) { sModuleId = aModulesIds [ nIndex ] ; sIdInstance = aInstancesIds && aInstancesIds [ nIndex ] || generateUniqueKey ( ) ; oData = aData && aData [ nIndex ] || oData ; bSingle = aSingle && aSingle [ nIndex ] || bSingle ; startSingleModule ( oInstance , sModuleId , sIdInstance , oData , bSingle ) ; } }


Input: Method to modify the init method to use it for extend . [CODESPLIT] function beforeInit ( oInstance , oData , bSingle ) { iterateObject ( oModifyInit , function ( oMember ) { if ( oMember && isTypeOf ( oMember , sFunctionType ) ) { oMember ( oInstance , oData , bSingle ) ; } } ) ; }