Input:
Create default delimiters and tags [CODESPLIT] function ( ) { if ( this . isInitialized ) return ; this . isInitialized = true ; var lexer = this ; this . lineno = 1 ; this . column = 1 ; this . lexed = '' ; this . file = utils . normalize ( this . file ) ; this . file . orig = this . file . contents ; this . input = this . file . contents . toString ( ) ; this . file . ast = this . ast ; this . file . ast . variables = { } ; this . file . ast . blocks = { } ; this . input = this . input . split ( '{% body %}' ) . join ( '{% block "body" %}{% endblock %}' ) ; if ( this . file . extends ) { this . prependNode ( this . file , 'extends' ) ; } /**
     * Tags
     */ this . captureTag ( 'extends' ) ; this . captureTag ( 'layout' ) ; /**
     * Block tags
     */ this . captureBlock ( 'block' ) ; /**
     * Captures
     */ this . capture ( 'text' , utils . negateDelims ( this . delimiters ) ) ; this . capture ( 'newline' , / ^\n+ / ) ; this . capture ( 'es6' , / ^\$\{([^\\}]*(?:\\.[^\\}]*)*)\} / ) ; this . capture ( 'variable' , / ^\{{2,}([^\\}]*(?:\\.[^\\}]*)*)\}{2,} / ) ; this . capture ( 'escape' , / ^\\(.) / ) ; this . capture ( 'space' , / ^[ \t]+ / ) ; /**
     * Custom helpers
     */ var helpers = this . options . helpers || { } ; if ( utils . isObject ( helpers ) ) { helpers = Object . keys ( helpers ) ; } helpers . forEach ( function ( key ) { lexer . known . blocks . push ( key ) ; lexer . captureBlock ( key ) ; } ) ; /**
     * Add other names to return un-rendered
     */ var matches = this . input . match ( / \{%\s*([^%}]+) / g ) ; var names = utils . getNames ( matches ) ; names . tags . forEach ( function ( key ) { if ( ! utils . isRegistered ( lexer , key ) ) { lexer . unknown . tags . push ( key ) ; lexer . captureTag ( key ) ; } } ) ; names . blocks . forEach ( function ( key ) { if ( ! utils . isRegistered ( lexer , key ) ) { lexer . unknown . blocks . push ( key ) ; lexer . captureBlock ( key ) ; } } ) ; }


Input: Set an error message with the current line number and column . [CODESPLIT] function ( msg ) { var message = this . file . relative + ' line:' + this . lineno + ' column:' + this . column + ': ' + msg ; var err = new Error ( message ) ; err . reason = msg ; err . line = this . lineno ; err . column = this . column ; err . source = this . input ; err . path = this . file . path ; if ( this . options . silent ) { this . errors . push ( err ) ; } else { throw err ; } }


Input: Mark position and patch node . position . [CODESPLIT] function ( ) { var start = { line : this . lineno , column : this . column } ; var self = this ; return function ( node ) { utils . define ( node , 'position' , new Position ( start , self ) ) ; return node ; } ; }


Input: Capture type with the given regex . [CODESPLIT] function ( type , regex ) { var cached = this . regex . create ( type , regex ) ; var lexer = this ; var fn = this . lexers [ type ] = function ( ) { var pos = lexer . position ( ) ; var m = lexer . match ( cached . val ) ; if ( ! m || ! m [ 0 ] ) return ; var parent = lexer . prev ( ) ; var node = pos ( { type : type , val : m [ 0 ] } ) ; utils . define ( node , 'parent' , parent ) ; utils . define ( node , 'rawArgs' , m [ 1 ] ) ; utils . define ( node , 'args' , function ( ) { return utils . parseArgs ( m [ 1 ] ) ; } ) ; parent . nodes . push ( node ) ; } ; this . addLexer ( fn ) ; return this ; }


Input: Create a lexer for the given variable type . [CODESPLIT] function ( type ) { var cached = this . regex . createVariable ( type ) ; var file = this . file ; var lexer = this ; var fn = this . lexers [ type ] = function ( ) { var pos = lexer . position ( ) ; var m = lexer . match ( cached . strict ) ; if ( ! m ) return ; var parent = this . prev ( ) ; var node = pos ( { type : type , known : utils . has ( lexer . known . tags , type ) , val : m [ 0 ] . trim ( ) } ) ; parent . known = node . known ; var nodes = parent . nodes ; Object . defineProperty ( file . ast . variables , type , { configurable : true , set : function ( val ) { nodes = val ; } , get : function ( ) { return nodes ; } } ) ; Object . defineProperty ( parent , 'nodes' , { configurable : true , set : function ( val ) { nodes = val ; } , get : function ( ) { return nodes ; } } ) ; utils . define ( node , 'parent' , parent ) ; parent . nodes . push ( node ) ; } ; this . addLexer ( fn ) ; return this ; }


Input: Create a tag lexer for the given type . [CODESPLIT] function ( type ) { this . ast . tags [ type ] = null ; this . names . push ( type ) ; var cached = this . regex . createTag ( type ) ; var file = this . file ; var lexer = this ; var fn = this . lexers [ type ] = function ( ) { var pos = lexer . position ( ) ; var m = lexer . match ( cached . strict ) ; if ( ! m ) return ; var name = utils . getName ( m [ 1 ] ) ; if ( this . options . strict ) { var isKnown = utils . has ( lexer . known . tags , type ) ; if ( isKnown && file . hasOwnProperty ( type ) && ! file . hasOwnProperty ( 'isParsed' ) ) { throw new Error ( ` ${ type } ` ) ; } } file [ type ] = name ; lexer . ast . tags [ type ] = name ; lexer . createNode ( type , name , m , pos ) ; } ; this . addLexer ( fn ) ; return this ; }


Input: Push AST node type onto parent . nodes [CODESPLIT] function ( type , name , m , pos ) { var parent = this . prev ( ) ; var val = m [ 1 ] ; var tok = { type : 'args' , val : val } ; var node = pos ( { type : type , name : name , known : utils . has ( this . known . tags , type ) , val : val . trim ( ) , nodes : [ tok ] } ) ; utils . define ( node , 'parent' , parent ) ; utils . define ( tok , 'parent' , node ) ; parent . nodes . push ( node ) ; }


Input: Create an opening tag lexer for block name . [CODESPLIT] function ( type ) { this . names . push ( type ) ; var cached = this . regex . createOpen ( type ) ; var file = this . file ; var lexer = this ; return function ( ) { var pos = lexer . position ( ) ; var m = lexer . match ( cached . strict ) ; if ( ! m ) return ; var name = utils . getName ( m [ 1 ] ) ; var action = utils . getAction ( m [ 1 ] ) ; var val = m [ 0 ] ; if ( ! name && lexer . options [ type ] && lexer . options [ type ] . args === 'required' ) { throw new Error ( ` ${ type } ${ m [ 0 ] } ` ) ; } if ( ! name ) name = 'unnamed' ; var node = pos ( { type : ` ${ type } ` , known : utils . has ( lexer . known . blocks , type ) , name : name , val : val . trim ( ) } ) ; var parent = lexer . prev ( ) ; if ( parent && parent . name && parent . name !== 'root' ) { name = parent . name + '.' + name ; } var block = { type : type , name : name , known : node . known , action : action , nodes : [ node ] } ; utils . define ( node , 'parent' , block ) ; utils . define ( block , 'parent' , parent ) ; block . rawArgs = m [ 1 ] ; block . args = utils . parseArgs ( m [ 1 ] ) ; Object . defineProperty ( file . ast . blocks [ type ] , name , { configurable : true , enumerable : true , set : function ( val ) { block = val ; } , get : function ( ) { return block ; } } ) ; parent . nodes . push ( block ) ; lexer . tokens . push ( block ) ; return block ; } ; }


Input: Create a closing tag lexer for block name . [CODESPLIT] function ( type ) { var cached = this . regex . createClose ( type ) ; var file = this . file ; var lexer = this ; return function ( ) { var pos = lexer . position ( ) ; var m = lexer . match ( cached . strict ) ; if ( ! m ) return ; var block = lexer . tokens . pop ( ) ; if ( typeof block === 'undefined' || block . type !== type ) { throw new Error ( ` ${ type } ` ) ; } if ( block . name === 'body' ) { lexer . ast . isLayout = true ; file . ast . isLayout = true ; } var nodes = block . nodes ; Object . defineProperty ( file . ast . blocks , block . name , { configurable : true , set : function ( val ) { nodes = val ; } , get : function ( ) { return nodes ; } } ) ; Object . defineProperty ( block , 'nodes' , { configurable : true , set : function ( val ) { nodes = val ; } , get : function ( ) { return nodes ; } } ) ; var tok = pos ( { known : block . known , type : ` ${ type } ` , val : m [ 0 ] . trim ( ) } ) ; utils . define ( block , 'position' , tok . position ) ; utils . define ( tok , 'parent' , block ) ; block . nodes . push ( tok ) ; return block ; } ; }


Input: Create a block lexer with opening and closing tags for the given name . [CODESPLIT] function ( type ) { this . file . ast . blocks [ type ] = this . file . ast . blocks [ type ] || { } ; this . addLexer ( this . captureOpen ( type ) ) ; this . addLexer ( this . captureClose ( type ) ) ; return this ; }


Input: Unshift node prop onto the AST [CODESPLIT] function ( file , prop ) { return this . createNode ( prop , file [ prop ] , ` ${ prop } ${ file [ prop ] } ` , this . position ( ) ) ; }


Input: Update lineno and column based on str . [CODESPLIT] function ( str , len ) { var lines = str . match ( / \n / g ) ; if ( lines ) this . lineno += lines . length ; var i = str . lastIndexOf ( '\n' ) ; this . column = ~ i ? len - i : this . column + len ; this . lexed += str ; this . consume ( str , len ) ; }


Input: Match regex return captures and update the cursor position by match [ 0 ] length . [CODESPLIT] function ( regex ) { var m = regex . exec ( this . input ) ; if ( m ) { this . updatePosition ( m [ 0 ] , m [ 0 ] . length ) ; return m ; } }


Input: Run lexers to advance the curson position [CODESPLIT] function ( ) { var len = this . fns . length ; var idx = - 1 ; while ( ++ idx < len ) { this . fns [ idx ] . call ( this ) ; if ( ! this . input ) { break ; } } }


Input: Get the next AST token [CODESPLIT] function ( ) { while ( this . input ) { var prev = this . input ; this . advance ( ) ; if ( this . input && prev === this . input ) { throw new Error ( ` ${ this . input . substr ( 0 , 10 ) } ` ) ; } } }


Input: Tokenize the given string . [CODESPLIT] function ( file ) { debug ( 'lexing <%s>' , this . file . path ) ; if ( file ) this . file = file ; this . init ( ) ; while ( this . input ) this . next ( ) ; return this . ast ; }


Input: Hook for showing the automatic message [CODESPLIT] function notifyHook ( e ) { message_count ++ ; var message ; if ( ! options . enabled ) { return ; } if ( ! e ) { return ; } if ( e && e . length === 1 ) { e = e [ 0 ] ; } if ( / Task .* failed\. / . test ( e . message ) ) { message = e . message ; } else if ( e . message && e . stack ) { message = exception ( e ) ; } else { message = e + '' ; } if ( message_count > 0 && message === 'Aborted due to warnings.' ) { // skip unhelpful message because there was probably another one that was more helpful return ; } // shorten message by removing full path // TODO - make a global replace message = message . replace ( cwd , '' ) . replace ( '\x07' , '' ) ; return notify ( { title : options . title + ( grunt . task . current . nameArgs ? ' ' + grunt . task . current . nameArgs : '' ) , message : message } ) ; }


Input: pauses the timer [CODESPLIT] function ( ) { if ( this . _initialized && this . _isPaused ) { return false ; } this . _isPaused = true ; raf . cancel ( this . _requestID ) ; this . _pauseTime = now ( ) ; this . _onPause ( ) ; return true ; }


Input: resumes the timer [CODESPLIT] function ( ) { if ( this . _initialized && ! this . _isPaused ) { return false ; } var pauseDuration ; this . _isPaused = false ; this . _prevTime = now ( ) ; pauseDuration = this . _prevTime - this . _pauseTime ; this . _onResume ( pauseDuration ) ; this . _requestID = raf . request ( this . _tick ) ; return true ; }


Input: Methods [CODESPLIT] function createServer ( options , callback ) { if ( options && options . cert && options . key ) { return https . createServer ( options , callback ) ; } return http . createServer ( callback || null ) ; }


Input: Methods [CODESPLIT] function createProxy ( api , obj , methods ) { return new Proxy ( obj , { get ( target , name ) { if ( methods . includes ( name ) ) { return ( params , callback ) => { const inject = Object . assign ( { chat_id : obj . id } , params ) ; return api . method ( name , inject , callback ) ; } ; } return target [ name ] ; } , set ( ) { return new Error ( 'Cannot change `chat` or `user`.' ) ; } , } ) ; }


Input: IS ARRAY - LIKE // FUNCTION : isArrayLike ( value ) Validates if a value is array - like . [CODESPLIT] function isArrayLike ( value ) { return ( value !== void 0 && value !== null && typeof value !== 'function' && isInteger ( value . length ) && value . length >= 0 && value . length <= MAX ) ; }


Input: Render loop [CODESPLIT] function render ( ) { shell . context . cache . clear ( ) ; shell . context . setViewport ( ) ; GLOW . defaultCamera . update ( ) shell . context . enableDepthTest ( true ) ; if ( params . cullCW ) { shell . context . enableCulling ( true , { frontFace : GL . CW , cullFace : GL . BACK } ) ; } else if ( params . cullCCW ) { shell . context . enableCulling ( true , { frontFace : GL . CCW , cullFace : GL . BACK } ) ; } else { shell . context . enableCulling ( false ) ; } shell . context . clear ( ) ; shell . events . emit ( "render" ) ; utils . nextFrame ( render ) ; }


Input:
/ * [CODESPLIT] function create ( opts , cb ) { // "use strict" ; var params = [ 'create' , '-f' ] ; /*
     immediately add some options to the create procedure
     done by adding argument -o option=value
     the opts.options parameter is an array of objects, or a single object

     opts.options = { property: String, value: String }

     OR:

     opts.options = [ { property: String, value: String }, { property: String, value: String } ]

     */ if ( opts . options ) { if ( opts . options . length ) { //opts.options is an array for ( var x = 0 ; x < opts . options . length ; x ++ ) { params . push ( '-o' , opts . options [ x ] . property + "=" + opts . options [ x ] . value ) ; } } else { //opts.options is a single object params . push ( '-o' , opts . options . property + "=" + opts . options . value ) ; } } if ( opts . mountpoint ) { params . push ( '-m' , opts . mountpoint ) ; } params . push ( opts . name ) ; if ( opts . devices . length ) { params = params . concat ( opts . devices ) ; } else { var devices = opts . devices . split ( / \s+ / ) ; params = params . concat ( devices ) ; } zpool ( params , cb ) ; }


Input: / * [CODESPLIT] function add ( opts , cb ) { "use strict" ; var params = [ 'add' , '-f' ] ; params . push ( opts . name ) ; //devices is an array or a string of devices if ( opts . devices . length ) { params = params . concat ( opts . devices ) ; } else { var devices = opts . devices . split ( / \s+ / ) ; params = params . concat ( devices ) ; } zpool ( params , cb ) ; }


Input: / * [CODESPLIT] function destroy ( opts , cb ) { "use strict" ; var params = [ 'destroy' , '-f' ] ; params . push ( opts . name ) ; zpool ( params , cb ) ; }


Input: / * [CODESPLIT] function list ( opts , cb ) { //list the statistics from a (specific) pool. -o option is NOT available "use strict" ; if ( typeof opts === 'function' ) { cb = opts ; opts = undefined ; } var params = [ 'list' , '-H' ] ; if ( opts && opts . name ) { params . push ( opts . name ) ; } zpool ( params , function ( err , stdout ) { if ( cb && typeof cb === 'function' ) { if ( err ) { cb ( err ) ; return ; } var lines = util . compact ( stdout . split ( '\n' ) ) ; var list = lines . map ( function ( x ) { return new ZPool ( x ) ; } ) ; cb ( err , list ) ; } } ) ; }


Input: Creates a temporary directory . [CODESPLIT] function mktmpdir ( prefixSuffix , tmpdir , callback , onend ) { if ( 'function' == typeof prefixSuffix ) { onend = tmpdir ; callback = prefixSuffix ; tmpdir = null ; prefixSuffix = null ; } else if ( 'function' == typeof tmpdir ) { onend = callback ; callback = tmpdir ; tmpdir = null ; } prefixSuffix = prefixSuffix || 'd' ; onend = onend || function ( ) { } ; tmpname . create ( prefixSuffix , tmpdir , function ( err , path , next ) { if ( err ) return callback ( err ) ; fs . mkdir ( path , 0700 , next ) ; } , function ( err , path ) { if ( err ) return callback ( err ) ; callback ( null , path , function ( err ) { if ( ! path ) return onend ( err ) ; rimraf ( path , function ( _err ) { onend ( err || _err , path ) ; } ) ; } ) ; } ) ; }


Input: / * [CODESPLIT] function list ( opts , cb ) { "use strict" ; if ( typeof opts === 'function' ) { cb = opts ; opts = undefined ; } var params = [ 'list' , '-H' ] ; if ( opts && opts . type ) { params . push ( '-t' ) ; params . push ( opts . type ) ; } if ( opts && opts . sort ) { params . push ( '-s' ) ; params . push ( opts . sort ) ; } if ( opts && opts . recursive ) { params . push ( '-r' ) ; } if ( opts && opts . name ) { params . push ( opts . name ) ; } zfs ( params , function ( err , stdout ) { if ( cb && typeof cb === 'function' ) { if ( err ) { cb ( err ) ; return ; } var lines = util . compact ( stdout . split ( '\n' ) ) ; var list = lines . map ( function ( x ) { return new ZFS ( x ) ; } ) ; cb ( err , list ) ; } } ) ; }


Input: / * [CODESPLIT] function get ( opts , cb ) { "use strict" ; var params = [ 'get' , '-pH' ] ; if ( opts . source ) { params . push ( '-s' , opts . source ) ; } params . push ( opts . property ) ; if ( opts . name ) { params . push ( opts . name ) ; } zfs ( params , function ( err , stdout ) { if ( cb && typeof cb === 'function' ) { if ( err ) return cb ( err ) ; var lines = util . compact ( stdout . split ( '\n' ) ) ; var list = lines . map ( function ( x ) { return new util . Property ( x ) ; } ) ; cb ( err , list ) ; } } ) ; }


Input: / * [CODESPLIT] function destroy ( opts , cb ) { "use strict" ; var params = [ 'destroy' ] ; if ( opts . recursive ) { params . push ( '-r' ) ; } params . push ( opts . name ) ; zfs ( params , cb ) ; }


Input: / * [CODESPLIT] function create ( opts , cb ) { "use strict" ; var params = [ 'create' ] ; if ( opts . options ) { if ( opts . options . length ) { //opts.options is an array for ( var x = 0 ; x < opts . options . length ; x ++ ) { params . push ( '-o' , opts . options [ x ] . property + "=" + opts . options [ x ] . value ) ; } } else { //opts.options is a single object params . push ( '-o' , opts . options . property + "=" + opts . options . value ) ; } } if ( opts . size ) { params . push ( '-V' , util . parseNumber ( opts . size ) ) ; } params . push ( opts . name ) ; zfs ( params , cb ) ; }


Input: / * Set a specific option for a given dataset [CODESPLIT] function set ( opts , cb ) { "use strict" ; var params = [ 'set' ] ; params . push ( opts . property + "=" + opts . value ) ; params . push ( opts . name ) ; zfs ( params , cb ) ; }


Input: / * [CODESPLIT] function snapshot ( opts , cb ) { "use strict" ; var params = [ 'snapshot' ] ; if ( opts . recursive ) { params . push ( '-r' ) ; } params . push ( opts . dataset + '@' + opts . name ) ; zfs ( params , cb ) ; }


Input: / * [CODESPLIT] function clone ( opts , cb ) { "use strict" ; var params = [ 'clone' ] ; params . push ( opts . snapshot , opts . dataset ) ; zfs ( params , cb ) ; }


Input: / * [CODESPLIT] function mount ( opts , cb ) { "use strict" ; var params = [ 'mount' ] ; if ( opts . overlay ) { params . push ( '-O' ) ; } if ( opts . options ) { if ( opts . options . length ) { //opts.options is an array for ( var x = 0 ; x < opts . options . length ; x ++ ) { params . push ( '-o' , opts . options [ x ] ) ; } } else { //opts.options is a single object, callback err and return cb ( { error : 'invalid argu: the options should be a string array' } ) ; return ; } } if ( opts . dataset ) { params . push ( opts . dataset ) ; } else { params . push ( '-a' ) ; } zfs ( params , cb ) ; }


Input: / * [CODESPLIT] function unmount ( opts , cb ) { "use strict" ; var params = [ 'unmount' ] ; if ( opts . force ) { params . push ( '-f' ) ; } if ( opts . name ) { params . push ( opts . name ) ; } else { params . push ( '-a' ) ; } zfs ( params , cb ) ; }


Input: / * [CODESPLIT] function send ( opts , cb ) { "use strict" ; var params = [ 'send' ] ; if ( opts . replication ) { params . push ( '-R' ) ; } if ( opts . deduplicate ) { params . push ( '-D' ) ; } if ( opts . properties ) { params . push ( '-p' ) ; } if ( opts . noop ) { params . push ( '-n' ) ; } if ( opts . parsable ) { params . push ( '-P' ) ; } if ( opts . verbose ) { params . push ( '-v' ) ; } if ( opts . incremental ) { if ( opts . intermediary ) { params . push ( '-I' ) ; } else { params . push ( '-i' ) ; } params . push ( opts . incremental ) ; } params . push ( opts . snapshot ) ; spawnzfs ( params , function ( err , child ) { if ( err ) { return cb ( err ) ; } var buffer = [ ] ; var sendStream = child . stdout ; child . stderr . on ( 'data' , function ( data ) { data = data . toString ( ) ; buffer . push ( data ) ; if ( opts . verbose ) { sendStream . emit ( 'verbose' , data ) ; } //only keep last 5 lines if ( buffer . length > 5 ) { buffer . shift ( ) ; } } ) ; child . once ( 'exit' , function ( code ) { if ( code !== 0 ) { var message = 'Send Error:' + util . compact ( buffer . join ( '\n' ) . split ( '\n' ) ) . join ( '; ' ) . trim ( ) ; var err = new Error ( message ) ; err . code = code ; sendStream . emit ( 'error' , err ) ; } } ) ; return cb ( null , sendStream ) ; } ) ; }


Input: / * [CODESPLIT] function receive ( opts , cb ) { "use strict" ; var params = [ 'receive' ] ; if ( opts . verbose ) { params . push ( '-v' ) ; } if ( opts . noop ) { params . push ( '-n' ) ; } if ( opts . force ) { params . push ( '-F' ) ; } if ( opts . unmounted ) { params . push ( '-u' ) ; } if ( opts . d ) { params . push ( '-d' ) ; } if ( opts . e ) { params . push ( '-e' ) ; } params . push ( opts . dataset ) ; spawnzfs ( params , function ( err , child ) { if ( err ) { return cb ( err ) ; } var buffer = [ ] ; var receiveStream = child . stdin ; child . stderr . on ( 'data' , function ( data ) { data = data . toString ( ) ; buffer . push ( data ) ; if ( opts . verbose ) { receiveStream . emit ( 'verbose' , data ) ; } //only keep last 5 lines if ( buffer . length > 5 ) { buffer . shift ( ) ; } } ) ; child . once ( 'exit' , function ( code ) { if ( code !== 0 ) { var message = 'Receive Error: ' + util . compact ( buffer . join ( '\n' ) . split ( '\n' ) ) . join ( '; ' ) . trim ( ) ; var err = new Error ( message ) ; err . code = code ; receiveStream . emit ( 'error' , err ) ; } } ) ; return cb ( null , receiveStream ) ; } ) ; }


Input: This is not valid for simpleStrings [CODESPLIT] function copyString ( buffer , length , offsetBegin , offsetEnd ) { if ( length > 2048 ) { return buffer . toString ( 'utf-8' , offsetBegin , offsetEnd ) ; } var string = '' ; while ( offsetBegin < offsetEnd ) { string += String . fromCharCode ( buffer [ offsetBegin ++ ] ) ; } return string ; }


Input: This is not UTF - 8 compliant [CODESPLIT] function parseSimpleString ( parser ) { var offset = parser . offset ; var length = parser . buffer . length ; var string = '' ; while ( offset < length ) { var c1 = parser . buffer [ offset ++ ] ; if ( c1 === 13 ) { var c2 = parser . buffer [ offset ++ ] ; if ( c2 === 10 ) { parser . offset = offset ; return string ; } string += String . fromCharCode ( c1 ) + String . fromCharCode ( c2 ) ; continue ; } string += String . fromCharCode ( c1 ) ; } return undefined ; }


Input: Build base config [CODESPLIT] function getBaseConfig ( isProd ) { // get library details from JSON config const libraryEntryPoint = path . join ( 'src' , LIBRARY_DESC . entry ) ; // generate webpack base config return { entry : [ // "babel-polyfill", path . join ( __dirname , libraryEntryPoint ) , ] , output : { devtoolLineToLine : true , pathinfo : true , } , module : { preLoaders : [ { test : / \.js$ / , exclude : / (node_modules|bower_components) / , loader : "eslint-loader" , } , ] , loaders : [ { exclude : / (node_modules|bower_components) / , loader : "babel-loader" , plugins : [ "transform-runtime" , ] , query : { presets : [ "es2015" , "stage-0" , "stage-1" , "stage-2" , ] , cacheDirectory : false , } , test : / \.js$ / , } , ] , } , eslint : { configFile : './.eslintrc' , } , resolve : { root : path . resolve ( './src' ) , extensions : [ '' , '.js' ] , } , devtool : isProd ? "source-map" /* null*/ : "source-map" /* '#eval-source-map'*/ , debug : ! isProd , plugins : isProd ? [ new webpack . DefinePlugin ( { 'process.env' : { NODE_ENV : '"production"' } } ) , new UglifyJsPlugin ( { compress : { warnings : true } , minimize : true , sourceMap : true , } ) , // Prod plugins here ] : [ new webpack . DefinePlugin ( { 'process.env' : { NODE_ENV : '"development"' } } ) , new UglifyJsPlugin ( { compress : { warnings : true } , minimize : true , sourceMap : true , } ) , // Dev plugins here ] , } ; }


Input: Methods @private Returns info about raw updates from Telegram Bot API [CODESPLIT] function getUpdateInfo ( update ) { /** Is it chosen inline or edited message/post */ let isChosen = false ; let isEdited = false ; /** Raw and formatted names of update */ let original = '' ; let name = '' ; if ( update . message ) { name = 'message' ; original = 'message' ; } else if ( update . edited_message ) { isEdited = true ; original = 'edited_message' ; name = 'message' ; } else if ( update . channel_post ) { original = 'channel_post' ; name = 'post' ; } else if ( update . edited_channel_post ) { isEdited = true ; original = 'edited_channel_post' ; name = 'post' ; } else if ( update . inline_query ) { original = 'inline_query' ; name = 'inline' ; } else if ( update . chosen_inline_result ) { isChosen = true ; original = 'chosen_inline_result' ; name = 'inline' ; } else if ( update . callback_query ) { original = 'callback_query' ; name = 'callback' ; } return { isChosen , isEdited , original , name } ; }


Input: -------------- [CODESPLIT] function attachStreamToSocket ( readStream , socketWriteStream , callback , usePipe = false ) { if ( ! usePipe ) { _attachStreamToSocket ( readStream , socketWriteStream , callback ) ; } else { readStream . pipe ( socketWriteStream , { end : false } ) ; readStream . once ( 'end' , ( ) => { readStream . unpipe ( ) ; callback ( ) ; } ) ; } }


Input: Public function to notify [CODESPLIT] function postNotification ( options , cb ) { options . title = removeColor ( options . title ) ; options . message = removeColor ( options . message ) ; if ( ! options . message ) { return cb && cb ( ! options . message && 'Message is required' ) ; } if ( ! notifyPlatform ) { notifyPlatform = choosePlatform ( ) ; } function resetPreviousTimer ( newMessage ) { previousMessage = newMessage ; clearTimeout ( previousMessageTimer ) ; previousMessageTimer = setTimeout ( function ( ) { previousMessage = false ; } , previousMessageTimeoutMS ) ; } if ( options . message === previousMessage ) { resetPreviousTimer ( options . message ) ; if ( typeof cb === 'function' ) { cb ( err ) ; } return ; } resetPreviousTimer ( options . message ) ; options . debug = debug ( notifyPlatform . name ) ; //for debug logging return notifyPlatform . notify ( options , function ( err ) { if ( err ) { options . debug ( { return_code : err } ) ; } if ( typeof cb === 'function' ) { cb ( err ) ; } } ) ; }


Input: Create a new Compiler with the given options . [CODESPLIT] function Compiler ( file , options ) { this . options = options || { } ; this . parser = new Parser ( file , options ) ; this . compilers = { } ; this . files = [ ] ; this . file = file ; this . files = [ this . file ] ; this . result = '' ; }


Input: Render [CODESPLIT] function dry ( file , options ) { debug ( 'rendering <%s>' , file . path ) ; var opts = utils . extend ( { } , options ) ; dry . parse ( file , opts ) ; dry . compile ( file , opts ) ; file . fn ( opts . locals ) ; return file ; }


Input: Adds numbers to a base name until it finds a unique database key [CODESPLIT] function generateUsername ( base ) { base = base . toLowerCase ( ) ; var entries = [ ] ; var finalName ; return userDB . allDocs ( { startkey : base , endkey : base + '\uffff' , include_docs : false } ) . then ( function ( results ) { if ( results . rows . length === 0 ) { return BPromise . resolve ( base ) ; } for ( var i = 0 ; i < results . rows . length ; i ++ ) { entries . push ( results . rows [ i ] . id ) ; } if ( entries . indexOf ( base ) === - 1 ) { return BPromise . resolve ( base ) ; } var num = 0 ; while ( ! finalName ) { num ++ ; if ( entries . indexOf ( base + num ) === - 1 ) { finalName = base + num ; } } return BPromise . resolve ( finalName ) ; } ) ; }


Input: Function to initialize a session following authentication from a socialAuth provider [CODESPLIT] function initSession ( req , res , next ) { var provider = getProvider ( req . path ) ; return user . createSession ( req . user . _id , provider , req ) . then ( function ( mySession ) { return BPromise . resolve ( { error : null , session : mySession , link : null } ) ; } ) . then ( function ( results ) { var template ; if ( config . getItem ( 'testMode.oauthTest' ) ) { template = fs . readFileSync ( path . join ( __dirname , '../templates/oauth/auth-callback-test.ejs' ) , 'utf8' ) ; } else { template = fs . readFileSync ( path . join ( __dirname , '../templates/oauth/auth-callback.ejs' ) , 'utf8' ) ; } var html = ejs . render ( template , results ) ; res . status ( 200 ) . send ( html ) ; } , function ( err ) { return next ( err ) ; } ) ; }


Input: Function to initialize a session following authentication from a socialAuth provider [CODESPLIT] function initTokenSession ( req , res , next ) { var provider = getProviderToken ( req . path ) ; return user . createSession ( req . user . _id , provider , req ) . then ( function ( mySession ) { return BPromise . resolve ( mySession ) ; } ) . then ( function ( session ) { res . status ( 200 ) . json ( session ) ; } , function ( err ) { return next ( err ) ; } ) ; }


Input: Called after an account has been succesfully linked [CODESPLIT] function linkSuccess ( req , res , next ) { var provider = getProvider ( req . path ) ; var result = { error : null , session : null , link : provider } ; var template ; if ( config . getItem ( 'testMode.oauthTest' ) ) { template = fs . readFileSync ( path . join ( __dirname , '../templates/oauth/auth-callback-test.ejs' ) , 'utf8' ) ; } else { template = fs . readFileSync ( path . join ( __dirname , '../templates/oauth/auth-callback.ejs' ) , 'utf8' ) ; } var html = ejs . render ( template , result ) ; res . status ( 200 ) . send ( html ) ; }


Input: Called after an account has been succesfully linked using access_token provider [CODESPLIT] function linkTokenSuccess ( req , res , next ) { var provider = getProviderToken ( req . path ) ; res . status ( 200 ) . json ( { ok : true , success : util . capitalizeFirstLetter ( provider ) + ' successfully linked' , provider : provider } ) ; }


Input: Handles errors if authentication fails [CODESPLIT] function oauthErrorHandler ( err , req , res , next ) { var template ; if ( config . getItem ( 'testMode.oauthTest' ) ) { template = fs . readFileSync ( path . join ( __dirname , '../templates/oauth/auth-callback-test.ejs' ) , 'utf8' ) ; } else { template = fs . readFileSync ( path . join ( __dirname , '../templates/oauth/auth-callback.ejs' ) , 'utf8' ) ; } var html = ejs . render ( template , { error : err . message , session : null , link : null } ) ; console . error ( err ) ; if ( err . stack ) { console . error ( err . stack ) ; } res . status ( 400 ) . send ( html ) ; }


Input: Handles errors if authentication from access_token provider fails [CODESPLIT] function tokenAuthErrorHandler ( err , req , res , next ) { var status ; if ( req . user && req . user . _id ) { status = 403 ; } else { status = 401 ; } console . error ( err ) ; if ( err . stack ) { console . error ( err . stack ) ; delete err . stack ; } res . status ( status ) . json ( err ) ; }


Input: Framework to register OAuth providers with passport [CODESPLIT] function registerProvider ( provider , configFunction ) { provider = provider . toLowerCase ( ) ; var configRef = 'providers.' + provider ; if ( config . getItem ( configRef + '.credentials' ) ) { var credentials = config . getItem ( configRef + '.credentials' ) ; credentials . passReqToCallback = true ; var options = config . getItem ( configRef + '.options' ) || { } ; configFunction . call ( null , credentials , passport , authHandler ) ; router . get ( '/' + provider , passportCallback ( provider , options , 'login' ) ) ; router . get ( '/' + provider + '/callback' , passportCallback ( provider , options , 'login' ) , initSession , oauthErrorHandler ) ; if ( ! config . getItem ( 'security.disableLinkAccounts' ) ) { router . get ( '/link/' + provider , passport . authenticate ( 'bearer' , { session : false } ) , passportCallback ( provider , options , 'link' ) ) ; router . get ( '/link/' + provider + '/callback' , passport . authenticate ( 'bearer' , { session : false } ) , passportCallback ( provider , options , 'link' ) , linkSuccess , oauthErrorHandler ) ; } console . log ( provider + ' loaded.' ) ; } }


Input: A shortcut to register OAuth2 providers that follow the exact accessToken refreshToken pattern . [CODESPLIT] function registerOAuth2 ( providerName , Strategy ) { registerProvider ( providerName , function ( credentials , passport , authHandler ) { passport . use ( new Strategy ( credentials , function ( req , accessToken , refreshToken , profile , done ) { authHandler ( req , providerName , { accessToken : accessToken , refreshToken : refreshToken } , profile ) . asCallback ( done ) ; } ) ) ; } ) ; }


Input: Registers a provider that accepts an access_token directly from the client skipping the popup window and callback This is for supporting Cordova native IOS and Android apps as well as other devices [CODESPLIT] function registerTokenProvider ( providerName , Strategy ) { providerName = providerName . toLowerCase ( ) ; var configRef = 'providers.' + providerName ; if ( config . getItem ( configRef + '.credentials' ) ) { var credentials = config . getItem ( configRef + '.credentials' ) ; credentials . passReqToCallback = true ; var options = config . getItem ( configRef + '.options' ) || { } ; // Configure the Passport Strategy passport . use ( providerName + '-token' , new Strategy ( credentials , function ( req , accessToken , refreshToken , profile , done ) { authHandler ( req , providerName , { accessToken : accessToken , refreshToken : refreshToken } , profile ) . asCallback ( done ) ; } ) ) ; router . post ( '/' + providerName + '/token' , passportTokenCallback ( providerName , options ) , initTokenSession , tokenAuthErrorHandler ) ; if ( ! config . getItem ( 'security.disableLinkAccounts' ) ) { router . post ( '/link/' + providerName + '/token' , passport . authenticate ( 'bearer' , { session : false } ) , passportTokenCallback ( providerName , options ) , linkTokenSuccess , tokenAuthErrorHandler ) ; } console . log ( providerName + '-token loaded.' ) ; } }


Input: This is called after a user has successfully authenticated with a provider If a user is authenticated with a bearer token we will link an account otherwise log in auth is an object containing access_token and optionally refresh_token [CODESPLIT] function authHandler ( req , provider , auth , profile ) { if ( req . user && req . user . _id && req . user . key ) { return user . linkSocial ( req . user . _id , provider , auth , profile , req ) ; } else { return user . socialAuth ( provider , auth , profile , req ) ; } }


Input: Configures the passport . authenticate for the given provider passing in options Operation is login or link [CODESPLIT] function passportCallback ( provider , options , operation ) { return function ( req , res , next ) { var theOptions = extend ( { } , options ) ; if ( provider === 'linkedin' ) { theOptions . state = true ; } var accessToken = req . query . bearer_token || req . query . state ; if ( accessToken && ( stateRequired . indexOf ( provider ) > - 1 || config . getItem ( 'providers.' + provider + '.stateRequired' ) === true ) ) { theOptions . state = accessToken ; } theOptions . callbackURL = getLinkCallbackURLs ( provider , req , operation , accessToken ) ; theOptions . session = false ; passport . authenticate ( provider , theOptions ) ( req , res , next ) ; } ; }


Input: Configures the passport . authenticate for the given access_token provider passing in options [CODESPLIT] function passportTokenCallback ( provider , options ) { return function ( req , res , next ) { var theOptions = extend ( { } , options ) ; theOptions . session = false ; passport . authenticate ( provider + '-token' , theOptions ) ( req , res , next ) ; } ; }


Input: Gets the provider name from a callback path [CODESPLIT] function getProvider ( pathname ) { var items = pathname . split ( '/' ) ; var index = items . indexOf ( 'callback' ) ; if ( index > 0 ) { return items [ index - 1 ] ; } }


Input: Gets the provider name from a callback path for access_token strategy [CODESPLIT] function getProviderToken ( pathname ) { var items = pathname . split ( '/' ) ; var index = items . indexOf ( 'token' ) ; if ( index > 0 ) { return items [ index - 1 ] ; } }


Input: Requires that the user have the specified role [CODESPLIT] function requireRole ( requiredRole ) { return function ( req , res , next ) { if ( ! req . user ) { return next ( superloginError ) ; } var roles = req . user . roles ; if ( ! roles || ! roles . length || roles . indexOf ( requiredRole ) === - 1 ) { res . status ( forbiddenError . status ) ; res . json ( forbiddenError ) ; } else { next ( ) ; } } ; }


Input: Escapes any characters that are illegal in a CouchDB database name using percent codes inside parenthesis Example : My . name [CODESPLIT] function getLegalDBName ( input ) { input = input . toLowerCase ( ) ; var output = encodeURIComponent ( input ) ; output = output . replace ( / \. / g , '%2E' ) ; output = output . replace ( / ! / g , '%21' ) ; output = output . replace ( / ~ / g , '%7E' ) ; output = output . replace ( / \* / g , '%2A' ) ; output = output . replace ( / ' / g , '%27' ) ; output = output . replace ( / \( / g , '%28' ) ; output = output . replace ( / \) / g , '%29' ) ; output = output . replace ( / \- / g , '%2D' ) ; output = output . toLowerCase ( ) ; output = output . replace ( / (%..) / g , function ( esc ) { esc = esc . substr ( 1 ) ; return '(' + esc + ')' ; } ) ; return output ; }


Input: BPromise . config ( { warnings : false } ) ; [CODESPLIT] function FileAdapter ( config ) { var sessionsRoot = config . getItem ( 'session.file.sessionsRoot' ) ; this . _sessionFolder = path . join ( process . env . PWD , sessionsRoot ) ; console . log ( 'File Adapter loaded' ) ; }


Input: Wire up rotation controls [CODESPLIT] function ( ) { var foundLayer = null ; $ . each ( projectedTiles , function ( layerName , layer ) { if ( map . hasLayer ( layer ) ) { foundLayer = layer ; } } ) ; return foundLayer ; }


Input: Public Functions [CODESPLIT] function ( tileLayer ) { if ( this . options . changingMap ) { return false ; } // Check for existing layer if ( this . _usingTileProjection ( tileLayer ) ) { console . log ( "That tile layer is already active." ) ; } else { // Drop base tile layers this . _dropTileLayers ( ) ; this . _update ( tileLayer ) ; } }


Input: Manually remove layers before destroying map . See https : // github . com / Leaflet / Leaflet / issues / 2718 [CODESPLIT] function ( ) { for ( var i in this . _layers ) { this . removeLayer ( this . _layers [ i ] ) ; } L . Map . prototype . remove . call ( this ) ; return this ; }


Input: Private Functions [CODESPLIT] function ( crs , options ) { var resolutions = [ ] ; for ( var zoom = options . minZoom ; zoom <= options . maxZoom ; zoom ++ ) { resolutions . push ( options . maxResolution / Math . pow ( 2 , zoom ) ) ; } return new L . Proj . CRS ( crs , options . proj4def , { origin : options . origin , resolutions : resolutions , bounds : options . projectedBounds } ) ; }


Input: Use default CRS classes for common codes fallback to custom for all other codes . [CODESPLIT] function ( crs , options ) { switch ( crs ) { case "EPSG:3857" : return L . CRS . EPSG3857 ; case "EPSG:3395" : return L . CRS . EPSG3395 ; case "EPSG:4326" : return L . CRS . EPSG4326 ; default : return this . _defineMapCRS ( crs , options ) ; } }


Input: This recurses through all the map s layers to update layer positions after their positions moved . [CODESPLIT] function ( group ) { var map = this ; if ( group . eachLayer ) { group . eachLayer ( function ( layer ) { map . _updateAllLayers ( layer ) ; } ) ; } else { if ( group . redraw ) { group . redraw ( ) ; } else if ( group . update ) { group . update ( ) ; } else { console . log ( "Don't know how to update" , group ) ; } } }


Input: Takes an array of markers and adds them in bulk [CODESPLIT] function ( layersArray ) { var fg = this . _featureGroup , npg = this . _nonPointGroup , chunked = this . options . chunkedLoading , chunkInterval = this . options . chunkInterval , chunkProgress = this . options . chunkProgress , newMarkers , i , l , m ; if ( this . _map ) { var offset = 0 , started = ( new Date ( ) ) . getTime ( ) ; var process = L . bind ( function ( ) { var start = ( new Date ( ) ) . getTime ( ) ; for ( ; offset < layersArray . length ; offset ++ ) { if ( chunked && offset % 200 === 0 ) { // every couple hundred markers, instrument the time elapsed since processing started: var elapsed = ( new Date ( ) ) . getTime ( ) - start ; if ( elapsed > chunkInterval ) { break ; // been working too hard, time to take a break :-) } } m = layersArray [ offset ] ; //Not point data, can't be clustered if ( ! m . getLatLng ) { npg . addLayer ( m ) ; continue ; } if ( this . hasLayer ( m ) ) { continue ; } this . _addLayer ( m , this . _maxZoom ) ; //If we just made a cluster of size 2 then we need to remove the other marker from the map (if it is) or we never will if ( m . __parent ) { if ( m . __parent . getChildCount ( ) === 2 ) { var markers = m . __parent . getAllChildMarkers ( ) , otherMarker = markers [ 0 ] === m ? markers [ 1 ] : markers [ 0 ] ; fg . removeLayer ( otherMarker ) ; } } } if ( chunkProgress ) { // report progress and time elapsed: chunkProgress ( offset , layersArray . length , ( new Date ( ) ) . getTime ( ) - started ) ; } if ( offset === layersArray . length ) { //Update the icons of all those visible clusters that were affected this . _featureGroup . eachLayer ( function ( c ) { if ( c instanceof L . MarkerCluster && c . _iconNeedsUpdate ) { c . _updateIcon ( ) ; } } ) ; this . _topClusterLevel . _recursivelyAddChildrenToMap ( null , this . _zoom , this . _currentShownBounds ) ; } else { setTimeout ( process , this . options . chunkDelay ) ; } } , this ) ; process ( ) ; } else { newMarkers = [ ] ; for ( i = 0 , l = layersArray . length ; i < l ; i ++ ) { m = layersArray [ i ] ; //Not point data, can't be clustered if ( ! m . getLatLng ) { npg . addLayer ( m ) ; continue ; } if ( this . hasLayer ( m ) ) { continue ; } newMarkers . push ( m ) ; } this . _needsClustering = this . _needsClustering . concat ( newMarkers ) ; } return this ; }


Input: Takes an array of markers and removes them in bulk [CODESPLIT] function ( layersArray ) { var i , l , m , fg = this . _featureGroup , npg = this . _nonPointGroup ; if ( ! this . _map ) { for ( i = 0 , l = layersArray . length ; i < l ; i ++ ) { m = layersArray [ i ] ; this . _arraySplice ( this . _needsClustering , m ) ; npg . removeLayer ( m ) ; } return this ; } for ( i = 0 , l = layersArray . length ; i < l ; i ++ ) { m = layersArray [ i ] ; if ( ! m . __parent ) { npg . removeLayer ( m ) ; continue ; } this . _removeLayer ( m , true , true ) ; if ( fg . hasLayer ( m ) ) { fg . removeLayer ( m ) ; if ( m . setOpacity ) { m . setOpacity ( 1 ) ; } } } //Fix up the clusters and markers on the map this . _topClusterLevel . _recursivelyAddChildrenToMap ( null , this . _zoom , this . _currentShownBounds ) ; fg . eachLayer ( function ( c ) { if ( c instanceof L . MarkerCluster ) { c . _updateIcon ( ) ; } } ) ; return this ; }


Input: Override FeatureGroup . getBounds as it doesn t work [CODESPLIT] function ( ) { var bounds = new L . LatLngBounds ( ) ; if ( this . _topClusterLevel ) { bounds . extend ( this . _topClusterLevel . _bounds ) ; } for ( var i = this . _needsClustering . length - 1 ; i >= 0 ; i -- ) { bounds . extend ( this . _needsClustering [ i ] . getLatLng ( ) ) ; } bounds . extend ( this . _nonPointGroup . getBounds ( ) ) ; return bounds ; }


Input: Overrides LayerGroup . eachLayer [CODESPLIT] function ( method , context ) { var markers = this . _needsClustering . slice ( ) , i ; if ( this . _topClusterLevel ) { this . _topClusterLevel . getAllChildMarkers ( markers ) ; } for ( i = markers . length - 1 ; i >= 0 ; i -- ) { method . call ( context , markers [ i ] ) ; } this . _nonPointGroup . eachLayer ( method , context ) ; }


Input: Overrides LayerGroup . getLayer WARNING : Really bad performance [CODESPLIT] function ( id ) { var result = null ; this . eachLayer ( function ( l ) { if ( L . stamp ( l ) === id ) { result = l ; } } ) ; return result ; }


Input: Returns true if the given layer is in this MarkerClusterGroup [CODESPLIT] function ( layer ) { if ( ! layer ) { return false ; } var i , anArray = this . _needsClustering ; for ( i = anArray . length - 1 ; i >= 0 ; i -- ) { if ( anArray [ i ] === layer ) { return true ; } } anArray = this . _needsRemoving ; for ( i = anArray . length - 1 ; i >= 0 ; i -- ) { if ( anArray [ i ] === layer ) { return false ; } } return ! ! ( layer . __parent && layer . __parent . _group === this ) || this . _nonPointGroup . hasLayer ( layer ) ; }


Input: Zoom down to show the given layer ( spiderfying if necessary ) then calls the callback [CODESPLIT] function ( layer , callback ) { var showMarker = function ( ) { if ( ( layer . _icon || layer . __parent . _icon ) && ! this . _inZoomAnimation ) { this . _map . off ( 'moveend' , showMarker , this ) ; this . off ( 'animationend' , showMarker , this ) ; if ( layer . _icon ) { callback ( ) ; } else if ( layer . __parent . _icon ) { var afterSpiderfy = function ( ) { this . off ( 'spiderfied' , afterSpiderfy , this ) ; callback ( ) ; } ; this . on ( 'spiderfied' , afterSpiderfy , this ) ; layer . __parent . spiderfy ( ) ; } } } ; if ( layer . _icon && this . _map . getBounds ( ) . contains ( layer . getLatLng ( ) ) ) { //Layer is visible ond on screen, immediate return callback ( ) ; } else if ( layer . __parent . _zoom < this . _map . getZoom ( ) ) { //Layer should be visible at this zoom level. It must not be on screen so just pan over to it this . _map . on ( 'moveend' , showMarker , this ) ; this . _map . panTo ( layer . getLatLng ( ) ) ; } else { var moveStart = function ( ) { this . _map . off ( 'movestart' , moveStart , this ) ; moveStart = null ; } ; this . _map . on ( 'movestart' , moveStart , this ) ; this . _map . on ( 'moveend' , showMarker , this ) ; this . on ( 'animationend' , showMarker , this ) ; layer . __parent . zoomToBounds ( ) ; if ( moveStart ) { //Never started moving, must already be there, probably need clustering however showMarker . call ( this ) ; } } }


Input: Overrides FeatureGroup . onAdd [CODESPLIT] function ( map ) { this . _map = map ; var i , l , layer ; if ( ! isFinite ( this . _map . getMaxZoom ( ) ) ) { throw "Map has no maxZoom specified" ; } this . _featureGroup . onAdd ( map ) ; this . _nonPointGroup . onAdd ( map ) ; if ( ! this . _gridClusters ) { this . _generateInitialClusters ( ) ; } for ( i = 0 , l = this . _needsRemoving . length ; i < l ; i ++ ) { layer = this . _needsRemoving [ i ] ; this . _removeLayer ( layer , true ) ; } this . _needsRemoving = [ ] ; //Remember the current zoom level and bounds this . _zoom = this . _map . getZoom ( ) ; this . _currentShownBounds = this . _getExpandedVisibleBounds ( ) ; this . _map . on ( 'zoomend' , this . _zoomEnd , this ) ; this . _map . on ( 'moveend' , this . _moveEnd , this ) ; if ( this . _spiderfierOnAdd ) { //TODO FIXME: Not sure how to have spiderfier add something on here nicely this . _spiderfierOnAdd ( ) ; } this . _bindEvents ( ) ; //Actually add our markers to the map: l = this . _needsClustering ; this . _needsClustering = [ ] ; this . addLayers ( l ) ; }


Input: Overrides FeatureGroup . onRemove [CODESPLIT] function ( map ) { map . off ( 'zoomend' , this . _zoomEnd , this ) ; map . off ( 'moveend' , this . _moveEnd , this ) ; this . _unbindEvents ( ) ; //In case we are in a cluster animation this . _map . _mapPane . className = this . _map . _mapPane . className . replace ( ' leaflet-cluster-anim' , '' ) ; if ( this . _spiderfierOnRemove ) { //TODO FIXME: Not sure how to have spiderfier add something on here nicely this . _spiderfierOnRemove ( ) ; } //Clean up all the layers we added to the map this . _hideCoverage ( ) ; this . _featureGroup . onRemove ( map ) ; this . _nonPointGroup . onRemove ( map ) ; this . _featureGroup . clearLayers ( ) ; this . _map = null ; }


Input: Remove the given object from the given array [CODESPLIT] function ( anArray , obj ) { for ( var i = anArray . length - 1 ; i >= 0 ; i -- ) { if ( anArray [ i ] === obj ) { anArray . splice ( i , 1 ) ; return true ; } } }


Input: Internal function for removing a marker from everything . dontUpdateMap : set to true if you will handle updating the map manually ( for bulk functions ) [CODESPLIT] function ( marker , removeFromDistanceGrid , dontUpdateMap ) { var gridClusters = this . _gridClusters , gridUnclustered = this . _gridUnclustered , fg = this . _featureGroup , map = this . _map ; //Remove the marker from distance clusters it might be in if ( removeFromDistanceGrid ) { for ( var z = this . _maxZoom ; z >= 0 ; z -- ) { if ( ! gridUnclustered [ z ] . removeObject ( marker , map . project ( marker . getLatLng ( ) , z ) ) ) { break ; } } } //Work our way up the clusters removing them as we go if required var cluster = marker . __parent , markers = cluster . _markers , otherMarker ; //Remove the marker from the immediate parents marker list this . _arraySplice ( markers , marker ) ; while ( cluster ) { cluster . _childCount -- ; if ( cluster . _zoom < 0 ) { //Top level, do nothing break ; } else if ( removeFromDistanceGrid && cluster . _childCount <= 1 ) { //Cluster no longer required //We need to push the other marker up to the parent otherMarker = cluster . _markers [ 0 ] === marker ? cluster . _markers [ 1 ] : cluster . _markers [ 0 ] ; //Update distance grid gridClusters [ cluster . _zoom ] . removeObject ( cluster , map . project ( cluster . _cLatLng , cluster . _zoom ) ) ; gridUnclustered [ cluster . _zoom ] . addObject ( otherMarker , map . project ( otherMarker . getLatLng ( ) , cluster . _zoom ) ) ; //Move otherMarker up to parent this . _arraySplice ( cluster . __parent . _childClusters , cluster ) ; cluster . __parent . _markers . push ( otherMarker ) ; otherMarker . __parent = cluster . __parent ; if ( cluster . _icon ) { //Cluster is currently on the map, need to put the marker on the map instead fg . removeLayer ( cluster ) ; if ( ! dontUpdateMap ) { fg . addLayer ( otherMarker ) ; } } } else { cluster . _recalculateBounds ( ) ; if ( ! dontUpdateMap || ! cluster . _icon ) { cluster . _updateIcon ( ) ; } } cluster = cluster . __parent ; } delete marker . __parent ; }


Input:
Default functionality [CODESPLIT] function ( cluster ) { var childCount = cluster . getChildCount ( ) ; var c = ' marker-cluster-' ; if ( childCount < 10 ) { c += 'small' ; } else if ( childCount < 100 ) { c += 'medium' ; } else { c += 'large' ; } return new L . DivIcon ( { html : '
' + childCount + '
' , className : 'marker-cluster' + c , iconSize : new L . Point ( 40 , 40 ) } ) ; }


Input: Zoom : Zoom to start adding at ( Pass this . _maxZoom to start at the bottom ) [CODESPLIT] function ( layer , zoom ) { var gridClusters = this . _gridClusters , gridUnclustered = this . _gridUnclustered , markerPoint , z ; if ( this . options . singleMarkerMode ) { layer . options . icon = this . options . iconCreateFunction ( { getChildCount : function ( ) { return 1 ; } , getAllChildMarkers : function ( ) { return [ layer ] ; } } ) ; } //Find the lowest zoom level to slot this one in for ( ; zoom >= 0 ; zoom -- ) { markerPoint = this . _map . project ( layer . getLatLng ( ) , zoom ) ; // calculate pixel position //Try find a cluster close by var closest = gridClusters [ zoom ] . getNearObject ( markerPoint ) ; if ( closest ) { closest . _addChild ( layer ) ; layer . __parent = closest ; return ; } //Try find a marker close by to form a new cluster with closest = gridUnclustered [ zoom ] . getNearObject ( markerPoint ) ; if ( closest ) { var parent = closest . __parent ; if ( parent ) { this . _removeLayer ( closest , false ) ; } //Create new cluster with these 2 in it var newCluster = new L . MarkerCluster ( this , zoom , closest , layer ) ; gridClusters [ zoom ] . addObject ( newCluster , this . _map . project ( newCluster . _cLatLng , zoom ) ) ; closest . __parent = newCluster ; layer . __parent = newCluster ; //First create any new intermediate parent clusters that don't exist var lastParent = newCluster ; for ( z = zoom - 1 ; z > parent . _zoom ; z -- ) { lastParent = new L . MarkerCluster ( this , z , lastParent ) ; gridClusters [ z ] . addObject ( lastParent , this . _map . project ( closest . getLatLng ( ) , z ) ) ; } parent . _addChild ( lastParent ) ; //Remove closest from this zoom level and any above that it is in, replace with newCluster for ( z = zoom ; z >= 0 ; z -- ) { if ( ! gridUnclustered [ z ] . removeObject ( closest , this . _map . project ( closest . getLatLng ( ) , z ) ) ) { break ; } } return ; } //Didn't manage to cluster in at this zoom, record us as a marker here and continue upwards gridUnclustered [ zoom ] . addObject ( layer , markerPoint ) ; } //Didn't get in anything, add us to the top this . _topClusterLevel . _addChild ( layer ) ; layer . __parent = this . _topClusterLevel ; return ; }


Input: Enqueue code to fire after the marker expand / contract has happened [CODESPLIT] function ( fn ) { this . _queue . push ( fn ) ; if ( ! this . _queueTimeout ) { this . _queueTimeout = setTimeout ( L . bind ( this . _processQueue , this ) , 300 ) ; } }


Input: Gets the maps visible bounds expanded in each direction by the size of the screen ( so the user cannot see an area we do not cover in one pan ) [CODESPLIT] function ( ) { if ( ! this . options . removeOutsideVisibleBounds ) { return this . getBounds ( ) ; } var map = this . _map , bounds = map . getBounds ( ) , sw = bounds . _southWest , ne = bounds . _northEast , latDiff = L . Browser . mobile ? 0 : Math . abs ( sw . lat - ne . lat ) , lngDiff = L . Browser . mobile ? 0 : Math . abs ( sw . lng - ne . lng ) ; return new L . LatLngBounds ( new L . LatLng ( sw . lat - latDiff , sw . lng - lngDiff , true ) , new L . LatLng ( ne . lat + latDiff , ne . lng + lngDiff , true ) ) ; }


Input: Shared animation code [CODESPLIT] function ( layer , newCluster ) { if ( newCluster === layer ) { this . _featureGroup . addLayer ( layer ) ; } else if ( newCluster . _childCount === 2 ) { newCluster . _addToMap ( ) ; var markers = newCluster . getAllChildMarkers ( ) ; this . _featureGroup . removeLayer ( markers [ 0 ] ) ; this . _featureGroup . removeLayer ( markers [ 1 ] ) ; } else { newCluster . _updateIcon ( ) ; } }


Input: Recursively retrieve all child markers of this cluster [CODESPLIT] function ( storageArray ) { storageArray = storageArray || [ ] ; for ( var i = this . _childClusters . length - 1 ; i >= 0 ; i -- ) { this . _childClusters [ i ] . getAllChildMarkers ( storageArray ) ; } for ( var j = this . _markers . length - 1 ; j >= 0 ; j -- ) { storageArray . push ( this . _markers [ j ] ) ; } return storageArray ; }


Input: Zoom to the minimum of showing all of the child markers or the extents of this cluster [CODESPLIT] function ( ) { var childClusters = this . _childClusters . slice ( ) , map = this . _group . _map , boundsZoom = map . getBoundsZoom ( this . _bounds ) , zoom = this . _zoom + 1 , mapZoom = map . getZoom ( ) , i ; //calculate how far we need to zoom down to see all of the markers while ( childClusters . length > 0 && boundsZoom > zoom ) { zoom ++ ; var newClusters = [ ] ; for ( i = 0 ; i < childClusters . length ; i ++ ) { newClusters = newClusters . concat ( childClusters [ i ] . _childClusters ) ; } childClusters = newClusters ; } if ( boundsZoom > zoom ) { this . _group . _map . setView ( this . _latlng , zoom ) ; } else if ( boundsZoom <= mapZoom ) { //If fitBounds wouldn't zoom us down, zoom us down instead this . _group . _map . setView ( this . _latlng , mapZoom + 1 ) ; } else { this . _group . _map . fitBounds ( this . _bounds ) ; } }


Input: Expand our bounds and tell our parent to [CODESPLIT] function ( marker ) { var addedCount , addedLatLng = marker . _wLatLng || marker . _latlng ; if ( marker instanceof L . MarkerCluster ) { this . _bounds . extend ( marker . _bounds ) ; addedCount = marker . _childCount ; } else { this . _bounds . extend ( addedLatLng ) ; addedCount = 1 ; } if ( ! this . _cLatLng ) { // when clustering, take position of the first point as the cluster center this . _cLatLng = marker . _cLatLng || addedLatLng ; } // when showing clusters, take weighted average of all points as cluster center var totalCount = this . _childCount + addedCount ; //Calculate weighted latlng for display if ( ! this . _wLatLng ) { this . _latlng = this . _wLatLng = new L . LatLng ( addedLatLng . lat , addedLatLng . lng ) ; } else { this . _wLatLng . lat = ( addedLatLng . lat * addedCount + this . _wLatLng . lat * this . _childCount ) / totalCount ; this . _wLatLng . lng = ( addedLatLng . lng * addedCount + this . _wLatLng . lng * this . _childCount ) / totalCount ; } }


Input: exceptBounds : If set don t remove any markers / clusters in it [CODESPLIT] function ( previousBounds , zoomLevel , exceptBounds ) { var m , i ; this . _recursively ( previousBounds , - 1 , zoomLevel - 1 , function ( c ) { //Remove markers at every level for ( i = c . _markers . length - 1 ; i >= 0 ; i -- ) { m = c . _markers [ i ] ; if ( ! exceptBounds || ! exceptBounds . contains ( m . _latlng ) ) { c . _group . _featureGroup . removeLayer ( m ) ; if ( m . setOpacity ) { m . setOpacity ( 1 ) ; } } } } , function ( c ) { //Remove child clusters at just the bottom level for ( i = c . _childClusters . length - 1 ; i >= 0 ; i -- ) { m = c . _childClusters [ i ] ; if ( ! exceptBounds || ! exceptBounds . contains ( m . _latlng ) ) { c . _group . _featureGroup . removeLayer ( m ) ; if ( m . setOpacity ) { m . setOpacity ( 1 ) ; } } } } ) ; }


Input: Run the given functions recursively to this and child clusters boundsToApplyTo : a L . LatLngBounds representing the bounds of what clusters to recurse in to zoomLevelToStart : zoom level to start running functions ( inclusive ) zoomLevelToStop : zoom level to stop running functions ( inclusive ) runAtEveryLevel : function that takes an L . MarkerCluster as an argument that should be applied on every level runAtBottomLevel : function that takes an L . MarkerCluster as an argument that should be applied at only the bottom level [CODESPLIT] function ( boundsToApplyTo , zoomLevelToStart , zoomLevelToStop , runAtEveryLevel , runAtBottomLevel ) { var childClusters = this . _childClusters , zoom = this . _zoom , i , c ; if ( zoomLevelToStart > zoom ) { //Still going down to required depth, just recurse to child clusters for ( i = childClusters . length - 1 ; i >= 0 ; i -- ) { c = childClusters [ i ] ; if ( boundsToApplyTo . intersects ( c . _bounds ) ) { c . _recursively ( boundsToApplyTo , zoomLevelToStart , zoomLevelToStop , runAtEveryLevel , runAtBottomLevel ) ; } } } else { //In required depth if ( runAtEveryLevel ) { runAtEveryLevel ( this ) ; } if ( runAtBottomLevel && this . _zoom === zoomLevelToStop ) { runAtBottomLevel ( this ) ; } //TODO: This loop is almost the same as above if ( zoomLevelToStop > zoom ) { for ( i = childClusters . length - 1 ; i >= 0 ; i -- ) { c = childClusters [ i ] ; if ( boundsToApplyTo . intersects ( c . _bounds ) ) { c . _recursively ( boundsToApplyTo , zoomLevelToStart , zoomLevelToStop , runAtEveryLevel , runAtBottomLevel ) ; } } } } }


Input: / * Given an array of latlngs compute a convex hull as an array of latlngs [CODESPLIT] function ( latLngs ) { // find first baseline var maxLat = false , minLat = false , maxPt = null , minPt = null , i ; for ( i = latLngs . length - 1 ; i >= 0 ; i -- ) { var pt = latLngs [ i ] ; if ( maxLat === false || pt . lat > maxLat ) { maxPt = pt ; maxLat = pt . lat ; } if ( minLat === false || pt . lat < minLat ) { minPt = pt ; minLat = pt . lat ; } } var ch = [ ] . concat ( this . buildConvexHull ( [ minPt , maxPt ] , latLngs ) , this . buildConvexHull ( [ maxPt , minPt ] , latLngs ) ) ; return ch ; }


Input: show spiral instead of circle from this marker count upwards . 0 - > always spiral ; Infinity - > always circle [CODESPLIT] function ( ) { if ( this . _group . _spiderfied === this || this . _group . _inZoomAnimation ) { return ; } var childMarkers = this . getAllChildMarkers ( ) , group = this . _group , map = group . _map , center = map . latLngToLayerPoint ( this . _latlng ) , positions ; this . _group . _unspiderfy ( ) ; this . _group . _spiderfied = this ; //TODO Maybe: childMarkers order by distance to center if ( childMarkers . length >= this . _circleSpiralSwitchover ) { positions = this . _generatePointsSpiral ( childMarkers . length , center ) ; } else { center . y += 10 ; //Otherwise circles look wrong positions = this . _generatePointsCircle ( childMarkers . length , center ) ; } this . _animationSpiderfy ( childMarkers , positions ) ; }


Input: Non Animated versions of everything [CODESPLIT] function ( childMarkers , positions ) { var group = this . _group , map = group . _map , fg = group . _featureGroup , i , m , leg , newPos ; for ( i = childMarkers . length - 1 ; i >= 0 ; i -- ) { newPos = map . layerPointToLatLng ( positions [ i ] ) ; m = childMarkers [ i ] ; m . _preSpiderfyLatlng = m . _latlng ; m . setLatLng ( newPos ) ; if ( m . setZIndexOffset ) { m . setZIndexOffset ( 1000000 ) ; //Make these appear on top of EVERYTHING } fg . addLayer ( m ) ; leg = new L . Polyline ( [ this . _latlng , newPos ] , { weight : 1.5 , color : '#222' } ) ; map . addLayer ( leg ) ; m . _spiderLeg = leg ; } this . setOpacity ( 0.3 ) ; group . fire ( 'spiderfied' ) ; }


Input: If the given layer is currently being spiderfied then we unspiderfy it so it isn t on the map anymore etc [CODESPLIT] function ( layer ) { if ( layer . _spiderLeg ) { this . _featureGroup . removeLayer ( layer ) ; layer . setOpacity ( 1 ) ; //Position will be fixed up immediately in _animationUnspiderfy layer . setZIndexOffset ( 0 ) ; this . _map . removeLayer ( layer . _spiderLeg ) ; delete layer . _spiderLeg ; } }


Input: Return the tile layer that has a key containing projection [CODESPLIT] function ( projection ) { for ( var key in projectedTiles ) { if ( projectedTiles . hasOwnProperty ( key ) ) { if ( key . indexOf ( projection ) !== - 1 ) { return projectedTiles [ key ] ; } } } return null ; }


Input: Return the tile layer that has a key containing projection [CODESPLIT] function ( projection ) { for ( var key in tiles ) { if ( tiles . hasOwnProperty ( key ) ) { if ( key . indexOf ( projection ) !== - 1 ) { return tiles [ key ] ; } } } return null ; }


Input: Have to create a separate marker for each map else weirdness happens [CODESPLIT] function addToMap ( location , map ) { var marker = L . marker ( location . coordinates ) ; marker . addTo ( map ) ; }


Input: avoid loading features South of 45N . Errors will occur when loading Antarctic data . [CODESPLIT] function ( featureData , layer ) { var coords = featureData . geometry . coordinates ; return boundsLimit . contains ( L . latLng ( [ coords [ 1 ] , coords [ 0 ] ] ) ) ; }


Input: avoid loading features South of 45N . Errors will occur when loading Antarctic data . [CODESPLIT] function ( featureData , layer ) { var bbox = featureData . geometry . bbox ; var llBounds = L . latLngBounds ( [ bbox [ 1 ] , bbox [ 0 ] ] , [ bbox [ 3 ] , bbox [ 2 ] ] ) ; return boundsLimit . contains ( llBounds ) ; }


Input: Interpolate the page path with pagination variables . [CODESPLIT] function interpolate ( path , data ) { return path . replace ( / :(\w+) / g , function ( match , param ) { return data [ param ] } ) }


Input: Create a get pages utility for people to use when rendering . [CODESPLIT] function createPagesUtility ( pages , index ) { return function getPages ( number ) { var offset = Math . floor ( number / 2 ) var start , end if ( index + offset >= pages . length ) { start = Math . max ( 0 , pages . length - number ) end = pages . length } else { start = Math . max ( 0 , index - offset ) end = Math . min ( start + number , pages . length ) } return pages . slice ( start , end ) } }


Input: helper engine that can use a template from a string [CODESPLIT] function ( ) { var templates = { data : { } } ; var stringTemplateSource = function ( template ) { this . text = function ( value ) { if ( arguments . length === 0 ) { return templates [ template ] ; } templates [ template ] = value ; } ; } ; var templateEngine = new ko . nativeTemplateEngine ( ) ; templateEngine . makeTemplateSource = function ( template ) { return new stringTemplateSource ( template ) ; } ; templateEngine . addTemplate = function ( key , value ) { templates [ key ] = value ; } ; return templateEngine ; }


Input: ::: PRIVATE FUNCTIONS [CODESPLIT] function beforeChild ( parserState , compilerState , result , checkParent ) { var _isDomMethod = checkParent !== true ? isDomMethod ( compilerState ) : isParentDomMethod ( compilerState ) ; var _numAttributes = checkParent !== true ? numAttributes ( parserState ) : numParentAttributes ( parserState ) ; var _numChildren = checkParent !== true ? numChildren ( parserState ) : numParentChildren ( parserState ) ; var _isTopLevelChild = checkParent !== true ? parserState . childCounts . length > 1 : parserState . childCounts . length > 2 ; if ( _isTopLevelChild === true ) { if ( _numAttributes <= 0 ) { if ( _numChildren <= 1 ) { if ( _isDomMethod !== true ) { // React.createElement("tag", result . push ( "," ) ; } // React.createElement("tag", null, // React.DOM.tag(null, result . push ( "null" ) ; result . push ( "," ) ; } else { // React.createElement("tag", {"attr":"value"}, sibling, // React.DOM.tag({"attr":"value"}, sibling, result . push ( "," ) ; } } else { // React.createElement("tag", {"attr":"value"}, // React.DOM.tag({"attr":"value"}, result . push ( "}" ) ; result . push ( "," ) ; } } // If top-level node with siblings else if ( _numChildren > 1 ) { // React.createElement(…), // React.DOM.tag(…), // "text", result . push ( "," ) ; } }


Input: Job retry specification [CODESPLIT] function Job ( collection , data ) { this . collection = collection ; if ( data ) { // Convert plain object to JobData type data . __proto__ = JobData . prototype ; this . data = data ; } else { this . data = new JobData ( ) ; } }


Input: Options for a new worker [CODESPLIT] function Worker ( queues , options ) { options || ( options = { } ) ; this . empty = 0 ; this . queues = queues || [ ] ; this . interval = options . interval || 5000 ; this . callbacks = options . callbacks || { } ; this . strategies = options . strategies || { } ; this . universal = options . universal || false ; // Default retry strategies this . strategies . linear || ( this . strategies . linear = linear ) ; this . strategies . exponential || ( this . strategies . exponential = exponential ) ; // This worker will only process jobs of this priority or higher this . minPriority = options . minPriority ; }


Input: uploader [CODESPLIT] function Uploader ( options ) { if ( typeof options !== 'object' ) { throw new TypeError ( 'options must be an object' ) ; } this . $el = this . _getElement ( options . el ) ; this . _elType = this . $el . tagName . toLowerCase ( ) ; // if ( options . name && typeof options . name !== 'string' ) { throw new TypeError ( 'options `name` must be a string' ) ; } if ( options . url && typeof options . url !== 'string' ) { throw new TypeError ( 'options `url` must be a string' ) ; } if ( options . method && typeof options . method !== 'string' ) { throw new TypeError ( 'options `method` must be a string' ) ; } if ( options . headers && typeof options . headers !== 'object' ) { throw new TypeError ( 'options `headers` must be an object' ) ; } // this . files = [ ] ; this . method = options . method || 'POST' ; this . name = options . name || 'file' ; this . url = options . url || null ; this . headers = options . headers || { } ; // EE3 EE3 . call ( this ) ; // error listener this . on ( 'error' , this . _onError . bind ( this ) ) ; // check support this . _checkSupport ( ) ; // attach to $el this . _attach ( ) ; }


Input: generic drag event handler [CODESPLIT] function handleDragEvents ( e ) { e . stopPropagation ( ) ; e . preventDefault ( ) ; return this . emit ( e . type , e ) ; }


Input: recodeの内容を、Excel上のカラム表示（A B ... ）にあわせてオブジェクトに格納し返却する。 [CODESPLIT] function formatRecordByColumnLabel ( recode ) { const recodeBuffer = { } ; recode . forEach ( function ( value , index ) { recodeBuffer [ new Ordinal ( index + 1 ) . toAlphabet ( ) ] = value ; } ) ; return recodeBuffer ; }


Input: recordの内容を、mappingで対応づけられたKey名にあわせてオブジェクトに格納し返却する。 [CODESPLIT] function formatRecordByMapping ( recode , mapping ) { return Object . keys ( mapping ) . reduce ( ( formatted , keyName ) => { if ( mapping [ keyName ] !== 0 ) { formatted [ keyName ] = recode [ new Ordinal ( mapping [ keyName ] ) . toNumber ( ) - 1 ] ; } return formatted ; } , { } ) ; }


Input: Device Object [CODESPLIT] function ( deviceInfo ) { this . _handle = deviceInfo . _handle ; this . address = deviceInfo . _handle ; this . name = deviceInfo . name ; this . serviceUUIDs = deviceInfo . uuids ; this . adData = deviceInfo . adData ; this . connected = false ; this . services = { } ; }


Input: Service Object [CODESPLIT] function ( serviceInfo ) { this . _handle = serviceInfo . _handle ; this . uuid = serviceInfo . uuid ; this . primary = serviceInfo . primary ; this . includedServices = { } ; this . characteristics = { } ; }


Input: Characteristic Object [CODESPLIT] function ( characteristicInfo ) { this . _handle = characteristicInfo . _handle ; this . uuid = characteristicInfo . uuid ; this . properties = characteristicInfo . properties ; this . descriptors = { } ; }


Input: Plugin function [CODESPLIT] function streamifyGulp ( pluginStream ) { var inputStream = new Stream . Transform ( { objectMode : true } ) ; var outputStream = new Stream . Transform ( { objectMode : true } ) ; var duplex = new Duplexer ( { objectMode : true } , inputStream , outputStream ) ; // Accepting functions returning streams if ( 'function' === typeof pluginStream ) { pluginStream = pluginStream ( ) ; } // Listening for plugin errors and reemit pluginStream . on ( 'error' , function ( error ) { duplex . emit ( 'error' , error ) ; } ) ; // Change files contents from stream to buffer and write to the plugin stream inputStream . _transform = function ( file , unused , cb ) { // Buffering the file stream var originalStream ; var buf ; var bufstream ; if ( file . isNull ( ) || file . isBuffer ( ) ) { inputStream . push ( file ) ; return cb ( ) ; } file . wasStream = true ; originalStream = file . contents ; buf = new Buffer ( 0 ) ; bufstream = new Stream . Writable ( ) ; // Buffer the stream bufstream . _write = function ( chunk , encoding , cb2 ) { buf = Buffer . concat ( [ buf , chunk ] , buf . length + chunk . length ) ; cb2 ( ) ; } ; // When buffered bufstream . once ( 'finish' , function ( ) { // Send the buffer wrapped in a file file . contents = buf ; inputStream . push ( file ) ; cb ( ) ; } ) ; originalStream . pipe ( bufstream ) ; } ; // Change files contents from buffer to stream and write to the output stream outputStream . _transform = function ( file , unused , cb ) { var buf ; var newStream ; if ( file . isNull ( ) || ! file . wasStream ) { outputStream . push ( file ) ; return cb ( ) ; } delete file . wasStream ; // Get the transformed buffer buf = file . contents ; newStream = new Stream . Readable ( ) ; // Write the buffer only when datas are needed newStream . _read = function ( ) { // Write the content back to the stream newStream . push ( buf ) ; newStream . push ( null ) ; } ; // Pass the file out file . contents = newStream ; outputStream . push ( file ) ; cb ( ) ; } ; outputStream . _flush = function ( cb ) { setImmediate ( function ( ) { // Old streams WTF if ( ! pluginStream . _readableState ) { outputStream . emit ( 'end' ) ; duplex . emit ( 'end' ) ; } } ) ; cb ( ) ; } ; inputStream . pipe ( pluginStream ) . pipe ( outputStream ) ; return duplex ; }


Input: More reliable indexOf courtesy of [CODESPLIT] function ( value ) { if ( value != value || value === 0 ) { for ( var i = this . length ; i -- && ! is ( this [ i ] , value ) ; ) { } } else { i = [ ] . indexOf . call ( this , value ) ; } return i ; }


Input: A wrapper for the tor process containing its ChildProcess port number and data directory . [CODESPLIT] function Tor ( child , port , dir ) { this . process = child ; this . port = port ; this . dir = dir ; }


Input: Returns an Array containing the included locations . [CODESPLIT] function getIncluded ( ) { var args = config . files ( ) . included || getDefaultArgs ( ) || getPackageJsonArgs ( ) || getBowerJsonArgs ( ) || [ ] ; return _expandGlobs ( args ) ; }


Input: Returns an Array of default paths . [CODESPLIT] function getDefaultArgs ( ) { var results = [ ] ; DEFAULT_PATHS . forEach ( function ( dir ) { if ( fs . existsSync ( dir ) ) results . push ( dir ) ; } ) ; return results . length == 0 ? null : results ; }


Input: Checks package . json for possible paths [CODESPLIT] function getPackageJsonArgs ( ) { var results = [ ] ; var config = _loadJson ( 'package.json' ) ; if ( config . main ) results = results . concat ( getMainFieldAsArray ( config . main ) ) ; if ( config . files ) results = results . concat ( config . files ) ; return results . length == 0 ? null : results . filter ( _uniqfilter ) ; }


Input: Checks bower . json for possible paths [CODESPLIT] function getBowerJsonArgs ( ) { var results = [ ] ; var config = _loadJson ( 'bower.json' ) ; if ( config . main ) results = results . concat ( getMainFieldAsArray ( config . main ) ) ; return results . length == 0 ? null : results . filter ( _uniqfilter ) ; }


Input: Returns an Array of the files mentioned in a main field If the value is noted without . js at the end it is appended . [CODESPLIT] function getMainFieldAsArray ( main ) { if ( main . constructor === Array ) { return main ; } else { if ( fs . existsSync ( main ) ) { return [ main ] ; } else if ( fs . existsSync ( main + '.js' ) ) { return [ main + '.js' ] ; } else { return [ ] ; } } }


Input: Check whether a symbol is a function and is the only symbol exported by a module ( as in module . exports = function () {} ; ) . [CODESPLIT] function isModuleFunction2 ( doclet ) { return doclet . longname && doclet . longname === doclet . name && doclet . longname . indexOf ( 'module:' ) === 0 && doclet . kind === 'function' ; }


Input: Retrieve all of the following types of members from a set of doclets : [CODESPLIT] function getMembers2 ( data ) { var find = function ( data , spec ) { return data ( spec ) . get ( ) ; } ; var members = { classes : find ( data , { kind : 'class' } ) , externals : find ( data , { kind : 'external' } ) , events : find ( data , { kind : 'event' } ) , globals : find ( data , { kind : [ 'member' , 'function' , 'constant' , 'typedef' ] , memberof : { isUndefined : true } } ) , mixins : find ( data , { kind : 'mixin' } ) , modules : find ( data , { kind : 'module' } ) , namespaces : find ( data , { kind : 'namespace' } ) , typedef : find ( data , { kind : 'typedef' , isTSEnum : { is : true } } ) , callbacks : find ( data , { kind : 'typedef' , isTSEnum : { isUndefined : true } } ) } ; // functions that are also modules (as in "module.exports = function() {};") are not globals members . globals = members . globals . filter ( function ( doclet ) { if ( isModuleFunction2 ( doclet ) ) { return false ; } return true ; } ) ; return members ; }


Input: / * xperiments [CODESPLIT] function ( field , reverse , primer ) { var key = function ( x ) { return primer ? primer ( x [ field ] ) : x [ field ] } ; return function ( a , b ) { var A = key ( a ) , B = key ( b ) ; return ( ( A < B ) ? - 1 : ( ( A > B ) ? 1 : 0 ) ) * [ - 1 , 1 ] [ + ! ! reverse ] ; } }


Input:
Create the navigation sidebar . [CODESPLIT] function buildNav ( members ) { var seen = { } ; var nav = navigationMaster ; if ( members . modules . length ) { members . modules . sort ( sort_by ( 'longname' , true , function ( a ) { return a . toUpperCase ( ) } ) ) ; members . modules . forEach ( function ( m ) { if ( ! hasOwnProp . call ( seen , m . longname ) ) { nav . module . members . push ( linkto ( m . longname , m . name ) ) ; } seen [ m . longname ] = true ; } ) ; } if ( members . externals . length ) { members . externals . sort ( sort_by ( 'longname' , true , function ( a ) { return a . toUpperCase ( ) } ) ) ; members . externals . forEach ( function ( e ) { if ( ! hasOwnProp . call ( seen , e . longname ) ) { nav . external . members . push ( linkto ( e . longname , e . name . replace ( / (^"|"$) / g , '' ) ) ) ; } seen [ e . longname ] = true ; } ) ; } if ( members . classes . length ) { members . classes . sort ( sort_by ( 'longname' , true , function ( a ) { return a . toUpperCase ( ) } ) ) ; members . classes . forEach ( function ( c ) { if ( ! hasOwnProp . call ( seen , c . longname ) ) { nav . class . members . push ( { link : linkto ( c . longname , c . longname ) , namespace : c } ) ; } seen [ c . longname ] = true ; } ) ; } /*
	 if ( members.events.length ) {

	 members.events.forEach( function ( e ) {
	 if ( !hasOwnProp.call( seen, e.longname ) ) {

	 nav.event.members.push( linkto( e.longname, e.name ) );

	 }
	 seen[e.longname] = true;
	 } );

	 }*/ if ( members . typedef . length ) { members . typedef . forEach ( function ( td ) { if ( ! hasOwnProp . call ( seen , td . longname ) ) { nav . typedef . members . push ( { link : linkto ( td . name , td . name ) , namespace : { longname : td . longname } } ) ; } seen [ td . longname ] = true ; } ) ; } if ( members . callbacks . length ) { members . callbacks . forEach ( function ( cb ) { if ( ! hasOwnProp . call ( seen , cb . longname ) ) { nav . callbacks . members . push ( { link : linkto ( cb . longname , cb . longname . split ( '#' ) [ 0 ] ) , namespace : { longname : cb . longname } } ) ; } seen [ cb . longname ] = true ; } ) ; } if ( members . namespaces . length ) { members . namespaces . sort ( sort_by ( 'longname' , true , function ( a ) { return a . toUpperCase ( ) } ) ) ; members . namespaces . forEach ( function ( n ) { if ( ! hasOwnProp . call ( seen , n . longname ) ) { nav . namespace . members . push ( { link : linkto ( n . longname , n . longname ) , namespace : n } ) ; } seen [ n . longname ] = true ; } ) ; } if ( members . mixins . length ) { members . mixins . sort ( sort_by ( 'longname' , true , function ( a ) { return a . toUpperCase ( ) } ) ) ; members . mixins . forEach ( function ( m ) { if ( ! hasOwnProp . call ( seen , m . longname ) ) { nav . mixin . members . push ( linkto ( m . longname , m . longname ) ) ; } seen [ m . longname ] = true ; } ) ; } if ( members . tutorials . length ) { members . tutorials . sort ( sort_by ( 'name' , true , function ( a ) { return a . toUpperCase ( ) } ) ) ; members . tutorials . forEach ( function ( t ) { nav . tutorial . members . push ( tutoriallink ( t . name ) ) ; } ) ; } if ( members . globals . length ) { members . globals . sort ( sort_by ( 'longname' , true , function ( a ) { return a . toUpperCase ( ) } ) ) ; members . globals . forEach ( function ( g ) { if ( g . kind !== 'typedef' && ! hasOwnProp . call ( seen , g . longname ) ) { nav . global . members . push ( linkto ( g . longname , g . longname ) ) ; } seen [ g . longname ] = true ; } ) ; } var topLevelNav = [ ] ; _ . each ( nav , function ( entry , name ) { if ( entry . members . length > 0 && name !== "index" ) { topLevelNav . push ( { title : entry . title , link : entry . link , members : entry . members } ) ; } } ) ; nav . topLevelNav = topLevelNav ; }


Input: Removes absolute paths from JSON output and inject some relevant metadata e . g . language . [CODESPLIT] function ( objects , inch_args ) { var cwd = process . cwd ( ) ; var excluded = config . files ( ) . excluded || [ ] ; var data = { language : 'javascript' , client_name : 'inchjs' , args : inch_args , client_version : "" + inch_config . version , git_repo_url : getGitRepoURL ( ) } ; if ( process . env . TRAVIS ) { data [ 'travis' ] = true ; data [ 'travis_job_id' ] = process . env . TRAVIS_JOB_ID ; data [ 'travis_commit' ] = process . env . TRAVIS_COMMIT ; data [ 'travis_repo_slug' ] = process . env . TRAVIS_REPO_SLUG ; } data [ 'branch_name' ] = getGitBranchName ( ) ; data [ 'objects' ] = objects . filter ( includeObjectFilter ) . map ( function ( item ) { return prepareCodeObject ( item , cwd ) ; } ) . filter ( function ( item ) { return ! excludeObjectIfMatch ( item , excluded ) ; } ) ; return data ; }


Input: An HTTP Agent for proxying requests through Tor using SOCKS5 . [CODESPLIT] function TorAgent ( opts ) { if ( ! ( this instanceof TorAgent ) ) { return new TorAgent ( ) ; } http . Agent . call ( this , opts ) ; this . socksHost = opts . socksHost || 'localhost' ; this . socksPort = opts . socksPort || 9050 ; this . defaultPort = 80 ; // Used when invoking TorAgent.create this . tor = opts . tor ; // Prevent protocol check, wrap destroy this . protocol = null ; this . defaultDestroy = this . destroy ; this . destroy = this . destroyWrapper ; }


Input: ------------------------------------------------------------------ Constructor [CODESPLIT] function ( element , options ) { this . $element = $ ( element ) ; this . options = $ . extend ( true , { } , $ . fn . typeahead . defaults , options ) ; this . $menu = $ ( this . options . menu ) . appendTo ( 'body' ) ; this . shown = false ; // Method overrides     this . eventSupported = this . options . eventSupported || this . eventSupported ; this . grepper = this . options . grepper || this . grepper ; this . highlighter = this . options . highlighter || this . highlighter ; this . lookup = this . options . lookup || this . lookup ; this . matcher = this . options . matcher || this . matcher ; this . render = this . options . render || this . render ; this . select = this . options . select || this . select ; this . sorter = this . options . sorter || this . sorter ; this . source = this . options . source || this . source ; if ( ! this . source . length ) { var ajax = this . options . ajax ; if ( typeof ajax === 'string' ) { this . ajax = $ . extend ( { } , $ . fn . typeahead . defaults . ajax , { url : ajax } ) ; } else { this . ajax = $ . extend ( { } , $ . fn . typeahead . defaults . ajax , ajax ) ; } if ( ! this . ajax . url ) { this . ajax = null ; } } this . listen ( ) ; }


Input: ------------------------------------------------------------------ Handle AJAX source [CODESPLIT] function ( ) { var that = this , query = that . $element . val ( ) ; if ( query === that . query ) { return that ; } // Query changed that . query = query ; // Cancel last timer if set if ( that . ajax . timerId ) { clearTimeout ( that . ajax . timerId ) ; that . ajax . timerId = null ; } if ( ! query || query . length < that . ajax . triggerLength ) { // Cancel the ajax callback if in progress if ( that . ajax . xhr ) { that . ajax . xhr . abort ( ) ; that . ajax . xhr = null ; that . ajaxToggleLoadClass ( false ) ; } return that . shown ? that . hide ( ) : that ; } // Query is good to send, set a timer that . ajax . timerId = setTimeout ( function ( ) { $ . proxy ( that . ajaxExecute ( query ) , that ) } , that . ajax . timeout ) ; return that ; }


Input: ------------------------------------------------------------------ Execute an AJAX request [CODESPLIT] function ( query ) { this . ajaxToggleLoadClass ( true ) ; // Cancel last call if already in progress if ( this . ajax . xhr ) this . ajax . xhr . abort ( ) ; var params = this . ajax . preDispatch ? this . ajax . preDispatch ( query ) : { query : query } ; var jAjax = ( this . ajax . method === "post" ) ? $ . post : $ . get ; this . ajax . xhr = jAjax ( this . ajax . url , params , $ . proxy ( this . ajaxLookup , this ) ) ; this . ajax . timerId = null ; }


Input: ------------------------------------------------------------------ Perform a lookup in the AJAX results [CODESPLIT] function ( data ) { var items ; this . ajaxToggleLoadClass ( false ) ; if ( ! this . ajax . xhr ) return ; if ( this . ajax . preProcess ) { data = this . ajax . preProcess ( data ) ; } // Save for selection retreival this . ajax . data = data ; items = this . grepper ( this . ajax . data ) ; if ( ! items || ! items . length ) { return this . shown ? this . hide ( ) : this ; } this . ajax . xhr = null ; return this . render ( items . slice ( 0 , this . options . items ) ) . show ( ) ; }


Input: ------------------------------------------------------------------ Search source [CODESPLIT] function ( event ) { var that = this , items ; if ( that . ajax ) { that . ajaxer ( ) ; } else { that . query = that . $element . val ( ) ; if ( ! that . query ) { return that . shown ? that . hide ( ) : that ; } items = that . grepper ( that . source ) ; if ( ! items || ! items . length ) { return that . shown ? that . hide ( ) : that ; } return that . render ( items . slice ( 0 , that . options . items ) ) . show ( ) ; } }


Input: ------------------------------------------------------------------ Filters relevent results [CODESPLIT] function ( data ) { var that = this , items ; if ( data && data . length && ! data [ 0 ] . hasOwnProperty ( that . options . display ) ) { return null ; } items = $ . grep ( data , function ( item ) { return that . matcher ( item [ that . options . display ] , item ) ; } ) ; return this . sorter ( items ) ; }


Input: ------------------------------------------------------------------ Sorts the results [CODESPLIT] function ( items ) { var that = this , beginswith = [ ] , caseSensitive = [ ] , caseInsensitive = [ ] , item ; while ( item = items . shift ( ) ) { if ( ! item [ that . options . display ] . toLowerCase ( ) . indexOf ( this . query . toLowerCase ( ) ) ) { beginswith . push ( item ) ; } else if ( ~ item [ that . options . display ] . indexOf ( this . query ) ) { caseSensitive . push ( item ) ; } else { caseInsensitive . push ( item ) ; } } return beginswith . concat ( caseSensitive , caseInsensitive ) ; }


Input: ------------------------------------------------------------------ Highlights the match ( es ) within the results [CODESPLIT] function ( item ) { var query = this . query . replace ( / [\-\[\]{}()*+?.,\\\^$|#\s] / g , '\\$&' ) ; return item . replace ( new RegExp ( '(' + query + ')' , 'ig' ) , function ( $1 , match ) { return '<strong>' + match + '</strong>' ; } ) ; }


Input: ------------------------------------------------------------------ Renders the results list [CODESPLIT] function ( items ) { var that = this ; items = $ ( items ) . map ( function ( i , item ) { i = $ ( that . options . item ) . attr ( 'data-value' , item [ that . options . val ] ) ; i . find ( 'a' ) . html ( that . highlighter ( item [ that . options . display ] , item ) ) ; return i [ 0 ] ; } ) ; items . first ( ) . addClass ( 'active' ) ; this . $menu . html ( items ) ; return this ; }


Input: ------------------------------------------------------------------ Selects the next result [CODESPLIT] function ( event ) { var active = this . $menu . find ( '.active' ) . removeClass ( 'active' ) ; var next = active . next ( ) ; if ( ! next . length ) { next = $ ( this . $menu . find ( 'li' ) [ 0 ] ) ; } next . addClass ( 'active' ) ; }


Input: ------------------------------------------------------------------ Handles a key being pressed [CODESPLIT] function ( e ) { e . stopPropagation ( ) ; if ( ! this . shown ) { return ; } switch ( e . keyCode ) { case 9 : // tab case 13 : // enter case 27 : // escape e . preventDefault ( ) ; break ; case 38 : // up arrow e . preventDefault ( ) ; this . prev ( ) ; break ; case 40 : // down arrow e . preventDefault ( ) ; this . next ( ) ; break ; } }


Input: ------------------------------------------------------------------ Handles cursor exiting the textbox [CODESPLIT] function ( e ) { var that = this ; e . stopPropagation ( ) ; e . preventDefault ( ) ; setTimeout ( function ( ) { if ( ! that . $menu . is ( ':focus' ) ) { that . hide ( ) ; } } , 150 ) }


Input: Runs a local version of Inch . [CODESPLIT] function run ( inch_args , options ) { var callback = function ( filename ) { LocalInch . run ( inch_args || [ 'suggest' ] , filename , noop ) ; } if ( options . dry_run ) callback = noop ; retriever . run ( PathExtractor . extractPaths ( inch_args ) , callback ) ; }


Input: train [CODESPLIT] function ( options , callback ) { var data = options . data ; var target = options . target ; var features = options . features ; var featureTypes = options . featureTypes ; featureTypes . forEach ( function ( f ) { if ( [ 'number' , 'category' ] . indexOf ( f ) === - 1 ) { callback ( new Error ( 'Unrecognized feature type' ) ) ; return ; } } ) ; var targets = unique ( data . map ( function ( d ) { return d [ d . length - 1 ] ; } ) ) ; this . features = features ; this . targets = targets ; this . target = target var classify = this . classify . bind ( this ) var model = { features : this . features , targets : this . targets , // model is the generated tree structure model : this . _c45 ( data , target , features , featureTypes , 0 ) , classify : function ( sample ) { return classify ( this . model , sample ) } , toJSON : function ( ) { return JSON . stringify ( this . model ) } } ; this . model = model . model callback ( null , model ) ; }


Input: shutdown puts it into power saving sleep mode . call with false to wake it up . [CODESPLIT] function shutdown ( addr , b ) { if ( addr < 0 || addr >= maxDevices ) throw 'address out of range' ; if ( b ) spiTransfer ( addr , OP_SHUTDOWN , 0 ) ; else spiTransfer ( addr , OP_SHUTDOWN , 1 ) ; }


Input: sets the number of pixels per row pretty much always 8 for most devices . [CODESPLIT] function setScanLimit ( addr , limit ) { if ( addr < 0 || addr >= maxDevices ) return ; //console.log("OP_SCANLIMIT"); if ( limit >= 0 && limit < 8 ) spiTransfer ( addr , OP_SCANLIMIT , limit ) ; }


Input: sets the brightness of the LEDs 0 to 15 [CODESPLIT] function setBrightness ( addr , intensity ) { if ( addr < 0 || addr >= maxDevices ) return ; if ( typeof intensity == 'undefined' ) return ; intensity = constrain ( intensity , 0 , 15 ) ; spiTransfer ( addr , OP_INTENSITY , intensity ) ; }


Input: clears the entire display [CODESPLIT] function clearDisplay ( addr ) { if ( addr < 0 || addr >= maxDevices ) throw 'address out of range' ; var offset ; offset = addr * 8 ; for ( var i = 0 ; i < 8 ; i ++ ) { status [ offset + i ] = 0 ; spiTransfer ( addr , i + 1 , status [ offset + i ] ) ; } }


Input: / * Display a hexadecimal digit on a 7 - Segment Display Params : addr address of the display digit the position of the digit on the display ( 0 .. 7 ) value the value to be displayed . ( 0x00 .. 0x0F ) dp sets the decimal point . [CODESPLIT] function setDigit ( addr , digit , value , dp ) { if ( addr < 0 || addr >= maxDevices ) throw 'address out of range' ; if ( digit < 0 || digit > 7 ) throw 'invalid digit number' ; if ( value < 0 || value > 15 ) throw 'number out of range' ; var offset = addr * 8 ; var v = charTable [ value ] ; //.toString(16)];  if ( dp ) v |= 0x80 ; // set the decimal point bit if necessary status [ offset + digit ] = v ; spiTransfer ( addr , digit + 1 , v ) ; }


Input: pos is passed in as 0 to 7 0 on the left 7 on the right [CODESPLIT] function showNumber ( addr , num , decimalplaces , mindigits , leftjustified , pos , dontclear ) { if ( addr < 0 || addr >= maxDevices ) throw 'address out of range' ; num = formatNumber ( num , decimalplaces , mindigits ) ; // internally, pos is 0 on the right, so we set defaults, and convert if ( typeof pos === 'undefined' ) { if ( leftjustified ) { pos = 7 ; } else { pos = 0 ; } } else pos = 7 - pos ; // get rid of the decimal place but remember where it was var decimalplace ; if ( num . indexOf ( '.' ) < 0 ) decimalplace = - 1 ; else { decimalplace = num . length - num . indexOf ( '.' ) - 1 ; num = num . split ( '.' ) . join ( '' ) ; } if ( leftjustified ) { pos -= ( num . length - 1 ) ; } for ( var i = 0 ; i < 8 ; i ++ ) { var offset = i + pos ; var char = num . charAt ( num . length - 1 - i ) ; if ( ( offset < 8 && offset >= 0 ) && ( ! dontclear || char != '' ) ) { if ( char == '-' ) setChar ( addr , offset , char , i > 0 && i == decimalplace ) ; else setDigit ( addr , offset , parseInt ( char ) , i > 0 && i == decimalplace ) ; } } }


Input: / * [CODESPLIT] function setChar ( addr , digit , char , dp ) { if ( addr < 0 || addr >= maxDevices ) throw 'address out of range' ; if ( digit < 0 || digit > 7 ) throw 'invalid digit number' ; var offset = addr * 8 ; var v = charTable [ char ] || charTable [ char . toLowerCase ( ) ] ; //.toString(16)];  if ( dp ) v |= 0x80 ; // set the decimal point bit if necessary status [ offset + digit ] = v ; spiTransfer ( addr , digit + 1 , v ) ; }