Input: Implementation of inherited event . [CODESPLIT] function wrapperEvents ( srcFunc , objFunc , ... args ) { const event = ( args [ 0 ] instanceof Event ) && args [ 0 ] ; const isStopped = event ? ( ) => event . immediatePropagationStopped : stubFalse ; if ( ! isStopped ( ) && isFunction ( objFunc ) ) { objFunc . apply ( this , args ) ; } if ( ! isStopped ( ) && isFunction ( srcFunc ) ) { srcFunc . apply ( this , args ) ; } }


Input: The assignment of parameters accessors . [CODESPLIT] function accessorsIterator ( options , name , accessors ) { const optionsSetter = get ( options , 'set' ) ; const updateSetter = wrap ( name , wrapperAccessorsSetUpdate ) ; accessors [ name ] = merge ( { } , options , { set : wrap ( optionsSetter , wrap ( updateSetter , wrapperFunction ) ) } ) ; }


Input: Update element when a property is changed . [CODESPLIT] function wrapperAccessorsSetUpdate ( accessorName , nextValue , prevValue ) { if ( nextValue !== prevValue && this . xprops . hasOwnProperty ( accessorName ) && this . mounted ) { this [ Constants . BLOCK ] . update ( ) ; } }


Input: The callback of the remote in DOM . [CODESPLIT] function lifecycleRemoved ( ) { this [ Constants . INSERTED ] = false ; const block = this [ Constants . BLOCK ] ; if ( block ) { block . destroy ( ) ; this [ Constants . BLOCK ] = undefined ; } }


Input:
The callback of the insert in DOM . [CODESPLIT] function lifecycleInserted ( ) { if ( this [ Constants . INSERTED ] ) { return ; } blockInit ( this ) ; this [ Constants . INSERTED ] = true ; const isScriptContent = Boolean ( this . querySelector ( 'script' ) ) ; // asynchronous read content // <xb-test>
not found
</xb-test> if ( isScriptContent ) { lazy ( blockCreateLazy , this ) ; } else { blockCreate ( this ) ; } }


Input: Returns copy of obj without removeProp field . [CODESPLIT] function ( obj , removeProp ) { var newObj = { } ; for ( var prop in obj ) { if ( ! obj . hasOwnProperty ( prop ) || prop === removeProp ) { continue ; } newObj [ prop ] = obj [ prop ] ; } return newObj ; }


Input: Reads thee content of a remote file . Invokes ** cat filepath ** and returns the result of the command execution as provided by the ** sshExec . command ** function . [CODESPLIT] function readFileContent ( conn , filepath ) { var validateInputArg = function ( ) { if ( filepath === null || filepath . length === 0 ) { throw { "success" : false , "value" : null , "error" : new Error ( "a filepath value is required" ) } ; } else { return true ; } } ; var readRemoteFileContent = function ( ) { // the success handler var successHandler = function ( result ) { return result ; } ; // the error handler var errorHandler = function ( err ) { throw err ; } ; return sshExec . command ( conn , 'cat ' + filepath ) . then ( successHandler , errorHandler ) ; } ; // main entry point return Q . fcall ( validateInputArg ) . then ( readRemoteFileContent ) ; }


Input: - retry { number } - 0 : no retries default - > 0 : max retry times - - 1 : no limit - retry_timeout : { number } default to 100 ms [CODESPLIT] function Client ( options ) { var self = this ; options = options || { } ; this . mid = 0 ; this . callbacks = { } ; this . socket = new net . Socket ( options ) ; replier . _migrate_events ( [ 'connect' , 'error' , 'end' , 'timeout' , 'close' , 'drain' ] , this . socket , this ) ; this . socket . on ( 'data' , function ( data ) { dealStream ( data , function ( msg ) { self . emit ( 'data' , msg ) ; self . _dealServerData ( msg ) ; } ) ; } ) ; }


Input: Transforms a HTML5 data - * attributes hash to a hash of Javascript properties . [CODESPLIT] function dataAttributesToProperties ( dataAttributesHash ) { var transformed = { } ; $ . each ( dataAttributesHash , function ( key , value ) { // Drop the "data-" prefix, then convert to camelCase key = toCamelCase ( key . replace ( / ^data- / , "" ) ) ; try { value = $ . parseJSON ( value ) ; } catch ( err ) { } transformed [ key ] = value ; } ) ; return transformed ; }


Input: Transforms a hash of Javascript properties into a HTML5 data - * attributes hash . Is the inverse function of dataAttributesToProperties () . [CODESPLIT] function propertiesToDataAttributes ( attributesHash ) { var transformed = { } ; $ . each ( attributesHash , function ( key , value ) { // Convert camelCase to dashed notation, then add the "data-" prefix key = "data-" + toDashed ( key ) ; if ( $ . isPlainObject ( value ) ) value = JSON . stringify ( value ) ; transformed [ key ] = value ; } ) ; return transformed ; }


Input: Transforms a hash of HTML attributes - e . g . data attributes - into a string . [CODESPLIT] function attributesHashToString ( attributesHash , options ) { var reduce = options && options . reverse ? _ . reduceRight : _ . reduce , separator = options && options . multiline ? "\n" : " " , spacing = options && options . extrSpace || "" , defaultQuote = options && options . preferSingleQuotes ? "'" : '"' ; return reduce ( attributesHash , function ( attrString , value , key ) { var quote = value . indexOf ( '"' ) !== - 1 ? "'" : value . indexOf ( "'" ) !== - 1 ? '"' : defaultQuote ; return attrString + key + spacing + "=" + spacing + quote + value + quote + separator ; } , "" ) ; }


Input: Returns a transformed hash in which all camelCased property names have been replaced by dashed property names . The input hash remains untouched . [CODESPLIT] function toDashedProperties ( hash ) { var transformed = { } ; _ . each ( hash , function ( value , key ) { transformed [ toDashed ( key ) ] = value ; } ) ; return transformed ; }


Input: Returns a transformed hash in which all dashed property names have been replaced by camelCased property names . The input hash remains untouched . [CODESPLIT] function toCamelCasedProperties ( hash ) { var transformed = { } ; _ . each ( hash , function ( value , key ) { transformed [ toCamelCase ( key ) ] = value ; } ) ; return transformed ; }


Input: Returns an array of dashed key names which are the alternative names for all camel - cased key names in a hash . [CODESPLIT] function dashedKeyAlternatives ( hash ) { var keys = _ . keys ( toDashedProperties ( hash ) ) ; return _ . filter ( keys , function ( key ) { return key . search ( / [^-]-[a-z] / ) !== - 1 ; } ) ; }


Input: Combines various hashes with a shallow _ . extend () . Doesn t modify the input hashes . [CODESPLIT] function combine ( hashA , hashB , hashN ) { var hashes = _ . toArray ( arguments ) ; return _ . extend . apply ( undefined , [ { } ] . concat ( hashes ) ) ; }


Input: Returns an array of matched Components from within the passed root object . [CODESPLIT] function ( selector , root ) { var selectors = selector . split ( ',' ) , length = selectors . length , i = 0 , results = [ ] , noDupResults = [ ] , dupMatcher = { } , query , resultsLn , cmp ; for ( ; i < length ; i ++ ) { selector = Ext . String . trim ( selectors [ i ] ) ; query = this . parse ( selector ) ; //                query = this.cache[selector]; //                if (!query) { //                    this.cache[selector] = query = this.parse(selector); //                } results = results . concat ( query . execute ( root ) ) ; } // multiple selectors, potential to find duplicates // lets filter them out. if ( length > 1 ) { resultsLn = results . length ; for ( i = 0 ; i < resultsLn ; i ++ ) { cmp = results [ i ] ; if ( ! dupMatcher [ cmp . id ] ) { noDupResults . push ( cmp ) ; dupMatcher [ cmp . id ] = true ; } } results = noDupResults ; } return results ; }


Input: Tests whether the passed Component matches the selector string . [CODESPLIT] function ( component , selector ) { if ( ! selector ) { return true ; } var query = this . cache [ selector ] ; if ( ! query ) { this . cache [ selector ] = query = this . parse ( selector ) ; } return query . is ( component ) ; }


Input: 计算 md5 [CODESPLIT] function md5 ( buffer ) { var hash = crypto . createHash ( 'md5' ) ; return hash . update ( buffer ) . digest ( 'hex' ) . slice ( 0 , 10 ) ; }


Input: 清掉 url 的 query 后缀 [CODESPLIT] function cleanQuery ( url ) { var query = path . extname ( url ) . split ( '?' ) [ 1 ] ; if ( query && query . length > 0 ) { return url . substr ( 0 , url . length - ( query . length + 1 ) ) ; } return url ; }


Input: 创建一个正则表达式 [CODESPLIT] function createPattern ( pattern , flags ) { pattern = pattern . replace ( / [\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|] / g , "\\$&" ) ; return flags ? new RegExp ( pattern , flags ) : new RegExp ( pattern ) ; }


Input: 正则全局提取依赖 [CODESPLIT] function walkDependencies ( file , rules ) { var directory = path . dirname ( file . path ) ; var content = file . contents . toString ( ) ; var list = [ ] ; // 这里不用判断是否已添加 // 比如同一个文件出现下面两句 // // require( //     [ 'common/a' ] // ); // // require( //     [ 'common/a', 'common/b' ] // ); // // common/a 无需判断是否存在，因为它出现在不同的匹配块中 // var addDependency = function ( dependency ) { list . push ( dependency ) ; } ; rules . forEach ( function ( parser , index ) { var results = content . match ( parser . pattern ) ; if ( results ) { results . forEach ( function ( result ) { var dependencies = parser . match ( result , file ) ; if ( ! dependencies ) { return ; } if ( ! Array . isArray ( dependencies ) ) { dependencies = [ dependencies ] ; } dependencies . forEach ( function ( dependency ) { // 支持返回对象，必须包含 raw 属性 if ( typeof dependency === 'string' ) { dependency = { raw : dependency } ; } var raw = dependency . raw ; var absolute = dependency . absolute ; if ( ! absolute ) { absolute = / ^(?:\w|\.(?:\.)?) / . test ( raw ) ? path . join ( directory , raw ) : raw ; } var extname = dependency . extname ; if ( extname && extname . length > 1 ) { var terms = absolute . split ( '.' ) ; terms . pop ( ) ; terms . push ( extname . substr ( 1 ) ) ; absolute = terms . join ( '.' ) ; } dependency . raw = cleanQuery ( raw ) ; dependency . absolute = cleanQuery ( absolute ) ; // 便于替换回去 dependency . match = result ; addDependency ( dependency ) ; } ) ; } ) ; } } ) ; return list ; }


Input: 依赖去重 [CODESPLIT] function uniqueDependencies ( dependencies ) { var result = [ ] ; var map = { } ; dependencies . forEach ( function ( dependency ) { if ( ! map [ dependency . absolute ] ) { result . push ( dependency ) ; map [ dependency . absolute ] = 1 ; } } ) ; return result ; }


Input: 纠正依赖的格式 [CODESPLIT] function correctDependencies ( file , dependencies , correct ) { if ( ! correct ) { return ; } for ( var i = dependencies . length - 1 ; i >= 0 ; i -- ) { correct ( file , dependencies [ i ] ) ; } }


Input: 过滤一些不需要的依赖，通常在 correctDependencies 之后处理 [CODESPLIT] function filterDependencies ( file , dependencies , filter ) { for ( var i = dependencies . length - 1 ; i >= 0 ; i -- ) { var dependency = dependencies [ i ] ; // 绝对路径不用处理 if ( isAbsolute ( dependency . raw ) || ( filter && filter ( file , dependency ) ) ) { dependencies . splice ( i , 1 ) ; } } }


Input: 替换依赖 [CODESPLIT] function renameDependencies ( file , dependencies , rename ) { var srcContent = file . contents . toString ( ) ; var destContent = srcContent ; // 按 match 分组 var group = { } ; dependencies . forEach ( function ( dependency ) { var list = group [ dependency . match ] ; if ( ! list ) { list = group [ dependency . match ] = [ ] ; } list . push ( dependency ) ; } ) ; util . each ( group , function ( dependencies , match ) { destContent = replaceByPattern ( destContent , match , function ( result ) { dependencies . forEach ( function ( dependency ) { var replacement = rename ( dependency ) ; if ( replacement ) { result = replaceByPattern ( result , dependency . raw , replacement ) ; } } ) ; return result ; } ) ; } ) ; if ( srcContent !== destContent ) { file . contents = new Buffer ( destContent ) ; } }


Input: 获取递归计算的 md5 [CODESPLIT] function getRecursiveHash ( dependency , hashMap , dependencyMap ) { // 递归分析出的完整的依赖列表 var dependencies = [ ] ; var map = { } ; var addDependency = function ( dependency ) { // 要避免循环依赖 if ( ! map [ dependency ] ) { map [ dependency ] = 1 ; dependencies . push ( dependency ) ; var childDependencies = dependencyMap [ dependency ] ; if ( Array . isArray ( childDependencies ) ) { childDependencies . forEach ( addDependency ) ; } } } ; addDependency ( dependency ) ; // 按字母表顺序排序，确保每次顺序一致 dependencies . sort ( function ( a , b ) { if ( a > b ) { return 1 ; } else if ( a < b ) { return - 1 ; } else { return 0 ; } } ) ; var list = [ ] ; dependencies . forEach ( function ( dependency ) { var hash = hashMap [ dependency ] ; if ( hash ) { list . push ( hash ) ; } } ) ; var hash ; switch ( list . length ) { case 0 : hash = '' ; break ; case 1 : hash = list [ 0 ] ; break ; default : hash = md5 ( new Buffer ( list . join ( '' ) ) ) ; break ; } return hash ; }


Input: 分析 html 文件依赖 [CODESPLIT] function htmlDependencies ( file , instance , options ) { var dependencies = walkDependencies ( file , instance . htmlRules ) ; correctDependencies ( file , dependencies , instance . correctDependency ) ; filterDependencies ( file , dependencies , instance . filterDependency ) ; if ( options . process ) { options . process ( file , dependencies ) ; } if ( options . rename ) { renameDependencies ( file , dependencies , function ( dependency ) { return options . rename ( file , dependency , instance . hashMap , instance . dependencyMap ) ; } ) ; } }


Input: 分析 css 文件依赖 [CODESPLIT] function cssDependencies ( file , instance , options ) { var dependencies = walkDependencies ( file , instance . cssRules ) ; correctDependencies ( file , dependencies , instance . correctDependency ) ; filterDependencies ( file , dependencies , instance . filterDependency ) ; if ( options . process ) { options . process ( file , dependencies ) ; } if ( options . rename ) { renameDependencies ( file , dependencies , function ( dependency ) { return options . rename ( file , dependency , instance . hashMap , instance . dependencyMap ) ; } ) ; } }


Input: 分析 amd 文件依赖 [CODESPLIT] function amdDependencies ( file , instance , options ) { var dependencies = [ ] ; var config = instance . getAmdConfig ( file ) ; var fileInfo = parseFile ( file . path , file . contents . toString ( ) , config ) ; fileInfo . modules . forEach ( function ( module ) { var resources = parseFactoryResources ( module . factory ) ; [ // 同步 module . dependencies , // 异步 resources . async , // 其他资源，如 toUrl('../../a.png') resources . other ] . forEach ( function ( resources ) { resources . forEach ( function ( resource ) { if ( util . keywords [ resource . id ] ) { return ; } var resourceId = resolveResourceId ( resource . id , module . id ) ; var filePath = resourceIdToFilePath ( resourceId , config ) ; if ( filePath ) { dependencies . push ( { raw : resource . id , absolute : filePath } ) ; } } ) ; } ) ; } ) ; correctDependencies ( file , dependencies , instance . correctDependency ) ; filterDependencies ( file , dependencies , instance . filterDependency ) ; if ( options . process ) { options . process ( file , dependencies ) ; } if ( options . rename ) { var replaceRequireResource = config . replaceRequireResource ; config . replaceRequireResource = function ( resource , absolute ) { return options . rename ( file , { raw : resource . id , absolute : absolute } , instance . hashMap , instance . dependencyMap ) ; } ; replaceResources ( fileInfo , config ) ; config . replaceRequireResource = replaceRequireResource ; file . contents = new Buffer ( generateFileCode ( fileInfo , config . minify ) ) ; } }


Input: 获取文件对应的遍历器 [CODESPLIT] function getIterator ( file ) { var iterator ; switch ( path . extname ( file . path ) . toLowerCase ( ) ) { // 其实用 .html 和 .tpl 就行了 // 非要用太奇葩的扩展名，就自己蛋疼去吧 case '.html' : case '.tpl' : case '.hbs' : case '.ejs' : case '.volt' : case '.twig' : case '.phtml' : iterator = htmlDependencies ; break ; case '.css' : case '.less' : case '.styl' : case '.sass' : iterator = cssDependencies ; break ; case '.js' : iterator = amdDependencies ; break ; } return iterator ; }


Input: 自定义处理 [CODESPLIT] function ( handler ) { var me = this ; return es . map ( function ( file , callback ) { var done = function ( ) { callback ( null , file ) ; } ; if ( file . contents ) { handler ( file , done ) ; } else { done ( ) ; } } ) ; }


Input: 获取 html 文件的依赖 [CODESPLIT] function ( options ) { var me = this ; return me . custom ( function ( file , callback ) { htmlDependencies ( file , me , options ) ; callback ( ) ; } ) ; }


Input: 获取 css 文件的依赖 [CODESPLIT] function ( options ) { var me = this ; return me . custom ( function ( file , callback ) { cssDependencies ( file , me , options ) ; callback ( ) ; } ) ; }


Input: 获取 amd 文件的依赖 [CODESPLIT] function ( options ) { var me = this ; return me . custom ( function ( file , callback ) { amdDependencies ( file , me , options ) ; callback ( ) ; } ) ; }


Input: 分析文件的 hash [CODESPLIT] function ( options ) { var me = this ; var filter = options && options . filter ; return me . custom ( function ( file , callback ) { if ( ! filter || ! filter ( file ) ) { var filePath = file . path ; var hash = me . hashMap [ filePath ] ; hash = md5 ( file . contents ) ; me . hashMap [ filePath ] = hash ; } callback ( ) ; } ) ; }


Input: 分析文件的依赖 [CODESPLIT] function ( options ) { var me = this ; var filter = options && options . filter ; return me . custom ( function ( file , callback ) { if ( ! filter || ! filter ( file ) ) { var iterator = getIterator ( file ) ; if ( iterator ) { iterator ( file , me , { process : function ( file , dependencies ) { if ( dependencies . length > 0 ) { me . dependencyMap [ file . path ] = uniqueDependencies ( dependencies ) . map ( function ( dependency ) { return dependency . absolute ; } ) ; } } } ) ; } } callback ( ) ; } ) ; }


Input: 替换依赖 [CODESPLIT] function ( options ) { var me = this ; var hashMap = me . hashMap ; var dependencyMap = me . dependencyMap ; var filter ; var replace ; if ( options ) { filter = options . filter ; replace = options . replace ; } return me . custom ( function ( file , callback ) { if ( ! filter || ! filter ( file ) ) { var iterator = getIterator ( file ) ; if ( iterator ) { iterator ( file , me , { process : function ( file , dependencies ) { if ( replace ) { var srcContent = file . contents . toString ( ) ; var destContent = replace ( file , srcContent ) ; if ( destContent && destContent !== srcContent ) { file . contents = new Buffer ( destContent ) ; } } } , rename : function ( file , dependency ) { var prefix = './' ; // "./a.js" 重命名为 "./a_123.js" // 但是 path.join('.', 'a.js') 会变成 a.js if ( dependency . raw . indexOf ( prefix ) !== 0 ) { prefix = '' ; } var dependencyPath = me . renameDependency ( file , me . getFileHash ( file . path , hashMap , dependencyMap , true ) , dependency , me . getFileHash ( dependency . absolute , hashMap , dependencyMap , true ) ) ; if ( prefix && dependencyPath . indexOf ( prefix ) !== 0 ) { dependencyPath = prefix + dependencyPath ; } return dependencyPath ; } } ) ; } } callback ( ) ; } ) ; }


Input: 生成文件名带有哈希值的文件 [CODESPLIT] function ( options ) { var me = this ; var filter = options && options . filter ; var hashMap = me . hashMap ; var dependencyMap = me . dependencyMap ; return me . custom ( function ( file , callback ) { if ( ! filter || ! filter ( file ) ) { var hash = me . getFileHash ( file . path , hashMap , dependencyMap , true ) ; var filePath = me . renameFile ( file , hash ) ; if ( filePath ) { file . path = filePath ; } } callback ( ) ; } ) ; }


Input: 获得文件的哈希（递归哈希） [CODESPLIT] function ( filePath , hashMap , dependencyMap , cache ) { var me = this ; var recursiveHashMap = me . recursiveHashMap ; var hash = recursiveHashMap [ filePath ] ; if ( ! cache || ! hash ) { hash = getRecursiveHash ( filePath , hashMap , dependencyMap ) ; } if ( cache ) { recursiveHashMap [ filePath ] = hash ; } return hash ; }


Input: 编译 amd 模块 [CODESPLIT] function ( ) { var me = this ; return me . custom ( function ( file , callback ) { amdDeploy ( { file : file . path , content : file . contents . toString ( ) , config : me . getAmdConfig ( file ) , callback : function ( code ) { file . contents = new Buffer ( code ) ; callback ( ) ; } } ) ; } ) ; }


Input: 解析 amd 依赖 [CODESPLIT] function ( file , match , literal ) { // literal 可能是 'moduleId'、'[ "module1", "module2" ]'、xxx（非法 js 变量） literal = literal . trim ( ) ; var resources ; try { var factory = new Function ( 'return ' + literal ) ; resources = factory ( ) ; } catch ( e ) { console . log ( '[INFO][amd id parse error]' ) ; console . log ( match ) ; console . log ( '' ) ; resources = literal ; } if ( ! resources ) { return ; } if ( ! Array . isArray ( resources ) ) { resources = [ resources ] ; } var me = this ; var config = me . getAmdConfig ( file ) ; var result = [ ] ; resources . forEach ( function ( resourceId ) { var filePath = resourceIdToFilePath ( resourceId , config ) ; if ( filePath ) { result . push ( { amd : true , raw : resourceId , absolute : filePath } ) ; } } ) ; return result ; }


Input: The plugin [CODESPLIT] function plugin ( suite ) { // Default parsers var parsers = util . loadAll ( true , __dirname , 'parsers' ) ; // Add the plugin's `root` suite . addRoot ( path . join ( __dirname , 'defaults' ) ) ; // Initialize Yadda require for Mocha Yadda . plugins . mocha . StepLevelPlugin . init ( { container : this . global } ) ; // Register parsers parsers . forEach ( function ( data ) { suite . constructor . addParser ( data ) ; } ) ; // Listen for a new Session creation suite . on ( 'create session' , function ( session ) { // Create a store for this plugin var plugin = session . plugin ( pkg . name , new Store ( ) ) ; session . on ( 'pre run' , function ( ) { var libraries = Object . keys ( plugin . libraries ) . map ( function ( name ) { return plugin . libraries [ name ] ; } ) ; plugin . parser = Yadda . createInstance ( libraries ) ; } ) ; // session.on('parse file', function (file) { //   console.log('eeeeeeeeeee', file) //   parseFile(session, file); // //   // PARSE FILES HERE, instead of Session.prototype.parseFiles // }); } ) ; return { // Register the plugin's name name : pkg . name } ; }


Input: POST // FUNCTION : post ( [ data ] opts clbk ) Sends a POST request to a Travis CI API endpoint . [CODESPLIT] function post ( data , opts , clbk ) { if ( arguments . length === 2 ) { // Assume `data` is `opts` and `opts` is `clbk`... return factory ( data , opts ) ( ) ; } factory ( opts , clbk ) ( data ) ; }


Input:
Returns a decorated router that wraps node selection [CODESPLIT] function RouterDecorator ( Router ) { function TelemetryRouter ( options ) { if ( ! ( this instanceof TelemetryRouter ) ) { return new TelemetryRouter ( options ) } Router . call ( this , options ) } inherits ( TelemetryRouter , Router ) /**
   * Wraps getNearestContacts with telemetry
   * #getNearestContacts
   * @returns {Array} shortlist
   */ TelemetryRouter . prototype . getNearestContacts = function ( key , limit , id , cb ) { var self = this var callback = function ( err , shortlist ) { if ( ! err ) { self . _log . debug ( 'sorting shortlist based on telemetry score' ) var profiles = { } each ( shortlist , function ( contact , iteratorCallback ) { var profileCallback = function ( err , profile ) { profiles [ contact . nodeID ] = profile iteratorCallback ( err ) } self . _rpc . telemetry . getProfile ( contact , profileCallback ) } , function ( err ) { if ( err ) { cb ( null , shortlist ) } else { shortlist . sort ( self . _compare . bind ( self , profiles ) ) cb ( null , shortlist ) } } ) } else { cb ( err , null ) } } Router . prototype . getNearestContacts . call ( this , key , limit , id , callback ) } /**
   * Uses the transport telemetry to compare two nodes
   * #_compare
   * @param {kad.Contact} contactA
   * @param {kad.Contact} contactB
   * @returns {Number}
   */ TelemetryRouter . prototype . _compare = function ( profiles , cA , cB ) { var profileA = profiles [ cA . nodeID ] var profileB = profiles [ cB . nodeID ] var scoresA = { } var scoresB = { } this . _rpc . _telopts . metrics . forEach ( function ( Metric ) { var m = new Metric ( ) scoresA [ m . key ] = Metric . score ( m . getMetric ( profileA ) ) scoresB [ m . key ] = Metric . score ( m . getMetric ( profileB ) ) } ) var resultA = TelemetryRouter . getSuccessProbability ( scoresA ) var resultB = TelemetryRouter . getSuccessProbability ( scoresB ) this . _log . debug ( 'success probability is %d% vs %d%' , ( resultA * 100 ) . toFixed ( 3 ) , ( resultB * 100 ) . toFixed ( 3 ) ) // results are close to each other, break tie with throughput score if ( Math . abs ( resultB - resultA ) <= 0.005 ) { this . _log . debug ( 'score difference is within threshold, selecting based on throughput' ) return scoresB . throughput - scoresA . throughput } return resultB - resultA } /**
   * Uses a profile scorecard to calculate the probability of success
   * #getSuccessProbability
   * @param {Object} score
   * @returns {Number}
   */ TelemetryRouter . getSuccessProbability = function ( score ) { return ( score . reliability + score . availability + score . latency ) / 3 } return TelemetryRouter }


Input:
PARTIAL // FUNCTION : partial ( a b c ) Partially applies lower limit a and upper limit b and mode c and returns a function for evaluating the quantile function for a triangular distribution . [CODESPLIT] function partial ( a , b , c ) { var pInflection = ( c - a ) / ( b - a ) , fact1 = ( b - a ) * ( c - a ) , fact2 = ( b - a ) * ( b - c ) ; /**
	* FUNCTION: quantile( p )
	*	Evaluates the quantile function for a triangular distribution.
	*
	* @private
	* @param {Number} p - input value
	* @returns {Number} evaluated quantile function
	*/ return function quantile ( p ) { if ( p !== p || p < 0 || p > 1 ) { return NaN ; } if ( p < pInflection ) { return a + sqrt ( fact1 * p ) ; } if ( p > pInflection ) { return b - sqrt ( fact2 * ( 1 - p ) ) ; } // Case: p = pInflection return c ; } ; }


Input: Returns a { @link Ext . device . sqlite . Database } instance . If the database with specified name does not exist it will be created . If the creationCallback is provided the database is created with the empty string as its version regardless of the specified version . [CODESPLIT] function ( config ) { if ( config . name == null ) { Ext . Logger . error ( 'Ext.device.SQLite#openDatabase: You must specify a `name` of the database.' ) ; return null ; } if ( config . version == null ) { Ext . Logger . error ( 'Ext.device.SQLite#openDatabase: You must specify a `version` of the database.' ) ; return null ; } if ( config . displayName == null ) { Ext . Logger . error ( 'Ext.device.SQLite#openDatabase: You must specify a `displayName` of the database.' ) ; return null ; } if ( config . estimatedSize == null ) { Ext . Logger . error ( 'Ext.device.SQLite#openDatabase: You must specify a `estimatedSize` of the database.' ) ; return null ; } var database = null ; var result = Ext . device . Communicator . send ( { command : 'SQLite#openDatabase' , sync : true , name : config . name , version : config . version , displayName : config . displayName , estimatedSize : config . estimatedSize , callbacks : { // `creationCallback != null` is checked for internal logic in native plugin code creationCallback : ! config . creationCallback ? null : function ( ) { config . creationCallback . call ( config . scope || this , database ) ; } } , scope : config . scope || this } ) ; if ( result ) { if ( result . error ) { Ext . Logger . error ( result . error ) ; return null ; } database = Ext . create ( 'Ext.device.sqlite.Database' , result . id , result . version ) ; return database ; } return null ; }


Input: Verifies and changes the version of the database at the same time as doing a schema update with a { @link Ext . device . sqlite . SQLTransaction } instance . [CODESPLIT] function ( config ) { if ( config . oldVersion == null ) { Ext . Logger . error ( 'Ext.device.SQLite#changeVersion: You must specify an `oldVersion` of the database.' ) ; return null ; } if ( config . newVersion == null ) { Ext . Logger . error ( 'Ext.device.SQLite#changeVersion: You must specify a `newVersion` of the database.' ) ; return null ; } this . transaction ( Ext . apply ( config , { preflight : function ( ) { return config . oldVersion == this . getVersion ( ) ? null : 'Unable to change version: version mismatch' ; } , postflight : function ( ) { var result = Ext . device . Communicator . send ( { command : 'SQLite#setVersion' , sync : true , databaseId : this . id , version : config . newVersion } ) ; if ( result ) { this . version = config . newVersion ; } } } ) ) ; }


Input: Executes an SQL statement . [CODESPLIT] function ( config ) { if ( ! this . active ) { Ext . Logger . error ( 'Ext.device.sqlite.SQLTransaction#executeSql: An attempt was made to use a SQLTransaction that is no longer usable.' ) ; return null ; } if ( config . sqlStatement == null ) { Ext . Logger . error ( 'Ext.device.sqlite.SQLTransaction#executeSql: You must specify a `sqlStatement` for the transaction.' ) ; return null ; } this . statements . push ( { sqlStatement : config . sqlStatement , arguments : config . arguments , callback : config . callback , failure : config . failure , scope : config . scope } ) ; }


Input: Returns a row at specified index returned by the SQL statement . If there is no such row returns null . [CODESPLIT] function ( index ) { if ( index < this . getLength ( ) ) { var item = { } ; var row = this . rows [ index ] ; this . names . forEach ( function ( name , index ) { item [ name ] = row [ index ] ; } ) ; return item ; } return null ; }


Input:
@class Logger instance with a name [CODESPLIT] function Logger ( name , options ) { this . name = name ; this . _enabled = _defaults ( options , 'enabled' ) ; this . _stream = _defaults ( options , 'stream' ) ; this . _level = _defaults ( options , 'level' ) ; var logger = this ; _loggers [ name ] = this ; /**
   * Create the logger method for each level. Set it up in the constructor
   * to properly lock in the context.
   */ Object . keys ( levels ) . forEach ( function ( level ) { logger [ level ] = function ( ) { return logger . write ( levels [ level ] , arguments ) ; } ; } ) ; }


Input: Function that create a JSON structure to be logged [CODESPLIT] function createPayload ( name , level , data ) { return { date : getDate ( ) , level : level , name : name , data : data } ; }


Input: Represents a [ JSON - RPC 2 . 0 ] ( http : // www . jsonrpc . org / specification ) request or response ; used by { @link RPC#send } . [CODESPLIT] function Message ( spec ) { if ( ! ( this instanceof Message ) ) { return new Message ( spec ) } this . jsonrpc = '2.0' if ( Message . isRequest ( spec ) ) { this . id = spec . id || Message . createID ( ) this . method = spec . method this . params = spec . params } else if ( Message . isResponse ( spec ) ) { this . id = spec . id this . result = merge ( { } , spec . result ) if ( spec . error ) { this . error = { code : - 32603 , message : spec . error . message } } } else { throw new Error ( 'Invalid message specification' ) } }


Input: Takes the arguments of a function ensures that the type provided is the type being bassed . [CODESPLIT] function __ENFORCETYPE ( a , ... types ) { if ( env . application_env !== "development" ) return ; let hasError = false ; let expecting ; let got ; let i = 0 ; types . map ( ( t , index ) => { if ( a [ index ] === null ) { hasError = true ; expecting = t ; got = "null" ; i = index ; return ; } switch ( t ) { case "mixed" : break ; case "jsx" : if ( ! React . isValidElement ( a [ index ] ) ) { hasError = true ; expecting = "jsx" ; got = typeof a [ index ] ; i = index ; } case "array" : if ( ! Array . isArray ( a [ index ] ) ) { hasError = true ; expecting = "array" ; got = typeof a [ index ] ; i = index ; } break ; case "object" : if ( typeof a [ index ] !== 'object' || Array . isArray ( a [ index ] ) || a [ index ] === null ) { hasError = true ; expecting = "object" ; i = index ; if ( a [ index ] === null ) { got = 'null' ; } else { got = Array . isArray ( a [ index ] ) ? "array" : typeof a [ index ] ; } } default : if ( typeof a [ index ] !== t ) { hasError = true ; { expecting = t ; got = typeof a [ index ] ; } i = index ; } } } ) ; if ( hasError ) { let err = new Error ( ) ; console . error ( ` ${ i + 1 } ${ expecting } ${ got } ` , err . stack ) ; } }


Input: PRIVATE [CODESPLIT] function parseXMP ( data ) { return new Promise ( function ( resolve , reject ) { var parserstrict = true ; var parser = sax . parser ( parserstrict ) ; var nodepath = [ ] ; var currentnode = null ; var outdata = { } ; parser . onerror = function ( err ) { reject ( { error : MediaExt . ERROR . PARSEXML , internalerror : err } ) } ; parser . onopentag = function ( node ) { nodepath . push ( node . name ) ; if ( node . attributes ) { for ( var att in node . attributes ) { if ( ! node . attributes . hasOwnProperty ( att ) ) continue ; var value = node . attributes [ att ] ; nodepath . push ( att ) ; setOutdata ( nodepath , value , outdata ) ; nodepath . pop ( ) ; } } currentnode = node ; } parser . onclosetag = function ( node ) { nodepath . pop ( ) ; currentnode = null ; } parser . ontext = function ( value ) { setOutdata ( nodepath , value , outdata ) ; } parser . onend = function ( data ) { resolve ( outdata ) } ; parser . write ( data ) . close ( ) ; } ) ; }


Input: Ensure object tree exists as dictated by the key [CODESPLIT] function assign ( parent , val , keyOpts ) { var target = parent , keyParts = keyOpts . val . toString ( ) . split ( '.' ) ; keyParts . forEach ( function ( keyPart , idx ) { if ( keyParts . length === idx + 1 ) { if ( val !== undefined ) { if ( Array . isArray ( val ) && Array . isArray ( target [ keyPart ] ) ) { val = target [ keyPart ] . concat ( val ) ; } if ( ! ( ( Array . isArray ( val ) && ! val . length ) || ( typeof val === 'object' && ! Object . keys ( val || { } ) . length ) ) ) { target [ keyPart ] = val ; } } } else if ( ! ( keyPart in target ) ) { target [ keyPart ] = { } ; } } ) ; }


Input: Filter factory [CODESPLIT] function ( token ) { var filter = { val : '' , opts : [ ] , type : 'filter' } token . filters . push ( filter ) ; return filter ; }


Input: This is a custom tree sorting algorithm . It uses the index property on each node to determine how to sort siblings . It uses the depth property plus the index to create a weight for each node . This weight algorithm has the limitation of not being able to go more then 80 levels in depth or more then 10k nodes per parent . The end result is a flat collection being correctly sorted based on this one single sort function . [CODESPLIT] function ( node1 , node2 ) { // A shortcut for siblings if ( node1 . parentNode === node2 . parentNode ) { return ( node1 . data . index < node2 . data . index ) ? - 1 : 1 ; } // @NOTE: with the following algorithm we can only go 80 levels deep in the tree // and each node can contain 10000 direct children max var weight1 = 0 , weight2 = 0 , parent1 = node1 , parent2 = node2 ; while ( parent1 ) { weight1 += ( Math . pow ( 10 , ( parent1 . data . depth + 1 ) * - 4 ) * ( parent1 . data . index + 1 ) ) ; parent1 = parent1 . parentNode ; } while ( parent2 ) { weight2 += ( Math . pow ( 10 , ( parent2 . data . depth + 1 ) * - 4 ) * ( parent2 . data . index + 1 ) ) ; parent2 = parent2 . parentNode ; } if ( weight1 > weight2 ) { return 1 ; } else if ( weight1 < weight2 ) { return - 1 ; } return ( node1 . data . index > node2 . data . index ) ? 1 : - 1 ; }


Input: Private method used to deeply retrieve the children of a record without recursion . [CODESPLIT] function ( root ) { var node = this . getNode ( ) , recursive = this . getRecursive ( ) , added = [ ] , child = root ; if ( ! root . childNodes . length || ( ! recursive && root !== node ) ) { return added ; } if ( ! recursive ) { return root . childNodes ; } while ( child ) { if ( child . _added ) { delete child . _added ; if ( child === root ) { break ; } else { child = child . nextSibling || child . parentNode ; } } else { if ( child !== root ) { added . push ( child ) ; } if ( child . firstChild ) { child . _added = true ; child = child . firstChild ; } else { child = child . nextSibling || child . parentNode ; } } } return added ; }


Input: Requests access to the Local File System [CODESPLIT] function ( config ) { var me = this ; config = Ext . device . filesystem . Abstract . prototype . requestFileSystem ( config ) ; var successCallback = function ( fs ) { var fileSystem = Ext . create ( 'Ext.device.filesystem.FileSystem' , fs ) ; config . success . call ( config . scope || me , fileSystem ) ; } ; if ( config . type == window . PERSISTENT ) { if ( navigator . webkitPersistentStorage ) { navigator . webkitPersistentStorage . requestQuota ( config . size , function ( grantedBytes ) { window . webkitRequestFileSystem ( config . type , grantedBytes , successCallback , config . failure ) ; } ) } else { window . webkitStorageInfo . requestQuota ( window . PERSISTENT , config . size , function ( grantedBytes ) { window . webkitRequestFileSystem ( config . type , grantedBytes , successCallback , config . failure ) ; } ) } } else { window . webkitRequestFileSystem ( config . type , config . size , successCallback , config . failure ) ; } }


Input: / * We use the PubSub to publish messages to everyone that is subscribed [CODESPLIT] function PubSub ( pub , sub ) { events . EventEmitter . call ( this ) ; var self = this ; //create a redis socket for publishing and connect to address and port this . pub = pub || redis . createClient ( ) ; //create a redis socket for subscribing and connect to address and port this . sub = sub || redis . createClient ( ) ; //when we receive a message from the subscription socket have us emit a "message" event this . sub . on ( 'message' , function ( channel , message ) { //TODO update this self . emit ( 'message' , String ( channel + ' ' + message ) ) ; } ) ; }


Input: Performs Ajax request . [CODESPLIT] function ( operation , callback , scope ) { var me = this , writer = me . getWriter ( ) , request = me . buildRequest ( operation ) ; request . setConfig ( { headers : me . getHeaders ( ) , timeout : me . getTimeout ( ) , method : me . getMethod ( request ) , callback : me . createRequestCallback ( request , operation , callback , scope ) , scope : me , proxy : me , useDefaultXhrHeader : me . getUseDefaultXhrHeader ( ) } ) ; if ( operation . getWithCredentials ( ) || me . getWithCredentials ( ) ) { request . setWithCredentials ( true ) ; request . setUsername ( me . getUsername ( ) ) ; request . setPassword ( me . getPassword ( ) ) ; } // We now always have the writer prepare the request request = writer . write ( request ) ; Ext . Ajax . request ( request . getCurrentConfig ( ) ) ; return request ; }


Input: Get unique error field name [CODESPLIT] function ( err ) { var output ; try { var fieldName = err . err . substring ( err . err . lastIndexOf ( '.$' ) + 2 , err . err . lastIndexOf ( '_1' ) ) ; output = fieldName . charAt ( 0 ) . toUpperCase ( ) + fieldName . slice ( 1 ) + ' already exists' ; } catch ( ex ) { output = 'Unique field already exists' ; } return output ; }


Input: Updates the message element with the new value of the { [CODESPLIT] function ( newMessage ) { var cls = Ext . baseCSSPrefix + 'has-message' ; if ( newMessage ) { this . addCls ( cls ) ; } else { this . removeCls ( cls ) ; } this . messageElement . setHtml ( newMessage ) ; }


Input: / * istanbul ignore next [CODESPLIT] function isPromise ( val , Promize ) { return val instanceof Promize || ( val !== null && typeof val === 'object' && typeof val . then === 'function' && typeof val . catch === 'function' ) }


Input: attempt to require a file passing args to require if 2nd arg ( err ) is a bool and true - > return the error if an error occurs otherwise return null if error or return module if success [CODESPLIT] function acquire ( src , err ) { let mod = _ . attempt ( require , src ) return mod ? _ . isError ( mod ) ? _ . isBoolean ( err ) && err ? mod : null : null : mod }


Input: same as _ . assign but does not alter first arg object assign WILL overwrite undefined values ( from right to left ) [CODESPLIT] function acopy ( ) { let zargs = _ . toArray ( arguments ) zargs . unshift ( { } ) return _ . assign . apply ( _ , zargs ) }


Input: same as _ . merge but does not alter first arg object merge WILL NOT overwrite undefined values ( from right to left ) [CODESPLIT] function mcopy ( ) { let zargs = _ . toArray ( arguments ) zargs . unshift ( { } ) return _ . merge . apply ( _ , zargs ) }


Input: Create a project with the default files and folders . [CODESPLIT] function ( project ) { var current = process . cwd ( ) ; console . log ( '\nCreating folder "' + project + '"...' ) ; // First, create the directory fs . mkdirSync ( path . join ( current , project ) ) ; console . log ( '\nCopying the files in "' + project + '"...' ) ; // Then, copy the files into it wrench . copyDirSyncRecursive ( path . join ( __dirname , 'default' , 'project' ) , path . join ( current , project ) ) ; console . log ( '\nCreating the package.json file...' ) ; // Open the package.json file and fill it in // with the correct datas. var packagePath = path . join ( current , project , 'package.json' ) ; // First, get the datas var pack = JSON . parse ( fs . readFileSync ( packagePath ) ) ; // Add the properties in the object pack . name = project ; pack . version = '0.0.1' ; pack . dependencies = { 'tartempion' : '0.0.x' } ; // And write the object to the package.json file // by overriding everything in it. fs . writeFileSync ( packagePath , JSON . stringify ( pack , null , 4 ) ) ; console . log ( '\nProject "' + project + '" created.\n' ) ; }


Input: browserify [CODESPLIT] function browserifyTask ( ) { // lazy loading required modules. var Browserify = require ( 'browserify' ) ; var browserSync = require ( 'browser-sync' ) ; var buffer = require ( 'vinyl-buffer' ) ; var log = require ( 'gulp-util' ) . log ; var merge = require ( 'merge-stream' ) ; var notify = require ( 'gulp-notify' ) ; var sourcemaps = require ( 'gulp-sourcemaps' ) ; var uglify = require ( 'gulp-uglify' ) ; var vinylify = require ( 'vinyl-source-stream' ) ; var watchify = require ( 'watchify' ) ; var _ = require ( 'lodash' ) ; // NOTE: //  1.Transform must be registered after plugin //  2.Some plugin (e.g. tsify) use transform internally, so make sure transforms are registered right after browserify initialized. var EXCERPTS = [ 'plugin' , 'transform' , 'require' , 'exclude' , 'external' , 'ignore' ] ; var gulp = this . gulp ; var config = this . config ; // Start bundling with Browserify for each bundle config specified return merge ( _ . map ( config . bundles , browserifyThis ) ) ; function browserifyThis ( bundleConfig ) { var options , excerpts , browserify ; options = realizeOptions ( ) ; excerpts = _ . pick ( options , EXCERPTS ) ; options = _ . omit ( options , EXCERPTS ) ; options = prewatch ( options ) ; browserify = new Browserify ( options ) . on ( 'log' , log ) ; watch ( ) ; EXCERPTS . forEach ( function ( name ) { var excerpt = excerpts [ name ] ; _apply ( excerpt , function ( target ) { browserify [ name ] ( target ) ; } ) ; } ) ; return bundle ( ) ; // Add watchify args function prewatch ( theOptions ) { if ( config . watch ) { return _ . defaults ( theOptions , watchify . args ) ; } return theOptions ; } function watch ( ) { if ( config . watch ) { // Wrap with watchify and rebundle on changes browserify = watchify ( browserify , typeof config . watch === 'object' && config . watch ) ; // Rebundle on update browserify . on ( 'update' , bundle ) ; // bundleLogger.watch(bundleConfig.file); } } function bundle ( ) { var stream , dest ; // Log when bundling starts // bundleLogger.start(bundleConfig.file); stream = browserify . bundle ( ) // Report compile errors . on ( 'error' , handleErrors ) // Use vinyl-source-stream to make the stream gulp compatible. // Specify the desired output filename here. . pipe ( vinylify ( options . file ) ) // optional, remove if you don't need to buffer file contents . pipe ( buffer ( ) ) ; if ( options . sourcemaps ) { // Loads map from browserify file stream = stream . pipe ( sourcemaps . init ( { loadMaps : true } ) ) ; } if ( options . uglify ) { stream = stream . pipe ( uglify ( ) ) ; } // Prepares sourcemaps, either internal or external. if ( options . sourcemaps === true ) { stream = stream . pipe ( sourcemaps . write ( ) ) ; } else if ( typeof options . sourcemaps === 'string' ) { stream = stream . pipe ( sourcemaps . write ( options . sourcemaps ) ) ; } // Specify the output destination dest = options . dest || config . dest ; return stream . pipe ( gulp . dest ( dest . path , dest . options ) ) . pipe ( browserSync . reload ( { stream : true } ) ) ; } function realizeOptions ( ) { var result ; result = _ . defaults ( { } , _ . omit ( bundleConfig , [ 'options' ] ) , bundleConfig . options , config . options ) ; result . entries = result . entries . globs ; // add sourcemap option if ( result . sourcemaps ) { // browserify use 'debug' option for sourcemaps, // but sometimes we want sourcemaps even in production mode. result . debug = true ; } return result ; } function handleErrors ( ) { var args = Array . prototype . slice . call ( arguments ) ; // Send error to notification center with gulp-notify notify . onError ( { title : 'Browserify Error' , message : '<%= error %>' } ) . apply ( this , args ) ; this . emit ( 'end' ) ; } } function _apply ( values , fn ) { if ( Array . isArray ( values ) ) { values . forEach ( fn ) ; } else if ( values ) { fn ( values ) ; } } }


Input: Add watchify args [CODESPLIT] function prewatch ( theOptions ) { if ( config . watch ) { return _ . defaults ( theOptions , watchify . args ) ; } return theOptions ; }


Input: This method inserts all the filters in the passed array at the given index . [CODESPLIT] function ( index , filters ) { // We begin by making sure we are dealing with an array of sorters if ( ! Ext . isArray ( filters ) ) { filters = [ filters ] ; } var ln = filters . length , filterRoot = this . getFilterRoot ( ) , currentFilters = this . getFilters ( ) , newFilters = [ ] , filterConfig , i , filter ; if ( ! currentFilters ) { currentFilters = this . createFiltersCollection ( ) ; } // We first have to convert every sorter into a proper Sorter instance for ( i = 0 ; i < ln ; i ++ ) { filter = filters [ i ] ; filterConfig = { root : filterRoot } ; if ( Ext . isFunction ( filter ) ) { filterConfig . filterFn = filter ; } // If we are dealing with an object, we assume its a Sorter configuration. In this case // we create an instance of Sorter passing this configuration. else if ( Ext . isObject ( filter ) ) { if ( ! filter . isFilter ) { if ( filter . fn ) { filter . filterFn = filter . fn ; delete filter . fn ; } filterConfig = Ext . apply ( filterConfig , filter ) ; } else { newFilters . push ( filter ) ; if ( ! filter . getRoot ( ) ) { filter . setRoot ( filterRoot ) ; } continue ; } } // Finally we get to the point where it has to be invalid // <debug> else { Ext . Logger . warn ( 'Invalid filter specified:' , filter ) ; } // </debug> // If a sorter config was created, make it an instance filter = Ext . create ( 'Ext.util.Filter' , filterConfig ) ; newFilters . push ( filter ) ; } // Now lets add the newly created sorters. for ( i = 0 , ln = newFilters . length ; i < ln ; i ++ ) { currentFilters . insert ( index + i , newFilters [ i ] ) ; } this . dirtyFilterFn = true ; if ( currentFilters . length ) { this . filtered = true ; } return currentFilters ; }


Input: This method removes all the filters in a passed array . [CODESPLIT] function ( filters ) { // We begin by making sure we are dealing with an array of sorters if ( ! Ext . isArray ( filters ) ) { filters = [ filters ] ; } var ln = filters . length , currentFilters = this . getFilters ( ) , i , filter ; for ( i = 0 ; i < ln ; i ++ ) { filter = filters [ i ] ; if ( typeof filter === 'string' ) { currentFilters . each ( function ( item ) { if ( item . getProperty ( ) === filter ) { currentFilters . remove ( item ) ; } } ) ; } else if ( typeof filter === 'function' ) { currentFilters . each ( function ( item ) { if ( item . getFilterFn ( ) === filter ) { currentFilters . remove ( item ) ; } } ) ; } else { if ( filter . isFilter ) { currentFilters . remove ( filter ) ; } else if ( filter . property !== undefined && filter . value !== undefined ) { currentFilters . each ( function ( item ) { if ( item . getProperty ( ) === filter . property && item . getValue ( ) === filter . value ) { currentFilters . remove ( item ) ; } } ) ; } } } if ( ! currentFilters . length ) { this . filtered = false ; } }


Input: This updates the cached sortFn based on the current sorters . [CODESPLIT] function ( ) { var filters = this . getFilters ( ) . items ; this . filterFn = function ( item ) { var isMatch = true , length = filters . length , i ; for ( i = 0 ; i < length ; i ++ ) { var filter = filters [ i ] , fn = filter . getFilterFn ( ) , scope = filter . getScope ( ) || this ; isMatch = isMatch && fn . call ( scope , item ) ; } return isMatch ; } ; this . dirtyFilterFn = false ; return this . filterFn ; }


Input: Special handler of merge . Arrays are merged by the concatenation . [CODESPLIT] function mergeCustomizer ( objValue , srcValue , key ) { if ( isArray ( objValue ) ) { return objValue . concat ( srcValue ) ; } if ( METHODS_INHERITANCE . indexOf ( key ) !== - 1 ) { return wrap ( objValue , wrap ( srcValue , wrapperFunction ) ) ; } if ( METHODS_MERGE_RESULT . indexOf ( key ) !== - 1 ) { return wrap ( objValue , wrap ( srcValue , wrapperMergeResult ) ) ; } if ( key === 'shouldComponentUpdate' ) { return wrap ( objValue , wrap ( srcValue , wrapperOrResult ) ) ; } if ( key === 'statics' ) { checkOverriddenMethods ( objValue , srcValue ) ; } if ( key === 'render' && objValue && srcValue ) { throw new Error ( 'The "render" method you can override' ) ; } if ( key === 'displayName' && objValue && srcValue ) { throw new Error ( 'The "displayName" property can not be redefined' ) ; } if ( isFunction ( objValue ) && isFunction ( srcValue ) ) { throw new Error ( ` ${ key } ` ) ; } }


Input: The implementation of the merger result . [CODESPLIT] function wrapperMergeResult ( srcFunc , objFunc , ... args ) { let resultObjFunction = { } ; let resultSrcFunction = { } ; if ( isFunction ( objFunc ) ) { resultObjFunction = objFunc . apply ( this , args ) ; } if ( isFunction ( srcFunc ) ) { resultSrcFunction = srcFunc . apply ( this , args ) ; } return merge ( { } , resultObjFunction , resultSrcFunction ) ; }


Input: Merging the result of the logical or . [CODESPLIT] function wrapperOrResult ( srcFunc , objFunc , ... args ) { let resultObjFunction = false ; let resultSrcFunction = false ; if ( isFunction ( objFunc ) ) { resultObjFunction = objFunc . apply ( this , args ) ; } if ( isFunction ( srcFunc ) ) { resultSrcFunction = srcFunc . apply ( this , args ) ; } return resultObjFunction || resultSrcFunction ; }


Input: A mock of the ember Snapshot object [CODESPLIT] function ( instance ) { this . _model = instance . _model ; this . _instance = instance ; this . id = instance . id ; this . eachAttribute = function ( cb ) { return this . _model . eachAttribute ( cb ) ; } ; this . eachRelationship = function ( cb ) { return this . _model . eachRelationship ( cb ) ; } this . attr = function ( name ) { return this . _instance [ name ] ; } ; this . belongsTo = function ( name , opts ) { return ( opts . id ? this . _instance [ name ] . id : new Snapshot ( this . _instance [ name ] ) ) ; } ; }


Input: Normalises a json string to a valid deserialisable json string [CODESPLIT] function ( val ) { var trimmed = val . trim ( ) ; if ( trimmed . indexOf ( "'" ) === 0 && trimmed . lastIndexOf ( "'" ) === ( trimmed . length - 1 ) ) return '"' + trimmed . substring ( 1 , trimmed . length - 1 ) + '"' ; return val ; }


Input: A mock of the salesforce SObject object [CODESPLIT] function ( typeName , obj ) { this . type = typeName ; if ( typeof obj !== 'undefined' ) for ( var key in obj ) this [ key ] = obj [ key ] ; }


Input: Generates a new fake salesforce id [CODESPLIT] function ( ) { var idStr = '' + sforce . db . id ++ ; return sforce . db . _idTemplate . substring ( 0 , 18 - idStr . length ) + idStr ; }


Input: Returns an antlr4 parse tree for a select query string [CODESPLIT] function ( select ) { var chars = new antlr4 . InputStream ( input ) ; var lexer = new SelectLexer ( chars ) ; var tokens = new antlr4 . CommonTokenStream ( lexer ) ; var parser = new SelectParser ( tokens ) ; parser . buildParseTrees = true ; return parser . select ( ) ; }


Input: Validates a given objects against the schema [CODESPLIT] function ( obj ) { var schema = sforce . db . schema ; var objDesc = schema [ obj . type ] ; if ( typeof objDesc === 'undefined' ) throw 'No type exists by the name: ' + obj . type ; for ( var key in obj ) { if ( { Id : false , type : true } [ key ] ) continue ; var fieldDesc = null ; for ( var i = 0 ; i < objDesc . fields . length ; i ++ ) { var fd = objDesc . fields [ i ] ; if ( fd . name === key ) { fieldDesc = fd ; break ; } } if ( fieldDesc == null ) throw 'No field exists by the name: ' + key + 'in the type: ' + obj . type ; } }


Input: Validates a list of field names against a type in the schema [CODESPLIT] function ( type , fields ) { for ( var i = 0 ; i < fields . length ; i ++ ) sforce . db . validateField ( type , fields [ i ] ) ; }


Input: Validates a field name against a type in the schema [CODESPLIT] function ( type , field ) { var objDesc = sforce . db . schema [ type ] ; for ( var i = 0 ; i < objDesc . fields . length ; i ++ ) if ( objDesc . fields [ i ] . name === field ) return ; throw 'No field exists by the name: ' + field + 'in the type: ' + type ; }


Input: Validates a relationship name against a type in the schema [CODESPLIT] function ( type , rel ) { var objDesc = sforce . db . schema [ type ] ; for ( var i = 0 ; i < objDesc . childRelationships . length ; i ++ ) if ( objDesc . childRelationships [ i ] . relationshipName === rel ) return ; throw 'No child relationship exists by the name: ' + rel + 'in the type: ' + type ; }


Input: Get all SObjects of the given type [CODESPLIT] function ( type ) { var sos = sforce . db . sobjects ; if ( typeof sos [ type ] !== 'object' ) sos [ type ] = { } ; return sos [ type ] ; }


Input: Create the objects in the array in the database and call success ( ... ) or err ( ... ) on success / failure [CODESPLIT] function ( objAry , success , err ) { var result = [ ] ; for ( var i = 0 ; i < objAry . length ; i ++ ) { var obj = objAry [ i ] ; try { sforce . db . validateSobject ( obj ) ; obj = _extend ( { } , obj ) ; var objs = sforce . db . getSobjects ( obj . type ) ; obj . Id = ( ( ! sforce . db . useGivenIds || typeof obj . Id === 'undefined' ) ? sforce . db . newId ( ) : obj . Id ) ; objs [ obj . Id ] = obj ; result . push ( { success : 'true' , id : obj . Id } ) ; } catch ( e ) { result . push ( { success : 'false' , id : obj . Id } ) ; } } if ( success ) success ( result ) ; return result ; }


Input: Delete all objects with thi id s in the id array and call success ( ... ) or err ( ... ) on success / failure [CODESPLIT] function ( idAry , success , err ) { var result = [ ] ; for ( var i = 0 ; i < idAry . length ; i ++ ) { var found = false ; var Id = idAry [ i ] ; for ( var type in this . schema ) { var allOfType = sforce . db . getSobjects ( type ) ; if ( Id in allOfType ) { delete allOfType [ Id ] ; found = true ; result . push ( { success : 'true' , id : Id } ) ; break ; } } if ( ! found ) result . push ( { success : 'false' , id : Id } ) ; } if ( success ) success ( result ) ; return result ; }


Input: Run a select query on the database and call success ( ... ) or err ( ... ) on success / failure [CODESPLIT] function ( select , success , err ) { try { var chars = new antlr4 . InputStream ( select ) ; var lexer = new SelectLexer ( chars ) ; var tokens = new antlr4 . CommonTokenStream ( lexer ) ; var parser = new SelectParser ( tokens ) ; parser . buildParseTrees = true ; var tree = parser . select ( ) ; console . log ( tree . toStringTree ( ) ) ; var listener = new QueryBuilderListener ( sforce . db ) ; antlr4 . tree . ParseTreeWalker . DEFAULT . walk ( listener , tree ) ; var result = listener . query . getResult ( ) ; if ( success ) success ( result ) ; return result ; } catch ( e ) { if ( err ) err ( e ) ; return e ; } }


Input: Creates a wrapped result in the form that you would expect the salesforce soap api to return a result [CODESPLIT] function ( resultAry , isRoot ) { if ( resultAry . length == 0 ) { if ( isRoot ) return { done : 'true' , queryLocator : null , size : 0 , } ; return null ; } var records = null ; if ( resultAry . length == 1 ) records = resultAry [ 0 ] ; else records = resultAry ; return { done : 'true' , queryLocator : null , records : records , size : resultAry . length , } ; }


Input: A mothod to create a result object out of a resolved object in the db [CODESPLIT] function ( obj ) { var result = { type : this . type } ; this . db . validateFields ( this . type , this . fields ) ; for ( var i = 0 ; i < this . fields . length ; i ++ ) { var fName = this . fields [ i ] ; result [ fName ] = obj [ fName ] ; } for ( var i = 0 ; i < this . subqueries . length ; i ++ ) { var sq = this . subqueries [ i ] ; result [ sq . relationship ] = sq . getResult ( obj ) ; } return result }


Input: Runs the query against the db [CODESPLIT] function ( ) { var all = this . db . getSobjects ( this . type ) ; var result = [ ] ; for ( var Id in all ) { var obj = all [ Id ] ; if ( ! this . condition || this . condition . matches ( obj ) ) result . push ( this . _createResultObj ( obj ) ) ; } return this . db . wrapResult ( result , true ) ; }


Input: A mothod to create a result object out of a resolved object in the db [CODESPLIT] function ( obj ) { var result = { type : obj . type } ; this . getDb ( ) . validateFields ( obj . type , this . fields ) ; for ( var i = 0 ; i < this . fields . length ; i ++ ) { var fName = this . fields [ i ] ; result [ fName ] = obj [ fName ] ; } return result }


Input: Runs the query against the db [CODESPLIT] function ( parentObj ) { this . getDb ( ) . validateRelationship ( this . getType ( ) , this . relationship ) var objDesc = this . getDb ( ) . schema [ this . getType ( ) ] ; var relDesc = null ; for ( var i = 0 ; i < objDesc . childRelationships . length ; i ++ ) if ( this . relationship === objDesc . childRelationships [ i ] . relationshipName ) relDesc = objDesc . childRelationships [ i ] ; if ( relDesc == null ) throw 'No child relationship by the name: ' + this . relationship + ' exists in the type: ' + this . getType ( ) ; var relObjDesc = this . getDb ( ) . schema [ relDesc . childSObject ] ; var all = this . getDb ( ) . getSobjects ( relDesc . childSObject ) ; var result = [ ] ; for ( var key in all ) { var obj = all [ key ] ; if ( obj [ relDesc . field ] === parentObj . Id && ( ! this . condition || this . condition . matches ( obj ) ) ) result . push ( this . _createResultObj ( obj ) ) ; } return this . getDb ( ) . wrapResult ( result ) ; }


Input: Runs the conditions in the condition set and returns a boolean as a result [CODESPLIT] function ( obj ) { var matches = this . sequence [ 0 ] . matches ( obj ) ; for ( var i = 1 ; i < this . sequence . length ; i += 2 ) { if ( this . sequence [ i ] === '&' ) matches = matches && this . sequence [ i + 1 ] . matches ( obj ) ; else matches = matches || this . sequence [ i + 1 ] . matches ( obj ) ; } return matches ; }


Input:
Add Contents for page [CODESPLIT] function addContents ( $ , contents ) { console . log ( 'addContents' , contents ) ; var body = document . getElementsByTagName ( 'BODY' ) ; if ( ! body ) return ; var $body = $ ( body [ 0 ] ) , contentsStyle = [ 'position:fixed;right:1em;top:1em;' , 'padding:0.5em;min-width:120px;' , 'font-size:90%;line-height:18px;' , 'border:1px solid #aaa;background: #F9F9F9;' ] . join ( '' ) , html = [ ] , order = [ ] , hash = [ ] ; for ( var i = 0 ; i < contents . length ; ++ i ) { order [ i ] = 0 ; hash [ i ] = '' ; } function indexOf ( tag ) { for ( var i = 0 ; i < contents . length && contents [ i ] . toLowerCase ( ) !== tag ; ++ i ) ; return i ; } $ ( contents . join ( ',' ) ) . each ( function ( i , obj ) { var index = indexOf ( obj . tagName . toLowerCase ( ) ) ; order [ index ] ++ ; hash [ index ] = $ ( obj ) . text ( ) ; for ( var j = index + 1 ; j < contents . length ; ++ j ) { // Clear low level order order [ j ] = 0 ; hash [ j ] = '' ; } var anchor = hash . slice ( 0 , index + 1 ) . join ( '-' ) ; //anchor = '__id_' + tag + Math.floor(9999999 * Math.random()); // Add anchor $ ( obj ) . append ( fm ( '' , anchor ) ) ; // Add contents item html . push ( fm ( '
{1}
' , index * 1.5 , order . slice ( 0 , index + 1 ) . join ( '.' ) + ' ' + hash [ index ] , anchor ) ) ; } ) ; var $contentsWrap = $ ( fm ( [ '
' , '
' , 'Contents hide' , '
' , '
{1}
' , '
' ] . join ( '' ) , contentsStyle , html . join ( '' ) ) ) . prependTo ( $body ) , $toggle = $contentsWrap . find ( '> :first' ) . find ( '> :last' ) , $contents = $contentsWrap . find ( '> :last' ) ; console . log ( $contentsWrap , $toggle , $contents ) ; $toggle . click ( function ( ) { $contents . slideToggle ( ) ; $toggle . html ( $toggle . html ( ) === 'show' ? 'hide' : 'show' ) ; } ) ; }


Input:
Add to Top link for mark h [CODESPLIT] function addTop ( $ , top ) { console . log ( 'addTop' , top ) ; $ ( top . join ( ',' ) ) . each ( function ( i , obj ) { //$(obj).append(' Top'); $ ( obj ) . prepend ( [ '
' , '' , '✦' , '
' ] . join ( '' ) ) ; var $prefix = $ ( this ) . find ( ':first' ) . find ( ':first' ) ; //var $top = $(this).find('a:last'); //console.log($prefix, $top); var rawCol = $ ( obj ) . css ( 'background-color' ) ; $ ( obj ) . mouseover ( function ( ) { $prefix . css ( 'height' , $ ( this ) . css ( 'height' ) ) ; $prefix . css ( 'line-height' , $ ( this ) . css ( 'line-height' ) ) ; $prefix . css ( 'visibility' , 'visible' ) ; $ ( this ) . css ( 'background-color' , '#FFF8D7' ) ; } ) . mouseout ( function ( ) { $prefix . css ( 'visibility' , 'hidden' ) ; $ ( this ) . css ( 'background-color' , rawCol ) ; } ) ; } ) ; }


Input: Initialize the API [CODESPLIT] function ( ) { var actions = this . getActions ( ) , namespace = this . getNamespace ( ) , action , cls , methods , i , ln , method ; for ( action in actions ) { if ( actions . hasOwnProperty ( action ) ) { cls = namespace [ action ] ; if ( ! cls ) { cls = namespace [ action ] = { } ; } methods = actions [ action ] ; for ( i = 0 , ln = methods . length ; i < ln ; ++ i ) { method = Ext . create ( 'Ext.direct.RemotingMethod' , methods [ i ] ) ; cls [ method . getName ( ) ] = this . createHandler ( action , method ) ; } } } }


Input: Run any callbacks related to the transaction . [CODESPLIT] function ( transaction , event ) { var success = ! ! event . getStatus ( ) , functionName = success ? 'success' : 'failure' , callback = transaction && transaction . getCallback ( ) , result ; if ( callback ) { // this doesnt make any sense. why do we have both result and data? // result = Ext.isDefined(event.getResult()) ? event.result : event.data; result = event . getResult ( ) ; if ( Ext . isFunction ( callback ) ) { callback ( result , event , success ) ; } else { Ext . callback ( callback [ functionName ] , callback . scope , [ result , event , success ] ) ; Ext . callback ( callback . callback , callback . scope , [ result , event , success ] ) ; } } }


Input: React to the AJAX request being completed . [CODESPLIT] function ( options , success , response ) { var me = this , i = 0 , ln , events , event , transaction , transactions ; if ( success ) { events = me . createEvents ( response ) ; for ( ln = events . length ; i < ln ; ++ i ) { event = events [ i ] ; transaction = me . getTransaction ( event ) ; me . fireEvent ( 'data' , me , event ) ; if ( transaction ) { me . runCallback ( transaction , event , true ) ; Ext . direct . Manager . removeTransaction ( transaction ) ; } } } else { transactions = [ ] . concat ( options . transaction ) ; for ( ln = transactions . length ; i < ln ; ++ i ) { transaction = me . getTransaction ( transactions [ i ] ) ; if ( transaction && transaction . getRetryCount ( ) < me . getMaxRetries ( ) ) { transaction . retry ( ) ; } else { event = Ext . create ( 'Ext.direct.ExceptionEvent' , { data : null , transaction : transaction , code : Ext . direct . Manager . exceptions . TRANSPORT , message : 'Unable to connect to the server.' , xhr : response } ) ; me . fireEvent ( 'data' , me , event ) ; if ( transaction ) { me . runCallback ( transaction , event , false ) ; Ext . direct . Manager . removeTransaction ( transaction ) ; } } } } }


Input: Get transaction from XHR options . [CODESPLIT] function ( options ) { return options && options . getTid ? Ext . direct . Manager . getTransaction ( options . getTid ( ) ) : null ; }


Input: Configure a direct request . [CODESPLIT] function ( action , method , args ) { var me = this , callData = method . getCallData ( args ) , data = callData . data , callback = callData . callback , scope = callData . scope , transaction ; transaction = Ext . create ( 'Ext.direct.Transaction' , { provider : me , args : args , action : action , method : method . getName ( ) , data : data , callback : scope && Ext . isFunction ( callback ) ? Ext . Function . bind ( callback , scope ) : callback } ) ; if ( me . fireEvent ( 'beforecall' , me , transaction , method ) !== false ) { Ext . direct . Manager . addTransaction ( transaction ) ; me . queueTransaction ( transaction ) ; me . fireEvent ( 'call' , me , transaction , method ) ; } }


Input: Gets the AJAX call info for a transaction . [CODESPLIT] function ( transaction ) { return { action : transaction . getAction ( ) , method : transaction . getMethod ( ) , data : transaction . getData ( ) , type : 'rpc' , tid : transaction . getId ( ) } ; }


Input: Add a new transaction to the queue . [CODESPLIT] function ( transaction ) { var me = this , enableBuffer = me . getEnableBuffer ( ) ; if ( transaction . getForm ( ) ) { me . sendFormRequest ( transaction ) ; return ; } me . callBuffer . push ( transaction ) ; if ( enableBuffer ) { if ( ! me . callTask ) { me . callTask = Ext . create ( 'Ext.util.DelayedTask' , me . combineAndSend , me ) ; } me . callTask . delay ( Ext . isNumber ( enableBuffer ) ? enableBuffer : 10 ) ; } else { me . combineAndSend ( ) ; } }


Input: Combine any buffered requests and send them off . [CODESPLIT] function ( ) { var buffer = this . callBuffer , ln = buffer . length ; if ( ln > 0 ) { this . sendRequest ( ln == 1 ? buffer [ 0 ] : buffer ) ; this . callBuffer = [ ] ; } }


Input: Configure a form submission request [CODESPLIT] function ( action , method , form , callback , scope ) { var me = this , transaction , isUpload , params ; transaction = new Ext . direct . Transaction ( { provider : me , action : action , method : method . getName ( ) , args : [ form , callback , scope ] , callback : scope && Ext . isFunction ( callback ) ? Ext . Function . bind ( callback , scope ) : callback , isForm : true } ) ; if ( me . fireEvent ( 'beforecall' , me , transaction , method ) !== false ) { Ext . direct . Manager . addTransaction ( transaction ) ; isUpload = String ( form . getAttribute ( 'enctype' ) ) . toLowerCase ( ) == 'multipart/form-data' ; params = { extTID : transaction . id , extAction : action , extMethod : method . getName ( ) , extType : 'rpc' , extUpload : String ( isUpload ) } ; // change made from typeof callback check to callback.params // to support addl param passing in DirectSubmit EAC 6/2 Ext . apply ( transaction , { form : Ext . getDom ( form ) , isUpload : isUpload , params : callback && Ext . isObject ( callback . params ) ? Ext . apply ( params , callback . params ) : params } ) ; me . fireEvent ( 'call' , me , transaction , method ) ; me . sendFormRequest ( transaction ) ; } }


Input: Sends a form request [CODESPLIT] function ( transaction ) { var me = this ; Ext . Ajax . request ( { url : me . getUrl ( ) , params : transaction . params , callback : me . onData , scope : me , form : transaction . form , isUpload : transaction . isUpload , transaction : transaction } ) ; }


Input: Work with options here [CODESPLIT] function inlineBlockFix ( decl ) { var origRule = decl . parent ; origRule . append ( { prop : '*display' , value : 'inline' } , { prop : '*zoom' , value : '1' } ) ; }


Input: <debug > [CODESPLIT] function ( target , eventName ) { if ( ! this . handles ( eventName ) ) { return false ; } var match = target . match ( this . idOrClassSelectorRegex ) , subscribers = this . getSubscribers ( eventName ) , type , value ; if ( match !== null ) { type = match [ 1 ] ; value = match [ 2 ] ; if ( type === '#' ) { return subscribers . id . hasOwnProperty ( value ) ; } else { return subscribers . className . hasOwnProperty ( value ) ; } } else { return ( subscribers . selector . hasOwnProperty ( target ) && Ext . Array . indexOf ( subscribers . selector , target ) !== - 1 ) ; } return false ; }


Input: When generating the . idea project WebStorm will remove any plain text files specified on first open if they do not exist . For example this lets files from a build be marked as plain text before they exist by stubbing an empty file at their expected position . [CODESPLIT] function stubPlainTextFiles ( resourceRoots , destination ) { _ . forEach ( resourceRoots , function ( resource ) { // Replace the webstorm file:// scheme with an absolute file path var filePath = resource . replace ( 'file://$PROJECT_DIR$' , destination ) ; filePath = filePath . replace ( '.idea/' , '' ) ; // Extract the location from the file path to recursively create it if it doesn't exist. var location = filePath . replace ( / [^\/]*$ / , '' ) ; if ( ! fs . existsSync ( location ) ) mkdir ( '-p' , location ) ; if ( ! fs . existsSync ( filePath ) ) fs . writeFileSync ( filePath , ' ' , 'utf8' ) ; } ) ; }


Input: The user preferences directory for WebStorm on the current platform . https : // www . jetbrains . com / webstorm / help / project - and - ide - settings . html [CODESPLIT] function userPreferencesDirectory ( configDirectory ) { var home = platform . userHomeDirectory ( ) ; var webStormPreferences = io . maximisePath ( home , / ^\.WebStorm\s*[.\d]+$ / , 'config' ) || // windows|unix io . maximisePath ( home , 'Library' , 'Preferences' , / ^WebStorm\s*[.\d]+$ / ) ; // darwin // If the config directory does not previously exist, create it. // Eg the tools directory wont exist unless External Tools were previously used. if ( webStormPreferences ) { webStormPreferences = path . join ( webStormPreferences , configDirectory ) ; if ( ! fs . existsSync ( webStormPreferences ) ) { fs . mkdirSync ( webStormPreferences ) ; } } return webStormPreferences ; }


Input: Utility to write the ProjectView node require for project pane default in the . idea / workspace . xml . [CODESPLIT] function writeProjectViewTemplate ( rootPath ) { var context = { rootPath : rootPath } ; var templateSource = path . join ( String ( __dirname ) , 'template' , 'projectView.xml' ) ; var toolTemplate = fs . readFileSync ( templateSource ) ; return io . templateSync ( toolTemplate , context ) ; }


Input: Check if a Webstorm . exe exists in a given windows program files directory . [CODESPLIT] function resolveJetbrainsExe ( jetbrainsDirectory ) { var exists = false ; var webstormInstallPaths = io . resolveDirMatches ( jetbrainsDirectory , / ^WebStorm\s*[.\d]+$ / ) ; // Check that the Webstorm folder have a bin folder, empty folders are a known issue. for ( var j = 0 ; j < webstormInstallPaths . length ; j ++ ) { var webstormPath = [ jetbrainsDirectory , webstormInstallPaths [ j ] , 'bin' ] ; var resolvedWebstorm = resolveMaxedPath ( webstormPath ) ; if ( resolvedWebstorm === null ) break ; exists = path . resolve ( resolvedWebstorm . join ( path . sep ) , 'Webstorm.exe' ) ; if ( fs . existsSync ( exists ) ) { return exists ; } } return exists ; }


Input: Trying autodetect and import key [CODESPLIT] function ( key , data ) { if ( data . n && data . e ) { if ( data . d && data . p && data . q && data . dmp1 && data . dmq1 && data . coeff ) { module . exports . privateImport ( key , data ) ; return true ; } else { module . exports . publicImport ( key , data ) ; return true ; } } return false ; }


Input: Mostly from Express router Route . [CODESPLIT] function Route ( method , path , callback , options ) { this . path = path ; this . method = method ; this . callback = callback ; this . regexp = utils . pathRegexp ( path , this . keys = [ ] , options . sensitive , options . strict ) ; }


Input: the _tree2archy function taken directly from bower source https : // github . com / bower / bower / blob / master / lib / renderers / StandardRenderer . js#L424 - 480 [CODESPLIT] function tree2archy ( node ) { var dependencies = mout . object . values ( node . dependencies ) ; var version = ! node . missing ? node . pkgMeta . _release || node . pkgMeta . version : null ; var label = node . endpoint . name + ( version ? '#' + version : '' ) ; var update ; if ( node . root ) { label += ' ' + node . canonicalDir ; } // State labels if ( node . missing ) { label += chalk . red ( ' not installed' ) ; return label ; } if ( node . different ) { label += chalk . red ( ' different' ) ; } if ( node . linked ) { label += chalk . magenta ( ' linked' ) ; } if ( node . incompatible ) { label += chalk . yellow ( ' incompatible' ) + ' with ' + node . endpoint . target ; } else if ( node . extraneous ) { label += chalk . green ( ' extraneous' ) ; } // New versions if ( node . update ) { update = '' ; if ( node . update . target && node . pkgMeta . version !== node . update . target ) { update += node . update . target + ' available' ; } if ( node . update . latest !== node . update . target ) { update += ( update ? ', ' : '' ) ; update += 'latest is ' + node . update . latest ; } if ( update ) { label += ' (' + chalk . cyan ( update ) + ')' ; } } if ( ! dependencies . length ) { return label ; } return { label : label , nodes : mout . object . values ( dependencies ) . map ( tree2archy ) } ; }


Input:
Returns a decorated transport adapter that writes telemetry data [CODESPLIT] function TransportDecorator ( Transport ) { function TelemetryTransport ( contact , options ) { if ( ! ( this instanceof TelemetryTransport ) ) { return new TelemetryTransport ( contact , options ) } assert . ok ( options , 'Missing required options parameter' ) this . _telopts = options . telemetry this . telemetry = new Persistence ( this . _telopts . storage ) Transport . call ( this , contact , options ) } inherits ( TelemetryTransport , Transport ) TelemetryTransport . DEFAULT_METRICS = [ metrics . Latency , metrics . Availability , metrics . Reliability , metrics . Throughput ] /**
   * Wraps _open with telemetry hooks setup
   * #_open
   * @param {Function} callback
   */ TelemetryTransport . prototype . _open = function ( callback ) { var self = this var metrics = this . _telopts . metrics if ( ! metrics || metrics . length === 0 ) { this . _telopts . metrics = TelemetryTransport . DEFAULT_METRICS } this . _telopts . metrics . forEach ( function ( Metric ) { var metric = new Metric ( ) metric . hooks . forEach ( function ( hook ) { self [ hook . trigger ] ( hook . event , hook . handler ( metric , self . telemetry ) ) } ) } ) return Transport . prototype . _open . call ( this , callback ) } return TelemetryTransport }


Input: Represents a routing table of known { [CODESPLIT] function Router ( options ) { if ( ! ( this instanceof Router ) ) { return new Router ( options ) } this . _log = options . logger this . _rpc = options . transport this . _self = this . _rpc . _contact this . _validator = options . validator this . _routingTable = new RoutingTable ( options . storage , this . _rpc ) }


Input: Get a random value from an array [CODESPLIT] function getRandomArrValue ( arr , min = 0 , max = arr . length - 1 ) { return arr [ getRandomInt ( min , max ) ] ; }


Input: Returns a random dinosaur or more random dinosaurs if number is set [CODESPLIT] function random ( number = 1 ) { if ( 1 > number ) { throw Error ( ` ${ number } ` ) ; } if ( number === 1 ) { return getRandomArrValue ( dinosaurs ) ; } else { const l = dinosaurs . length - 1 ; return new Array ( number ) . fill ( ) . map ( ( ) => getRandomArrValue ( dinosaurs , 0 , l ) ) ; } }


Input: @method getInitialConfig @hide Registers a push notification . [CODESPLIT] function ( config ) { var me = this ; if ( ! config . received ) { Ext . Logger . error ( 'Failed to pass a received callback. This is required.' ) ; } if ( config . type == null ) { Ext . Logger . error ( 'Failed to pass a type. This is required.' ) ; } return { success : function ( token ) { me . onSuccess ( token , config . success , config . scope || me ) ; } , failure : function ( error ) { me . onFailure ( error , config . failure , config . scope || me ) ; } , received : function ( notifications ) { me . onReceived ( notifications , config . received , config . scope || me ) ; } , type : config . type } ; }


Input: Specialized version of buildUrl that incorporates the { [CODESPLIT] function ( request ) { var me = this , operation = request . getOperation ( ) , records = operation . getRecords ( ) || [ ] , record = records [ 0 ] , model = me . getModel ( ) , idProperty = model . getIdProperty ( ) , format = me . getFormat ( ) , url = me . getUrl ( request ) , params = request . getParams ( ) || { } , id = ( record && ! record . phantom ) ? record . getId ( ) : params [ idProperty ] ; if ( me . getAppendId ( ) && id ) { if ( ! url . match ( / \/$ / ) ) { url += '/' ; } url += id ; delete params [ idProperty ] ; } if ( format ) { if ( ! url . match ( / \.$ / ) ) { url += '.' ; } url += format ; } request . setUrl ( url ) ; return me . callParent ( [ request ] ) ; }


Input: Shims features of Express s response object in routes . Accepts a callback function to be called with the data to send . [CODESPLIT] function Response ( ghosttrain , callback ) { this . charset = '' ; this . headers = { } ; this . statusCode = 200 ; this . app = ghosttrain ; this . _callback = callback ; }


Input: Sends a response [CODESPLIT] function ( ) { var body ; var app = this . app ; // If status provide, set that, and set `body` to the content correctly if ( typeof arguments [ 0 ] === 'number' ) { this . status ( arguments [ 0 ] ) ; body = arguments [ 1 ] ; } else { body = arguments [ 0 ] ; } var type = this . get ( 'Content-Type' ) ; if ( ! body && type !== 'application/json' ) { body = utils . STATUS_CODES [ this . statusCode ] ; if ( ! type ) this . type ( 'txt' ) ; } else if ( typeof body === 'string' ) { if ( ! type ) { this . charset = this . charset || 'utf-8' ; this . type ( 'html' ) ; } } else if ( typeof body === 'object' ) { if ( body === null ) body = '' ; else if ( ! type || type === 'application/json' ) { this . contentType ( 'application/json' ) ; // Cast object to string to normalize response var replacer = app . get ( 'json replacer' ) ; var spaces = app . get ( 'json spaces' ) ; body = JSON . stringify ( body , replacer , spaces ) ; } } this . end ( body ) ; return this ; }


Input: Sends a JSON response [CODESPLIT] function ( ) { var data ; if ( arguments . length === 2 ) { this . status ( arguments [ 0 ] ) ; data = arguments [ 1 ] ; } else { data = arguments [ 0 ] ; } if ( ! this . get ( 'Content-Type' ) ) this . contentType ( 'application/json' ) ; return this . send ( data ) ; }


Input: Sets field header to value or accepts an object and applies those key value pairs to the Response object s headers . [CODESPLIT] function ( field , value ) { if ( arguments . length === 2 ) this . headers [ field ] = value ; else { for ( var prop in field ) this . headers [ prop ] = field [ prop ] ; } return this ; }


Input: Formats response and calls initial callback [CODESPLIT] function ( body ) { var type = this . get ( 'Content-Type' ) ; if ( type === 'application/json' ) this . _callback ( JSON . parse ( body || '{}' ) ) ; else this . _callback ( body ) ; }


Input: Asserts that the arguments supplied are what s expected . If an argument can be multiples types use an array of acceptable types . [CODESPLIT] function ( args ) { // Find the minimum expected length. var expected = Array . prototype . slice . call ( arguments , 1 ) ; var minimum = expected . length var hasOptionalTypes = false ; for ( var i = 0 ; i < expected . length ; i ++ ) { if ( ! isValidType ( expected [ i ] ) ) { throw Error ( 'Expected argument ' + i + ' is not a valid type.' ) ; } if ( isOptionalType ( expected [ i ] ) ) { minimum -- ; hasOptionalTypes = true ; } } ; // Exit early if in production, INSIST_IN_PROD is not equal to true and there are no optional // options. if ( isDisabled && ! hasOptionalTypes ) { return [ ] ; } // Check if the args and expected lengths are different (and there are no optional args). if ( minimum == expected . length && args . length != expected . length ) { throw Error ( getExpectedVsRecieved_ ( expected , args ) ) ; } // Check if the args are within the expected range. if ( args . length < minimum || args . length > expected . length ) { throw Error ( getExpectedVsRecieved_ ( expected , args ) ) ; } // We don't have to worry about shifting if all the arguments are present. if ( args . length === expected . length ) { for ( var i = 0 ; i < expected . length ; i ++ ) { if ( ! isOfType ( args [ i ] , expected [ i ] ) ) { throw Error ( getExpectedVsRecieved_ ( expected , args ) ) ; } } ; return args ; } return shiftArguments_ ( expected , args , minimum ) ; }


Input: Returns an array of all of the arguments shifted into the correct place . [CODESPLIT] function ( expected , args , minimum ) { var shiftedArgs = [ ] ; var curArg = args . length - 1 ; var remainingOptionalArgs = expected . length - minimum ; var optionalIndiceSegments = [ ] ; var optionalIndiceSegment = [ ] ; var availableArgsSegments = [ ] ; var availableArgsSegment = [ ] ; // Fill the return array with nulls first. for ( var i = 0 ; i < expected . length ; i ++ ) shiftedArgs [ i ] = null ; // Capture groups of available arguments separated by ones that have been used. var advanceArg = function ( ) { availableArgsSegment . unshift ( curArg ) ; curArg -- ; remainingOptionalArgs -- ; if ( curArg < 0 || remainingOptionalArgs < 0 ) { throw Error ( getExpectedVsRecieved_ ( expected , args ) ) ; } } ; // Fill in all of the required types, starting from the last expected argument and working // towards the first. for ( i = expected . length - 1 ; i >= 0 ; i -- ) { var type = expected [ i ] ; if ( isOptionalType ( type ) ) { optionalIndiceSegment . unshift ( i ) ; continue ; } // Keep moving down the line of arguments until one matches. while ( ! isOfType ( args [ curArg ] , type ) ) { advanceArg ( ) ; } // Check if this argument should be left for a trailing optional argument. if ( checkIfShouldLeaveArgument_ ( expected , i , args , curArg ) ) { // Found enough matches to let this be an optional argument. Advance the argument and // then restart on this same function. advanceArg ( ) ; i ++ ; continue ; } // Capture groups of optional arguments separated by required arguments. optionalIndiceSegments . unshift ( optionalIndiceSegment ) ; optionalIndiceSegment = [ ] ; availableArgsSegments . unshift ( availableArgsSegment ) ; availableArgsSegment = [ ] shiftedArgs [ i ] = args [ curArg -- ] ; } // Now that we have found all the required arguments, group the rest for processing with optional // arguments. while ( curArg >= 0 ) availableArgsSegment . unshift ( curArg -- ) ; availableArgsSegments . unshift ( availableArgsSegment ) ; optionalIndiceSegments . unshift ( optionalIndiceSegment ) ; // Make sure that the optional argument count matches up correctly. if ( availableArgsSegments . length != optionalIndiceSegments . length ) { throw Error ( getExpectedVsRecieved_ ( expected , args ) ) ; } // Go through all the optional segments and argument segments to match up the optional arguments. optionalIndiceSegments . forEach ( function ( optionalIndices , index ) { availableArgsSegment = availableArgsSegments [ index ] ; i = 0 ; availableArgsSegment . forEach ( function ( argIndex ) { arg = args [ argIndex ] // Skip forward until we find an optional expected argument that matches. while ( ! isOfType ( arg , expected [ optionalIndices [ i ] ] ) && i < optionalIndices . length ) { i ++ ; } // If none match then the arguments are invalid. if ( i >= optionalIndices . length ) { throw Error ( getExpectedVsRecieved_ ( expected , args ) ) ; } // Success! This is an optional expected argument. shiftedArgs [ optionalIndices [ i ++ ] ] = arg ; } ) ; } ) ; return shiftedArgs ; }


Input: Capture groups of available arguments separated by ones that have been used . [CODESPLIT] function ( ) { availableArgsSegment . unshift ( curArg ) ; curArg -- ; remainingOptionalArgs -- ; if ( curArg < 0 || remainingOptionalArgs < 0 ) { throw Error ( getExpectedVsRecieved_ ( expected , args ) ) ; } }


Input: Checks if the current argument should be left for an optional argument . [CODESPLIT] function ( expected , expectedIndex , actual , actualIndex ) { // Check how many optional types in front of this argument that match the current value. var consecutiveOptionals = countTrailingOptionals_ ( expected , expectedIndex , actual [ actualIndex ] ) ; // Check how many required types are behind this argument that match the current value. We // will then use this value to determine if the current argument can be allowed to fill an // optional spot instead of a required one. var matchingRequires = countLeadingMatchingRequires_ ( expected , expectedIndex , actual [ actualIndex ] ) ; // Now that we have found the consecutive matching types, more forward through the arguments // to see if there are enough to fill the option types. var matchesRequired = 1 + matchingRequires ; var availableDistance = matchingRequires + consecutiveOptionals ; // Determine if there are enough optional arguments. var i = actualIndex - 1 ; var type = expected [ expectedIndex ] ; while ( i >= 0 && availableDistance > 0 && matchesRequired > 0 ) { if ( isOfType ( actual [ i ] , type ) ) { matchesRequired -- ; } availableDistance -- ; i -- ; } return matchesRequired <= 0 ; }


Input: Counts the number of trailing consecutive optional arguments . [CODESPLIT] function ( expected , expectedIndex , value ) { var i = expectedIndex + 1 ; var matchingOptionals = 0 ; var inBetweenOptionals = 0 ; var tmpInBetween = 0 ; while ( i < expected . length && isOptionalType ( expected [ i ] ) ) { if ( isOfType ( value , expected [ i ] ) ) { matchingOptionals ++ ; inBetweenOptionals += tmpInBetween ; tmpInBetween = 0 ; } else { tmpInBetween ++ ; } i ++ ; } return matchingOptionals + inBetweenOptionals ; }


Input: Counts the number of leading required arguments . [CODESPLIT] function ( expected , expectedIndex , value ) { var i = expectedIndex - 1 ; var matchingRequires = 0 while ( i >= 0 ) { if ( ! isOptionalType ( expected [ i ] ) && isOfType ( value , expected [ i ] ) ) { matchingRequires ++ ; } i -- ; } return matchingRequires ; }


Input: Returns a string of expected arguments vs actual . [CODESPLIT] function ( expected , actual ) { var argNames = [ ] ; var expectedNames = [ ] ; for ( var i = 0 ; i < actual . length ; i ++ ) { argNames . push ( getNameForValue ( actual [ i ] ) ) ; } ; for ( var i = 0 ; i < expected . length ; i ++ ) { expectedNames . push ( getNameForType ( expected [ i ] ) ) ; } ; return 'Expected arguments to be (' + expectedNames . join ( ', ' ) + ') but received (' + argNames . join ( ', ' ) + ') instead.' ; }


Input: Asserts that the supplied value is of the supplied type . [CODESPLIT] function ( value , type ) { if ( ! isValidType ( type ) ) { throw Error ( 'Invalid type supplied.' ) ; } if ( ! isOfType ( value , type ) ) { argName = getNameForValue ( value ) ; typeName = getNameForType ( type ) ; throw Error ( 'Expected ' + argName + ' to be an instance of ' + typeName + '.' ) ; } }


Input: Determines if the argument is a valid type . [CODESPLIT] function ( type ) { if ( type === null ) return true ; if ( type === undefined ) return true ; if ( type instanceof AnyType ) return true ; if ( type instanceof Array ) { // An array is only valid if it contains one or more valid types. if ( ! type . length ) return false ; for ( var i = 0 ; i < type . length ; i ++ ) { if ( ! isValidType ( type [ i ] ) ) return false ; } ; return true ; } if ( type instanceof ArrayOf ) return isValidType ( type . type ) ; if ( type instanceof EnumType ) return ( type . enumerable instanceof Object ) ; return ( type instanceof Object ) ; }


Input: Gets the pretty name for the type of the value . [CODESPLIT] function ( value ) { if ( value === undefined ) return 'undefined' ; if ( value === null ) return 'null' ; // Look inside the array to determine the inner type. if ( value instanceof Array ) { if ( ! value . length ) return 'Array(empty)' ; var innerType = undefined ; for ( var i = 0 ; i < value . length ; i ++ ) { type = getNameForValue ( value [ i ] ) ; if ( innerType !== undefined && innerType !== type ) { return 'Array(mixed)' ; } innerType = type ; } ; return 'Array<' + innerType + '>' ; } if ( value instanceof Function ) { if ( value . name ) return value . name ; return 'Anonymous function' ; } // Try and use the constructor to find the name of the type. if ( value instanceof Object ) { if ( value . constructor ) return value . constructor . name ; return 'Object' ; } // No other way to determine the name of the type, just capitilize the typeof value. name = typeof value ; return name [ 0 ] . toUpperCase ( ) + name . substring ( 1 ) ; }


Input: Gets the pretty name for the type . [CODESPLIT] function ( type ) { if ( type === undefined ) return 'undefined' ; if ( type === null ) return 'null' ; // Create a list of all the possible types. if ( type instanceof Array ) { if ( ! type . length ) return 'None' ; var possibleTypes = [ ] ; for ( var i = 0 ; i < type . length ; i ++ ) { possibleTypes . push ( getNameForType ( type [ i ] ) ) ; } ; return possibleTypes . join ( ' or ' ) ; } // Look inside the array to determine the inner type. if ( type instanceof ArrayOf ) { return 'Array<' + getNameForType ( type . type ) + '>' ; } // All types should be functions. if ( type instanceof Function ) return type . name return 'Invalid type' ; }


Input: Performs the read request to the remote domain . JsonP proxy does not actually create an Ajax request instead we write out a <script > tag based on the configuration of the internal Ext . data . Request object [CODESPLIT] function ( operation , callback , scope ) { // <debug> var action = operation . getAction ( ) ; if ( action !== 'read' ) { Ext . Logger . error ( 'JsonP proxies can only be used to read data.' ) ; } // </debug> //generate the unique IDs for this request var me = this , request = me . buildRequest ( operation ) , params = request . getParams ( ) ; // apply JsonP proxy-specific attributes to the Request request . setConfig ( { callbackKey : me . getCallbackKey ( ) , timeout : me . getTimeout ( ) , scope : me , callback : me . createRequestCallback ( request , operation , callback , scope ) } ) ; // Prevent doubling up because the params are already added to the url in buildUrl if ( me . getAutoAppendParams ( ) ) { request . setParams ( { } ) ; } request . setJsonP ( Ext . data . JsonP . request ( request . getCurrentConfig ( ) ) ) ; // Set the params back once we have made the request though request . setParams ( params ) ; operation . setStarted ( ) ; me . lastRequest = request ; return request ; }


Input: Generates a url based on a given Ext . data . Request object . Adds the params and callback function name to the url [CODESPLIT] function ( request ) { var me = this , url = me . callParent ( arguments ) , params = Ext . apply ( { } , request . getParams ( ) ) , filters = params . filters , filter , i , value ; delete params . filters ; if ( me . getAutoAppendParams ( ) ) { url = Ext . urlAppend ( url , Ext . Object . toQueryString ( params ) ) ; } if ( filters && filters . length ) { for ( i = 0 ; i < filters . length ; i ++ ) { filter = filters [ i ] ; value = filter . getValue ( ) ; if ( value ) { url = Ext . urlAppend ( url , filter . getProperty ( ) + "=" + value ) ; } } } return url ; }


Input: Retreive the state object descriptor from its name [CODESPLIT] function getStateFromOptions ( options , propertyName ) { propertyName = propertyName || 'state' ; const stateName = options [ propertyName ] || options . resource . defaultState ; let stateObj = options . resource . states [ stateName ] || { validate : false } ; stateObj . name = stateName ; return stateObj ; }


Input: Validate a document against its resource [CODESPLIT] function validate ( resource , doc , doValidate ) { return new Promise ( ( resolve , reject ) => { if ( doValidate !== true ) { return resolve ( ) ; } if ( resource . validate ( doc ) ) { return resolve ( ) ; } else { debug ( 'model have %d error(s)' , resource . validate . errors . length ) ; return reject ( resource . validate . errors ) ; } } ) ; }


Input: trims end of string can trimmed back to next clean word or add suffix to end of trimmed string [CODESPLIT] function prune ( str , max , nice , suf ) { max = max || 140 nice = _ . isBoolean ( nice ) ? nice : false if ( ! str || max <= 0 || str . length <= max ) return str suf = suf || "..." str = str . substr ( 0 , max ) return nice ? str . substr ( 0 , Math . min ( str . length , str . lastIndexOf ( " " ) ) ) + suf : str }


Input: Attempt to validate the less file [CODESPLIT] function attemptRender ( reporter , filename , src , resolve , reject , globals ) { globals = globals || { } ; less . render ( src , { // Specify search paths for @import directives paths : [ "public/static/less" ] , // Specify a filename, for better error messages filename : filename , modifyVars : globals , compress : false } , function ( e , css ) { if ( e ) { if ( ( / ^variable @(.+?) is undefined$ / ) . test ( e . message ) ) { // ignore undef variable globals [ ( / ^variable @(.+?) is undefined$ / ) . exec ( e . message ) [ 1 ] ] = "1" ; attemptRender ( reporter , filename , src , resolve , reject , globals ) ; return ; } reporter ( "LESS" , filename , e . line , e . message ) ; reject ( ) ; return ; } resolve ( { filename : filename , src : css . css || css } ) ; } ) ; }


Input: Validate the given value and make sure it is valid array indexes . The value must be a valid String [CODESPLIT] function validateArray ( indexes ) { var valid = false ; if ( typeof indexes === 'string' ) { if ( indexes . match ( TYPE_ARRAY_REGEX ) ) { valid = true ; } } return valid ; }


Input: Add ALL the routes! [CODESPLIT] function addRoutes ( pies , pie , routes , app ) { // Add the GET routes if ( 'get' in routes ) { routes . get . forEach ( function ( route ) { Object . keys ( route ) . forEach ( function ( r ) { var middlewares = true ; if ( typeof route [ r ] === 'string' ) { middlewares = false ; } loadRoute ( app , 'get' , r , pies [ pie ] . path , route [ r ] , middlewares ) ; } ) ; } ) ; } // Add the POST routes if ( 'post' in routes ) { routes . post . forEach ( function ( route ) { Object . keys ( route ) . forEach ( function ( r ) { var middlewares = true ; if ( typeof route [ r ] === 'string' ) { middlewares = false ; } loadRoute ( app , 'post' , r , pies [ pie ] . path , route [ r ] , middlewares ) ; } ) ; } ) ; } }


Input: Load * one * route [CODESPLIT] function loadRoute ( app , method , route , piePath , fn , middleware ) { var middlewares = [ ] ; // If there is some middleware, load it if ( middleware ) { middlewares = fn . middlewares . map ( function ( middleware ) { return require ( path . join ( process . cwd ( ) , 'middlewares' , 'middlewares.js' ) ) [ middleware ] ; } ) ; // Also, let's not forget to change the function to call fn = fn . method ; } // Then, load the route app [ method ] ( route , middlewares , require ( path . join ( process . cwd ( ) , 'pies' , piePath , 'controller.js' ) ) [ fn ] ) ; }


Input: Generates a unique 36 character hyphenated GUID [CODESPLIT] function generateUUID ( ) { let dat = new Date ( ) . getTime ( ) ; return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx' . replace ( / [xy] / g , ( cha ) => { const ran = ( dat + ( Math . random ( ) * 16 ) ) % 16 | 0 ; dat = Math . floor ( dat / 16 ) ; return ( cha === 'x' ? ran : ran & 0x3 | 0x8 ) . toString ( 16 ) ; } ) ; }


Input: Generates a random string of text of a given length . Will generate an alpha - numeric string unless you specify a different character set as the second argument [CODESPLIT] function randomString ( length , charSet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' ) { let str = '' , isAllNumeric = false , isNegative = false , useCharSet = charSet ; if ( + length ) { if ( ! isString ( charSet ) ) { if ( isNumber ( charSet ) ) { if ( + charSet ) { isAllNumeric = true ; isNegative = + charSet < 0 ; useCharSet = ` ${ Math . abs ( + charSet ) } ` ; } else { useCharSet = ALPHANUMERIC_CHARS ; } } else { useCharSet = ALPHANUMERIC_CHARS ; } } const generateChar = function gc ( len ) { return Math . round ( Math . random ( ) * ( len - 1 ) ) ; } . bind ( null , useCharSet . length ) ; str = Array ( + length ) . fill ( ) . map ( ( v , index ) => { const newChar = generateChar ( ) ; /* If we are generating a random number, make sure the first digit is not zero */ if ( ! index && isAllNumeric && ! newChar ) { return useCharSet . charAt ( newChar + 1 ) ; } return useCharSet . charAt ( newChar ) ; } ) . join ( '' ) ; } if ( isAllNumeric ) { return isNegative ? - + str : + str ; } return str ; }


Input: Converts a string value to Uint8array [CODESPLIT] function toUint ( str ) { const string = window . btoa ( unescape ( encodeURIComponent ( str ) ) ) , chars = string . split ( '' ) , len = chars . length , uintArray = [ ] ; Array ( len ) . fill ( ) . forEach ( ( val , i ) => uintArray . push ( chars [ i ] . charCodeAt ( 0 ) ) ) ; return new Uint8Array ( uintArray ) ; }


Input: Converts a string value to an ArrayBuffer [CODESPLIT] function toArrayBuffer ( str ) { /* eslint no-bitwise: "off" */ const len = isString ( str ) ? str . length : 0 , buf = new ArrayBuffer ( len ) , view = new Uint8Array ( buf ) ; Array ( len ) . fill ( ) . forEach ( ( val , i ) => ( view [ i ] = str . charCodeAt ( i ) & 0xFF ) ) ; return view ; }


Input: This is called when an Item is added to the BackButtonContainer of a SplitNavigation View @private [CODESPLIT] function ( toolbar , item ) { item . on ( { scope : this , show : this . refreshBackButtonContainer , hide : this . refreshBackButtonContainer } ) ; this . refreshBackButtonContainer ( ) ; }


Input: This is called when an Item is removed from the BackButtonContainer of a SplitNavigation View @private [CODESPLIT] function ( toolbar , item ) { item . un ( { scope : this , show : this . refreshBackButtonContainer , hide : this . refreshBackButtonContainer } ) ; this . refreshBackButtonContainer ( ) ; }


Input: This is used for Blackberry SplitNavigation to monitor the state of child items in the bottom toolbar . if no visible children exist the toolbar will be hidden [CODESPLIT] function ( ) { if ( ! this . $backButtonContainer ) { return ; } var i = 0 , backButtonContainer = this . $backButtonContainer , items = backButtonContainer . items , item ; for ( ; i < items . length ; i ++ ) { item = items . get ( i ) ; if ( ! item . isHidden ( ) ) { this . $backButtonContainer . show ( ) ; return ; } } this . $backButtonContainer . hide ( ) ; }